aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2011-03-02 21:24:56 +0000
committerJon Leighton <j@jonathanleighton.com>2011-03-04 09:30:27 +0000
commit735844db712c511dd8abf36a5279318fbc0ff9d0 (patch)
tree5fbd5d224ef85d8c878bf221db98b422c9345466
parent9a98c766e045aebc2ef6d5b716936b73407f095d (diff)
parentb171b9e73dcc6a89b1da652da61c5127fe605b51 (diff)
downloadrails-735844db712c511dd8abf36a5279318fbc0ff9d0.tar.gz
rails-735844db712c511dd8abf36a5279318fbc0ff9d0.tar.bz2
rails-735844db712c511dd8abf36a5279318fbc0ff9d0.zip
Merge branch 'master' into nested_has_many_through
Conflicts: activerecord/CHANGELOG activerecord/lib/active_record/association_preload.rb activerecord/lib/active_record/associations.rb activerecord/lib/active_record/associations/class_methods/join_dependency.rb activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb activerecord/lib/active_record/associations/has_many_association.rb activerecord/lib/active_record/associations/has_many_through_association.rb activerecord/lib/active_record/associations/has_one_association.rb activerecord/lib/active_record/associations/has_one_through_association.rb activerecord/lib/active_record/associations/through_association_scope.rb activerecord/lib/active_record/reflection.rb activerecord/test/cases/associations/has_many_through_associations_test.rb activerecord/test/cases/associations/has_one_through_associations_test.rb activerecord/test/cases/reflection_test.rb activerecord/test/cases/relations_test.rb activerecord/test/fixtures/memberships.yml activerecord/test/models/categorization.rb activerecord/test/models/category.rb activerecord/test/models/member.rb activerecord/test/models/reference.rb activerecord/test/models/tagging.rb
-rw-r--r--.gitignore2
-rw-r--r--Gemfile25
-rw-r--r--README.rdoc4
-rwxr-xr-xRakefile29
-rw-r--r--actionmailer/MIT-LICENSE2
-rw-r--r--actionmailer/README.rdoc2
-rwxr-xr-xactionmailer/Rakefile2
-rw-r--r--actionmailer/actionmailer.gemspec2
-rw-r--r--actionmailer/lib/action_mailer.rb2
-rw-r--r--actionmailer/lib/action_mailer/base.rb19
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb28
-rw-r--r--actionmailer/lib/action_mailer/old_api.rb6
-rw-r--r--actionmailer/lib/action_mailer/tmail_compat.rb21
-rw-r--r--actionmailer/test/abstract_unit.rb3
-rw-r--r--actionmailer/test/asset_host_test.rb4
-rw-r--r--actionmailer/test/base_test.rb6
-rw-r--r--actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb4
-rw-r--r--actionmailer/test/i18n_with_controller_test.rb46
-rw-r--r--actionmailer/test/old_base/tmail_compat_test.rb9
-rw-r--r--actionpack/CHANGELOG21
-rw-r--r--actionpack/MIT-LICENSE2
-rw-r--r--actionpack/README.rdoc2
-rw-r--r--actionpack/actionpack.gemspec4
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb2
-rw-r--r--actionpack/lib/abstract_controller/layouts.rb4
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb36
-rw-r--r--actionpack/lib/action_controller/base.rb2
-rw-r--r--actionpack/lib/action_controller/caching/actions.rb8
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb58
-rw-r--r--actionpack/lib/action_controller/caching/pages.rb2
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb6
-rw-r--r--actionpack/lib/action_controller/metal.rb63
-rw-r--r--actionpack/lib/action_controller/metal/implicit_render.rb4
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb12
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb37
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb2
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb21
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb6
-rw-r--r--actionpack/lib/action_controller/railties/paths.rb8
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb2
-rw-r--r--actionpack/lib/action_dispatch.rb3
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb6
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb7
-rw-r--r--actionpack/lib/action_dispatch/middleware/callbacks.rb35
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb24
-rw-r--r--actionpack/lib/action_dispatch/middleware/reloader.rb76
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb24
-rw-r--r--actionpack/lib/action_dispatch/middleware/stack.rb58
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb8
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb8
-rw-r--r--actionpack/lib/action_dispatch/routing.rb12
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb331
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb8
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb13
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb6
-rw-r--r--actionpack/lib/action_pack.rb2
-rw-r--r--actionpack/lib/action_view.rb2
-rw-r--r--actionpack/lib/action_view/base.rb14
-rw-r--r--actionpack/lib/action_view/helpers.rb4
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb22
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb2
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb23
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb7
-rw-r--r--actionpack/lib/action_view/helpers/cache_helper.rb26
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb22
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb49
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb81
-rw-r--r--actionpack/lib/action_view/helpers/number_helper.rb5
-rw-r--r--actionpack/lib/action_view/helpers/output_safety_helper.rb38
-rw-r--r--actionpack/lib/action_view/helpers/raw_output_helper.rb18
-rw-r--r--actionpack/lib/action_view/helpers/tag_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb9
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb27
-rw-r--r--actionpack/lib/action_view/lookup_context.rb40
-rw-r--r--actionpack/lib/action_view/partials.rb22
-rw-r--r--actionpack/lib/action_view/path_set.rb12
-rw-r--r--actionpack/lib/action_view/railtie.rb10
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb10
-rw-r--r--actionpack/lib/action_view/renderer/template_renderer.rb8
-rw-r--r--actionpack/lib/action_view/template.rb4
-rw-r--r--actionpack/lib/action_view/template/error.rb13
-rw-r--r--actionpack/lib/action_view/template/resolver.rb34
-rw-r--r--actionpack/lib/action_view/test_case.rb5
-rw-r--r--actionpack/lib/action_view/testing/resolvers.rb6
-rw-r--r--actionpack/test/abstract/abstract_controller_test.rb14
-rw-r--r--actionpack/test/abstract/callbacks_test.rb43
-rw-r--r--actionpack/test/abstract/render_test.rb4
-rw-r--r--actionpack/test/activerecord/render_partial_with_record_identification_test.rb6
-rw-r--r--actionpack/test/controller/caching_test.rb18
-rw-r--r--actionpack/test/controller/filters_test.rb10
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb23
-rw-r--r--actionpack/test/controller/mime_responds_test.rb4
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb2
-rw-r--r--actionpack/test/controller/new_base/content_negotiation_test.rb9
-rw-r--r--actionpack/test/controller/new_base/render_once_test.rb8
-rw-r--r--actionpack/test/controller/new_base/render_partial_test.rb25
-rw-r--r--actionpack/test/controller/new_base/render_test.rb42
-rw-r--r--actionpack/test/controller/render_json_test.rb10
-rw-r--r--actionpack/test/controller/render_test.rb10
-rw-r--r--actionpack/test/controller/request/test_request_test.rb3
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb207
-rw-r--r--actionpack/test/controller/routing_test.rb4
-rw-r--r--actionpack/test/controller/url_for_test.rb15
-rw-r--r--actionpack/test/controller/webservice_test.rb2
-rw-r--r--actionpack/test/dispatch/callbacks_test.rb74
-rw-r--r--actionpack/test/dispatch/cookies_test.rb102
-rw-r--r--actionpack/test/dispatch/middleware_stack/middleware_test.rb77
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb7
-rw-r--r--actionpack/test/dispatch/reloader_test.rb138
-rw-r--r--actionpack/test/dispatch/request_test.rb2
-rw-r--r--actionpack/test/dispatch/response_test.rb10
-rw-r--r--actionpack/test/dispatch/routing_assertions_test.rb103
-rw-r--r--actionpack/test/dispatch/routing_test.rb81
-rw-r--r--actionpack/test/dispatch/session/cookie_store_test.rb1
-rw-r--r--actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb4
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb75
-rw-r--r--actionpack/test/template/date_helper_test.rb43
-rw-r--r--actionpack/test/template/form_helper_test.rb56
-rw-r--r--actionpack/test/template/form_options_helper_test.rb32
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb51
-rw-r--r--actionpack/test/template/html-scanner/sanitizer_test.rb7
-rw-r--r--actionpack/test/template/log_subscriber_test.rb6
-rw-r--r--actionpack/test/template/lookup_context_test.rb72
-rw-r--r--actionpack/test/template/number_helper_test.rb5
-rw-r--r--actionpack/test/template/output_safety_helper_test.rb30
-rw-r--r--actionpack/test/template/raw_output_helper_test.rb21
-rw-r--r--actionpack/test/template/render_test.rb12
-rw-r--r--actionpack/test/template/template_error_test.rb13
-rw-r--r--actionpack/test/template/template_test.rb4
-rw-r--r--actionpack/test/template/test_case_test.rb23
-rw-r--r--actionpack/test/template/text_helper_test.rb8
-rw-r--r--actionpack/test/template/url_helper_test.rb17
-rw-r--r--activemodel/CHANGELOG7
-rw-r--r--activemodel/MIT-LICENSE2
-rw-r--r--activemodel/README.rdoc8
-rwxr-xr-xactivemodel/Rakefile2
-rw-r--r--activemodel/activemodel.gemspec1
-rw-r--r--activemodel/lib/active_model.rb3
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb60
-rw-r--r--activemodel/lib/active_model/callbacks.rb7
-rw-r--r--activemodel/lib/active_model/dirty.rb1
-rw-r--r--activemodel/lib/active_model/errors.rb75
-rw-r--r--activemodel/lib/active_model/mass_assignment_security.rb38
-rw-r--r--activemodel/lib/active_model/naming.rb17
-rw-r--r--activemodel/lib/active_model/observing.rb17
-rw-r--r--activemodel/lib/active_model/secure_password.rb66
-rw-r--r--activemodel/lib/active_model/serialization.rb4
-rw-r--r--activemodel/lib/active_model/serializers/xml.rb23
-rw-r--r--activemodel/lib/active_model/translation.rb2
-rw-r--r--activemodel/lib/active_model/validations.rb24
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb6
-rw-r--r--activemodel/lib/active_model/validations/callbacks.rb2
-rw-r--r--activemodel/lib/active_model/validations/confirmation.rb5
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb3
-rw-r--r--activemodel/lib/active_model/validations/format.rb4
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb18
-rw-r--r--activemodel/lib/active_model/validations/length.rb4
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb4
-rw-r--r--activemodel/lib/active_model/validations/presence.rb5
-rw-r--r--activemodel/lib/active_model/validations/validates.rb19
-rw-r--r--activemodel/lib/active_model/validations/with.rb12
-rw-r--r--activemodel/test/cases/attribute_methods_test.rb38
-rw-r--r--activemodel/test/cases/callbacks_test.rb4
-rw-r--r--activemodel/test/cases/errors_test.rb12
-rw-r--r--activemodel/test/cases/secure_password_test.rb45
-rw-r--r--activemodel/test/cases/serializeration/xml_serialization_test.rb2
-rw-r--r--activemodel/test/cases/translation_test.rb7
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb19
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb9
-rw-r--r--activemodel/test/cases/validations/validates_test.rb30
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb21
-rw-r--r--activemodel/test/cases/validations_test.rb28
-rw-r--r--activemodel/test/models/administrator.rb10
-rw-r--r--activemodel/test/models/person.rb7
-rw-r--r--activemodel/test/models/topic.rb12
-rw-r--r--activemodel/test/models/user.rb8
-rw-r--r--activemodel/test/models/visitor.rb9
-rw-r--r--activemodel/test/validators/namespace/email_validator.rb6
-rw-r--r--activerecord/CHANGELOG178
-rw-r--r--activerecord/MIT-LICENSE2
-rw-r--r--activerecord/README.rdoc4
-rw-r--r--activerecord/RUNNING_UNIT_TESTS6
-rwxr-xr-xactiverecord/Rakefile13
-rw-r--r--activerecord/examples/performance.rb197
-rw-r--r--activerecord/lib/active_record.rb8
-rw-r--r--activerecord/lib/active_record/aggregations.rb65
-rw-r--r--activerecord/lib/active_record/association_preload.rb421
-rw-r--r--activerecord/lib/active_record/associations.rb761
-rw-r--r--activerecord/lib/active_record/associations/alias_tracker.rb52
-rw-r--r--activerecord/lib/active_record/associations/association.rb262
-rw-r--r--activerecord/lib/active_record/associations/association_collection.rb558
-rw-r--r--activerecord/lib/active_record/associations/association_proxy.rb314
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb98
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb74
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb53
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb83
-rw-r--r--activerecord/lib/active_record/associations/builder/collection_association.rb75
-rw-r--r--activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb63
-rw-r--r--activerecord/lib/active_record/associations/builder/has_many.rb63
-rw-r--r--activerecord/lib/active_record/associations/builder/has_one.rb61
-rw-r--r--activerecord/lib/active_record/associations/builder/singular_association.rb32
-rw-r--r--activerecord/lib/active_record/associations/class_methods/join_dependency.rb216
-rw-r--r--activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb258
-rw-r--r--activerecord/lib/active_record/associations/class_methods/join_dependency/join_base.rb26
-rw-r--r--activerecord/lib/active_record/associations/class_methods/join_dependency/join_part.rb80
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb549
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb127
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb141
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb121
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb159
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb155
-rw-r--r--activerecord/lib/active_record/associations/has_one_through_association.rb46
-rw-r--r--activerecord/lib/active_record/associations/join_dependency.rb215
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_association.rb259
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_base.rb24
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_part.rb78
-rw-r--r--activerecord/lib/active_record/associations/preloader.rb177
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb126
-rw-r--r--activerecord/lib/active_record/associations/preloader/belongs_to.rb17
-rw-r--r--activerecord/lib/active_record/associations/preloader/collection_association.rb24
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb58
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many.rb17
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many_through.rb15
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_one.rb23
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_one_through.rb9
-rw-r--r--activerecord/lib/active_record/associations/preloader/singular_association.rb21
-rw-r--r--activerecord/lib/active_record/associations/preloader/through_association.rb67
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb55
-rw-r--r--activerecord/lib/active_record/associations/through_association.rb281
-rw-r--r--activerecord/lib/active_record/associations/through_association_scope.rb300
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb24
-rw-r--r--activerecord/lib/active_record/attribute_methods/dirty.rb5
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb34
-rw-r--r--activerecord/lib/active_record/attribute_methods/read.rb24
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb5
-rw-r--r--activerecord/lib/active_record/autosave_association.rb107
-rw-r--r--activerecord/lib/active_record/base.rb232
-rw-r--r--activerecord/lib/active_record/callbacks.rb26
-rw-r--r--activerecord/lib/active_record/coders/yaml_column.rb41
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb65
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb49
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb258
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb90
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb21
-rw-r--r--activerecord/lib/active_record/connection_adapters/column.rb268
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb610
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb132
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb22
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb43
-rw-r--r--activerecord/lib/active_record/counter_cache.rb2
-rw-r--r--activerecord/lib/active_record/fixtures.rb342
-rw-r--r--activerecord/lib/active_record/identity_map.rb102
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb14
-rw-r--r--activerecord/lib/active_record/locking/pessimistic.rb2
-rw-r--r--activerecord/lib/active_record/log_subscriber.rb16
-rw-r--r--activerecord/lib/active_record/migration/command_recorder.rb20
-rw-r--r--activerecord/lib/active_record/named_scope.rb5
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb30
-rw-r--r--activerecord/lib/active_record/observer.rb9
-rw-r--r--activerecord/lib/active_record/persistence.rb23
-rw-r--r--activerecord/lib/active_record/railtie.rb16
-rw-r--r--activerecord/lib/active_record/railties/databases.rake8
-rw-r--r--activerecord/lib/active_record/reflection.rb83
-rw-r--r--activerecord/lib/active_record/relation.rb77
-rw-r--r--activerecord/lib/active_record/relation/batches.rb8
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb32
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb27
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb11
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb78
-rw-r--r--activerecord/lib/active_record/relation/spawn_methods.rb22
-rw-r--r--activerecord/lib/active_record/result.rb6
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb2
-rw-r--r--activerecord/lib/active_record/serializers/xml_serializer.rb20
-rw-r--r--activerecord/lib/active_record/session_store.rb2
-rw-r--r--activerecord/lib/active_record/test_case.rb11
-rw-r--r--activerecord/lib/active_record/timestamp.rb24
-rw-r--r--activerecord/lib/active_record/transactions.rb25
-rw-r--r--activerecord/lib/active_record/validations.rb20
-rw-r--r--activerecord/lib/active_record/validations/associated.rb4
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb17
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/migration.rb8
-rw-r--r--activerecord/lib/rails/generators/active_record/model/model_generator.rb1
-rw-r--r--activerecord/lib/rails/generators/active_record/model/templates/migration.rb11
-rw-r--r--activerecord/test/active_record/connection_adapters/fake_adapter.rb36
-rw-r--r--activerecord/test/cases/adapter_test.rb12
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql/reserved_word_test.rb24
-rw-r--r--activerecord/test/cases/adapters/mysql2/reserved_word_test.rb18
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb5
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb233
-rw-r--r--activerecord/test/cases/associations/callbacks_test.rb9
-rw-r--r--activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb1
-rw-r--r--activerecord/test/cases/associations/eager_load_nested_include_test.rb2
-rw-r--r--activerecord/test/cases/associations/eager_test.rb114
-rw-r--r--activerecord/test/cases/associations/extension_test.rb23
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb126
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb80
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb316
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb139
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb71
-rw-r--r--activerecord/test/cases/associations/identity_map_test.rb137
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb16
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb112
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb49
-rw-r--r--activerecord/test/cases/associations/nested_through_associations_test.rb258
-rw-r--r--activerecord/test/cases/associations_test.rb44
-rw-r--r--activerecord/test/cases/attribute_methods/read_test.rb61
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb52
-rw-r--r--activerecord/test/cases/autosave_association_test.rb306
-rw-r--r--activerecord/test/cases/base_test.rb164
-rw-r--r--activerecord/test/cases/batches_test.rb1
-rw-r--r--activerecord/test/cases/bind_parameter_test.rb90
-rw-r--r--activerecord/test/cases/calculations_test.rb41
-rw-r--r--activerecord/test/cases/coders/yaml_column_test.rb46
-rw-r--r--activerecord/test/cases/column_definition_test.rb206
-rw-r--r--activerecord/test/cases/connection_pool_test.rb72
-rw-r--r--activerecord/test/cases/custom_locking_test.rb17
-rw-r--r--activerecord/test/cases/finder_test.rb2
-rw-r--r--activerecord/test/cases/fixtures_test.rb38
-rw-r--r--activerecord/test/cases/habtm_destroy_order_test.rb17
-rw-r--r--activerecord/test/cases/helper.rb81
-rw-r--r--activerecord/test/cases/identity_map_test.rb402
-rw-r--r--activerecord/test/cases/inheritance_test.rb8
-rw-r--r--activerecord/test/cases/lifecycle_test.rb27
-rw-r--r--activerecord/test/cases/locking_test.rb61
-rw-r--r--activerecord/test/cases/method_scoping_test.rb10
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb2
-rw-r--r--activerecord/test/cases/migration_test.rb146
-rw-r--r--activerecord/test/cases/modules_test.rb1
-rw-r--r--activerecord/test/cases/named_scope_test.rb48
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb25
-rw-r--r--activerecord/test/cases/pooled_connections_test.rb2
-rw-r--r--activerecord/test/cases/query_cache_test.rb2
-rw-r--r--activerecord/test/cases/quoting_test.rb4
-rw-r--r--activerecord/test/cases/readonly_test.rb38
-rw-r--r--activerecord/test/cases/reflection_test.rb29
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb24
-rw-r--r--activerecord/test/cases/relations_test.rb110
-rw-r--r--activerecord/test/cases/serialization_test.rb6
-rw-r--r--activerecord/test/cases/session_store/session_test.rb3
-rw-r--r--activerecord/test/cases/timestamp_test.rb30
-rw-r--r--activerecord/test/cases/transactions_test.rb16
-rw-r--r--activerecord/test/cases/unconnected_test.rb3
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb13
-rw-r--r--activerecord/test/cases/xml_serialization_test.rb6
-rw-r--r--activerecord/test/cases/yaml_serialization_test.rb26
-rw-r--r--activerecord/test/connections/native_sqlite3/connection.rb9
-rw-r--r--activerecord/test/connections/native_sqlite3/in_memory_connection.rb18
-rw-r--r--activerecord/test/connections/native_sqlite3_mem/connection.rb19
-rw-r--r--activerecord/test/fixtures/companies.yml1
-rw-r--r--activerecord/test/fixtures/dashboards.yml5
-rw-r--r--activerecord/test/fixtures/posts.yml2
-rw-r--r--activerecord/test/fixtures/ships.yml1
-rw-r--r--activerecord/test/fixtures/speedometers.yml6
-rw-r--r--activerecord/test/fixtures/subscribers.yml4
-rw-r--r--activerecord/test/fixtures/traffic_lights.yml6
-rw-r--r--activerecord/test/models/author.rb11
-rw-r--r--activerecord/test/models/bulb.rb11
-rw-r--r--activerecord/test/models/categorization.rb13
-rw-r--r--activerecord/test/models/category.rb7
-rw-r--r--activerecord/test/models/club.rb1
-rw-r--r--activerecord/test/models/comment.rb6
-rw-r--r--activerecord/test/models/company.rb36
-rw-r--r--activerecord/test/models/contact.rb10
-rw-r--r--activerecord/test/models/contract.rb2
-rw-r--r--activerecord/test/models/customer.rb2
-rw-r--r--activerecord/test/models/joke.rb4
-rw-r--r--activerecord/test/models/lesson.rb11
-rw-r--r--activerecord/test/models/member.rb11
-rw-r--r--activerecord/test/models/person.rb30
-rw-r--r--activerecord/test/models/pirate.rb6
-rw-r--r--activerecord/test/models/post.rb35
-rw-r--r--activerecord/test/models/project.rb21
-rw-r--r--activerecord/test/models/reader.rb3
-rw-r--r--activerecord/test/models/reference.rb12
-rw-r--r--activerecord/test/models/reply.rb7
-rw-r--r--activerecord/test/models/sponsor.rb5
-rw-r--r--activerecord/test/models/student.rb3
-rw-r--r--activerecord/test/models/tagging.rb2
-rw-r--r--activerecord/test/models/task.rb4
-rw-r--r--activerecord/test/models/topic.rb4
-rw-r--r--activerecord/test/models/traffic_light.rb3
-rw-r--r--activerecord/test/schema/schema.rb28
-rw-r--r--activeresource/MIT-LICENSE2
-rw-r--r--activeresource/README.rdoc2
-rwxr-xr-xactiveresource/Rakefile2
-rw-r--r--activeresource/lib/active_resource/base.rb4
-rw-r--r--activeresource/lib/active_resource/http_mock.rb17
-rw-r--r--activeresource/test/cases/http_mock_test.rb27
-rw-r--r--activeresource/test/cases/validations_test.rb6
-rw-r--r--activeresource/test/fixtures/project.rb19
-rw-r--r--activesupport/CHANGELOG11
-rw-r--r--activesupport/MIT-LICENSE2
-rw-r--r--activesupport/lib/active_support.rb1
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb51
-rw-r--r--activesupport/lib/active_support/callbacks.rb235
-rw-r--r--activesupport/lib/active_support/concern.rb2
-rw-r--r--activesupport/lib/active_support/configurable.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal/conversions.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/class/subclasses.rb54
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/date/conversions.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/date/zones.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/calculations.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/date_time/conversions.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/hash/conversions.rb16
-rw-r--r--activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/object/with_options.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/range.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/range/cover.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/time/zones.rb12
-rw-r--r--activesupport/lib/active_support/dependencies.rb73
-rw-r--r--activesupport/lib/active_support/deprecation.rb4
-rw-r--r--activesupport/lib/active_support/deprecation/behaviors.rb7
-rw-r--r--activesupport/lib/active_support/deprecation/proxy_wrappers.rb2
-rw-r--r--activesupport/lib/active_support/deprecation/reporting.rb6
-rw-r--r--activesupport/lib/active_support/duration.rb4
-rw-r--r--activesupport/lib/active_support/file_update_checker.rb2
-rw-r--r--activesupport/lib/active_support/file_watcher.rb36
-rw-r--r--activesupport/lib/active_support/gzip.rb6
-rw-r--r--activesupport/lib/active_support/i18n_railtie.rb25
-rw-r--r--activesupport/lib/active_support/inflections.rb4
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb2
-rw-r--r--activesupport/lib/active_support/json/backends/jsongem.rb6
-rw-r--r--activesupport/lib/active_support/json/backends/yajl.rb6
-rw-r--r--activesupport/lib/active_support/json/backends/yaml.rb35
-rw-r--r--activesupport/lib/active_support/json/encoding.rb8
-rw-r--r--activesupport/lib/active_support/log_subscriber/test_helper.rb3
-rw-r--r--activesupport/lib/active_support/notifications.rb17
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb21
-rw-r--r--activesupport/lib/active_support/ordered_options.rb2
-rw-r--r--activesupport/lib/active_support/testing/performance.rb2
-rw-r--r--activesupport/lib/active_support/testing/setup_and_teardown.rb8
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb14
-rw-r--r--activesupport/lib/active_support/xml_mini/libxml.rb1
-rw-r--r--activesupport/lib/active_support/xml_mini/libxmlsax.rb3
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogiri.rb1
-rw-r--r--activesupport/lib/active_support/xml_mini/nokogirisax.rb1
-rw-r--r--activesupport/lib/active_support/xml_mini/rexml.rb1
-rw-r--r--activesupport/test/buffered_logger_test.rb4
-rw-r--r--activesupport/test/callback_inheritance_test.rb2
-rw-r--r--activesupport/test/callbacks_test.rb31
-rw-r--r--activesupport/test/class_cache_test.rb108
-rw-r--r--activesupport/test/configurable_test.rb8
-rw-r--r--activesupport/test/core_ext/bigdecimal.rb10
-rw-r--r--activesupport/test/core_ext/bigdecimal_test.rb17
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb42
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb10
-rw-r--r--activesupport/test/core_ext/duration_test.rb15
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb1
-rw-r--r--activesupport/test/core_ext/module_test.rb4
-rw-r--r--activesupport/test/core_ext/numeric_ext_test.rb10
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb12
-rw-r--r--activesupport/test/core_ext/range_ext_test.rb12
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb16
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb19
-rw-r--r--activesupport/test/dependencies_test.rb8
-rw-r--r--activesupport/test/file_watcher_test.rb233
-rw-r--r--activesupport/test/gzip_test.rb13
-rw-r--r--activesupport/test/inflector_test.rb39
-rw-r--r--activesupport/test/inflector_test_cases.rb1
-rw-r--r--activesupport/test/json/decoding_test.rb16
-rw-r--r--activesupport/test/json/encoding_test.rb31
-rw-r--r--activesupport/test/notifications_test.rb9
-rw-r--r--activesupport/test/ordered_hash_test.rb40
-rw-r--r--activesupport/test/safe_buffer_test.rb22
-rw-r--r--activesupport/test/test_case_test.rb4
-rw-r--r--activesupport/test/test_xml_mini.rb123
-rwxr-xr-xci/ci_build.rb18
-rw-r--r--load_paths.rb2
-rw-r--r--railties/MIT-LICENSE2
-rwxr-xr-xrailties/Rakefile6
-rw-r--r--railties/guides/assets/stylesheets/fixes.css16
-rw-r--r--railties/guides/rails_guides.rb4
-rw-r--r--railties/guides/rails_guides/generator.rb11
-rw-r--r--railties/guides/source/2_2_release_notes.textile6
-rw-r--r--railties/guides/source/2_3_release_notes.textile2
-rw-r--r--railties/guides/source/3_0_release_notes.textile26
-rw-r--r--railties/guides/source/action_controller_overview.textile9
-rw-r--r--railties/guides/source/action_mailer_basics.textile18
-rw-r--r--railties/guides/source/action_view_overview.textile46
-rw-r--r--railties/guides/source/active_record_basics.textile2
-rw-r--r--railties/guides/source/active_record_querying.textile149
-rw-r--r--railties/guides/source/active_record_validations_callbacks.textile52
-rw-r--r--railties/guides/source/active_support_core_extensions.textile95
-rw-r--r--railties/guides/source/ajax_on_rails.textile24
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile8
-rw-r--r--railties/guides/source/association_basics.textile12
-rw-r--r--railties/guides/source/caching_with_rails.textile94
-rw-r--r--railties/guides/source/command_line.textile76
-rw-r--r--railties/guides/source/configuring.textile79
-rw-r--r--railties/guides/source/contribute.textile4
-rw-r--r--railties/guides/source/contributing_to_rails.textile311
-rw-r--r--railties/guides/source/contributing_to_ruby_on_rails.textile370
-rw-r--r--railties/guides/source/credits.html.erb4
-rw-r--r--railties/guides/source/debugging_rails_applications.textile26
-rw-r--r--railties/guides/source/form_helpers.textile42
-rw-r--r--railties/guides/source/generators.textile77
-rw-r--r--railties/guides/source/getting_started.textile24
-rw-r--r--railties/guides/source/i18n.textile46
-rw-r--r--railties/guides/source/index.html.erb6
-rw-r--r--railties/guides/source/initialization.textile3772
-rw-r--r--railties/guides/source/layout.html.erb14
-rw-r--r--railties/guides/source/layouts_and_rendering.textile36
-rw-r--r--railties/guides/source/migrations.textile20
-rw-r--r--railties/guides/source/nested_model_forms.textile4
-rw-r--r--railties/guides/source/performance_testing.textile28
-rw-r--r--railties/guides/source/plugins.textile1453
-rw-r--r--railties/guides/source/rails_application_templates.textile22
-rw-r--r--railties/guides/source/rails_on_rack.textile17
-rw-r--r--railties/guides/source/routing.textile33
-rw-r--r--railties/guides/source/ruby_on_rails_guides_guidelines.textile18
-rw-r--r--railties/guides/source/security.textile16
-rw-r--r--railties/guides/source/testing.textile14
-rw-r--r--railties/guides/w3c_validator.rb4
-rw-r--r--railties/lib/rails/application.rb13
-rw-r--r--railties/lib/rails/application/bootstrap.rb8
-rw-r--r--railties/lib/rails/application/configuration.rb25
-rw-r--r--railties/lib/rails/application/finisher.rb8
-rw-r--r--railties/lib/rails/cli.rb2
-rw-r--r--railties/lib/rails/commands.rb2
-rw-r--r--railties/lib/rails/commands/application.rb12
-rw-r--r--railties/lib/rails/commands/dbconsole.rb10
-rw-r--r--railties/lib/rails/commands/plugin.rb7
-rw-r--r--railties/lib/rails/commands/server.rb4
-rw-r--r--railties/lib/rails/console/app.rb4
-rw-r--r--railties/lib/rails/engine.rb195
-rw-r--r--railties/lib/rails/generators.rb2
-rw-r--r--railties/lib/rails/generators/app_base.rb20
-rw-r--r--railties/lib/rails/generators/base.rb4
-rw-r--r--railties/lib/rails/generators/named_base.rb6
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb20
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile9
-rw-r--r--railties/lib/rails/generators/rails/app/templates/README4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/boot.rb13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/index.html16
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js2703
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js280
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js88
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb45
-rwxr-xr-xrailties/lib/rails/generators/rails/plugin_new/templates/Rakefile9
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb5
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb2
-rw-r--r--railties/lib/rails/generators/test_case.rb2
-rw-r--r--railties/lib/rails/paths.rb8
-rw-r--r--railties/lib/rails/rack/logger.rb2
-rw-r--r--railties/lib/rails/railtie.rb54
-rw-r--r--railties/lib/rails/railtie/configurable.rb10
-rw-r--r--railties/lib/rails/tasks/engine.rake69
-rw-r--r--railties/lib/rails/test_help.rb4
-rw-r--r--railties/test/application/configuration_test.rb53
-rw-r--r--railties/test/application/console_test.rb8
-rw-r--r--railties/test/application/initializers/frameworks_test.rb4
-rw-r--r--railties/test/application/initializers/i18n_test.rb30
-rw-r--r--railties/test/application/middleware/show_exceptions_test.rb37
-rw-r--r--railties/test/application/middleware_test.rb18
-rw-r--r--railties/test/application/rake_test.rb36
-rw-r--r--railties/test/generators/app_generator_test.rb25
-rw-r--r--railties/test/generators/generators_test_helper.rb2
-rw-r--r--railties/test/generators/migration_generator_test.rb7
-rw-r--r--railties/test/generators/model_generator_test.rb51
-rw-r--r--railties/test/generators/named_base_test.rb5
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb37
-rw-r--r--railties/test/generators/scaffold_generator_test.rb7
-rw-r--r--railties/test/generators_test.rb18
-rw-r--r--railties/test/isolation/abstract_unit.rb8
-rw-r--r--railties/test/railties/engine_test.rb214
-rw-r--r--railties/test/railties/railtie_test.rb6
-rw-r--r--railties/test/railties/shared_tests.rb10
584 files changed, 18299 insertions, 13369 deletions
diff --git a/.gitignore b/.gitignore
index a18fba3780..8daa1e4dcd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@ activerecord/doc
actionpack/doc
actionmailer/doc
activesupport/doc
+activesupport/test/tmp
activemodel/test/fixtures/fixture_database.sqlite3
actionpack/test/tmp
activesupport/test/fixtures/isolation_test
@@ -20,3 +21,4 @@ railties/test/initializer/root/log
railties/doc
railties/guides/output
railties/tmp
+.rvmrc
diff --git a/Gemfile b/Gemfile
index 4e13331626..7d8949409c 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,5 +1,7 @@
source 'http://rubygems.org'
+gemspec
+
if ENV['AREL']
gem "arel", :path => ENV['AREL']
else
@@ -7,23 +9,20 @@ else
end
gem "rack", :git => "git://github.com/rack/rack.git"
-gem "rails", :path => File.dirname(__FILE__)
+gem "rack-test", :git => "git://github.com/brynary/rack-test.git"
gem "rake", ">= 0.8.7"
gem "mocha", ">= 0.9.8"
-gem "rdoc", ">= 2.5.10"
-gem "horo", ">= 1.0.2"
-# for perf tests
-gem "faker"
-gem "rbench"
-gem "addressable"
+group :doc do
+ gem "rdoc", "~> 3.4"
+ gem "horo", "= 1.0.3"
+ gem "RedCloth", "~> 4.2" if RUBY_VERSION < "1.9.3"
+end
# AS
gem "memcache-client", ">= 1.8.5"
-
-# AM
-gem "text-format", "~> 1.0.0"
+gem "fssm", "~> 0.2.5"
platforms :mri_18 do
gem "system_timer"
@@ -33,7 +32,7 @@ end
platforms :mri_19 do
# TODO: Remove the conditional when ruby-debug19 supports Ruby >= 1.9.3
- gem "ruby-debug19" if RUBY_VERSION < "1.9.3"
+ gem "ruby-debug19", :require => 'ruby-debug' if RUBY_VERSION < "1.9.3"
end
platforms :ruby do
@@ -42,12 +41,12 @@ platforms :ruby do
gem "nokogiri", ">= 1.4.4"
# AR
- gem "sqlite3-ruby", "~> 1.3.1", :require => 'sqlite3'
+ gem "sqlite3", "~> 1.3.3"
group :db do
gem "pg", ">= 0.9.0"
gem "mysql", ">= 2.8.1"
- gem "mysql2", ">= 0.2.6"
+ gem "mysql2", :git => "git://github.com/brianmario/mysql2.git"
end
end
diff --git a/README.rdoc b/README.rdoc
index 7ca376d492..0b209cf56f 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -53,8 +53,8 @@ more separate. Each of these packages can be used independently outside of
* The README file created within your application.
* The {Getting Started with Rails}[http://guides.rubyonrails.org/getting_started.html].
* The {Ruby on Rails Tutorial}[http://railstutorial.org/book].
-* The {Ruby on Rails guides}[http://guides.rubyonrails.org/getting_started.html].
-* The {API documentation}[http://api.rubyonrails.org].
+* The {Ruby on Rails Guides}[http://guides.rubyonrails.org].
+* The {API Documentation}[http://api.rubyonrails.org].
== Contributing
diff --git a/Rakefile b/Rakefile
index 1f3c770c77..53acd077d7 100755
--- a/Rakefile
+++ b/Rakefile
@@ -1,6 +1,4 @@
#!/usr/bin/env rake
-gem 'rdoc', '>= 2.5.10'
-require 'rdoc'
require 'rdoc/task'
require 'net/http'
@@ -14,31 +12,6 @@ task :build => "all:build"
desc "Release all gems to gemcutter and create a tag"
task :release => "all:release"
-# RDoc skips some files in the Rails tree due to its binary? predicate. This is a quick
-# hack for edge docs, until we decide which is the correct way to address this issue.
-# If not fixed in RDoc itself, via an option or something, we should probably move this
-# to railties and use it also in doc:rails.
-def hijack_rdoc!
- require "rdoc/parser"
- class << RDoc::Parser
- def binary?(file)
- s = File.read(file, 1024) or return false
-
- if s[0, 2] == Marshal.dump('')[0, 2] then
- true
- elsif file =~ /erb\.rb$/ then
- false
- elsif s.index("\x00") then # ORIGINAL is s.scan(/<%|%>/).length >= 4 || s.index("\x00")
- true
- elsif 0.respond_to? :fdiv then
- s.count("^ -~\t\r\n").fdiv(s.size) > 0.3
- else # HACK 1.8.6
- (s.count("^ -~\t\r\n").to_f / s.size) > 0.3
- end
- end
- end
-end
-
PROJECTS = %w(activesupport activemodel actionpack actionmailer activeresource activerecord railties)
desc 'Run all tests by default'
@@ -76,8 +49,6 @@ end
desc "Generate documentation for the Rails framework"
RDoc::Task.new do |rdoc|
- hijack_rdoc!
-
rdoc.rdoc_dir = 'doc/rdoc'
rdoc.title = "Ruby on Rails Documentation"
diff --git a/actionmailer/MIT-LICENSE b/actionmailer/MIT-LICENSE
index a345a2419d..7ad1051066 100644
--- a/actionmailer/MIT-LICENSE
+++ b/actionmailer/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
index dfb696eb55..b346bd9e79 100644
--- a/actionmailer/README.rdoc
+++ b/actionmailer/README.rdoc
@@ -59,7 +59,7 @@ generated would look like this:
Mr. david@loudthinking.com
-In previous version of rails you would call <tt>create_method_name</tt> and
+In previous version of Rails you would call <tt>create_method_name</tt> and
<tt>deliver_method_name</tt>. Rails 3.0 has a much simpler interface, you
simply call the method and optionally call +deliver+ on the return value.
diff --git a/actionmailer/Rakefile b/actionmailer/Rakefile
index 123ef9bbbf..df996acbc2 100755
--- a/actionmailer/Rakefile
+++ b/actionmailer/Rakefile
@@ -17,7 +17,7 @@ namespace :test do
task :isolated do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
Dir.glob("test/**/*_test.rb").all? do |file|
- system(ruby, '-Ilib:test', file)
+ sh(ruby, '-Ilib:test', file)
end or raise "Failures"
end
end
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index 29b5813785..2ae85f8b57 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -20,5 +20,5 @@ Gem::Specification.new do |s|
s.has_rdoc = true
s.add_dependency('actionpack', version)
- s.add_dependency('mail', '~> 2.2.9')
+ s.add_dependency('mail', '~> 2.2.15')
end
diff --git a/actionmailer/lib/action_mailer.rb b/actionmailer/lib/action_mailer.rb
index 02a9916703..b9e682b711 100644
--- a/actionmailer/lib/action_mailer.rb
+++ b/actionmailer/lib/action_mailer.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 840708cdc6..15b0d01154 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -222,7 +222,7 @@ module ActionMailer #:nodoc:
#
# An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be
# called before the email is sent, allowing you to make modifications to the email before it hits
- # the delivery agents. Your object should make and needed modifications directly to the passed
+ # the delivery agents. Your object should make any needed modifications directly to the passed
# in Mail::Message instance.
#
# = Default Hash
@@ -246,7 +246,7 @@ module ActionMailer #:nodoc:
# but Action Mailer translates them appropriately and sets the correct values.
#
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
- # an underscorised symbol, so the following will work:
+ # an underscored symbol, so the following will work:
#
# class Notifier < ActionMailer::Base
# default 'Content-Transfer-Encoding' => '7bit',
@@ -298,7 +298,7 @@ module ActionMailer #:nodoc:
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
- # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@addres</tt>
+ # * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@address</tt>
# added automatically before the message is sent.
#
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
@@ -404,7 +404,7 @@ module ActionMailer #:nodoc:
end
end
- def respond_to?(method, *args) #:nodoc:
+ def respond_to?(method, include_private = false) #:nodoc:
super || action_methods.include?(method.to_s)
end
@@ -693,15 +693,8 @@ module ActionMailer #:nodoc:
end
def each_template(paths, name, &block) #:nodoc:
- Array.wrap(paths).each do |path|
- templates = lookup_context.find_all(name, path)
- templates = templates.uniq_by { |t| t.formats }
-
- unless templates.empty?
- templates.each(&block)
- return
- end
- end
+ templates = lookup_context.find_all(name, Array.wrap(paths))
+ templates.uniq_by { |t| t.formats }.each(&block)
end
def create_parts_from_responses(m, responses) #:nodoc:
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index 80ffc9b7ee..887c7012d9 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -3,17 +3,8 @@ module ActionMailer
# Uses Text::Format to take the text and format it, indented two spaces for
# each line, and wrapped at 72 columns.
def block_format(text)
- begin
- require 'text/format'
- rescue LoadError => e
- $stderr.puts "You don't have text-format installed in your application. Please add it to your Gemfile and run bundle install"
- raise e
- end unless defined?(Text::Format)
-
formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
+ simple_format(paragraph)
}.join("\n")
# Make list points stand on their own line
@@ -37,5 +28,22 @@ module ActionMailer
def attachments
@_message.attachments
end
+
+ private
+ def simple_format(text, len = 72, indent = 2)
+ sentences = [[]]
+
+ text.split.each do |word|
+ if (sentences.last + [word]).join(' ').length > len
+ sentences << [word]
+ else
+ sentences.last << word
+ end
+ end
+
+ sentences.map { |sentence|
+ "#{" " * indent}#{sentence.join(' ')}"
+ }.join "\n"
+ end
end
end
diff --git a/actionmailer/lib/action_mailer/old_api.rb b/actionmailer/lib/action_mailer/old_api.rb
index a8d7454898..04728cafb0 100644
--- a/actionmailer/lib/action_mailer/old_api.rb
+++ b/actionmailer/lib/action_mailer/old_api.rb
@@ -201,7 +201,7 @@ module ActionMailer
if String === @body
@parts.unshift create_inline_part(@body)
elsif @parts.empty? || @parts.all? { |p| p.content_disposition =~ /^attachment/ }
- lookup_context.find_all(@template, @mailer_name).each do |template|
+ lookup_context.find_all(@template, [@mailer_name]).each do |template|
self.formats = template.formats
@parts << create_inline_part(render(:template => template), template.mime_type)
end
@@ -242,12 +242,12 @@ module ActionMailer
ct.to_s.split("/")
end
- def parse_content_type(defaults=nil)
+ def parse_content_type
if @content_type.blank?
[ nil, {} ]
else
ctype, *attrs = @content_type.split(/;\s*/)
- attrs = Hash[attrs.map { |attr| attr.split(/\=/, 2) }]
+ attrs = Hash[attrs.map { |attr| attr.split(/=/, 2) }]
[ctype, {"charset" => @charset}.merge!(attrs)]
end
end
diff --git a/actionmailer/lib/action_mailer/tmail_compat.rb b/actionmailer/lib/action_mailer/tmail_compat.rb
index 26cc474e91..1b2cdcfb27 100644
--- a/actionmailer/lib/action_mailer/tmail_compat.rb
+++ b/actionmailer/lib/action_mailer/tmail_compat.rb
@@ -2,16 +2,18 @@ module Mail
class Message
def set_content_type(*args)
- ActiveSupport::Deprecation.warn('Message#set_content_type is deprecated, please just call ' <<
- 'Message#content_type with the same arguments', caller[0,2])
+ message = 'Message#set_content_type is deprecated, please just call ' <<
+ 'Message#content_type with the same arguments'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
content_type(*args)
end
alias :old_transfer_encoding :transfer_encoding
def transfer_encoding(value = nil)
if value
- ActiveSupport::Deprecation.warn('Message#transfer_encoding is deprecated, please call ' <<
- 'Message#content_transfer_encoding with the same arguments', caller[0,2])
+ message = 'Message#transfer_encoding is deprecated, ' <<
+ 'please call Message#content_transfer_encoding with the same arguments'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
content_transfer_encoding(value)
else
old_transfer_encoding
@@ -19,16 +21,17 @@ module Mail
end
def transfer_encoding=(value)
- ActiveSupport::Deprecation.warn('Message#transfer_encoding= is deprecated, please call ' <<
- 'Message#content_transfer_encoding= with the same arguments', caller[0,2])
+ message = 'Message#transfer_encoding= is deprecated, ' <<
+ 'please call Message#content_transfer_encoding= with the same arguments'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
self.content_transfer_encoding = value
end
def original_filename
- ActiveSupport::Deprecation.warn('Message#original_filename is deprecated, ' <<
- 'please call Message#filename', caller[0,2])
+ message = 'Message#original_filename is deprecated, please call Message#filename'
+ ActiveSupport::Deprecation.warn(message, caller[0,2])
filename
end
end
-end \ No newline at end of file
+end
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb
index 0dce0ac15d..ce664bf301 100644
--- a/actionmailer/test/abstract_unit.rb
+++ b/actionmailer/test/abstract_unit.rb
@@ -25,7 +25,6 @@ end
silence_warnings do
# These external dependencies have warnings :/
- require 'text/format'
require 'mail'
end
@@ -79,4 +78,4 @@ def restore_delivery_method
ActionMailer::Base.delivery_method = @old_delivery_method
end
-ActiveSupport::Deprecation.silenced = true \ No newline at end of file
+ActiveSupport::Deprecation.silenced = true
diff --git a/actionmailer/test/asset_host_test.rb b/actionmailer/test/asset_host_test.rb
index 069860ff06..b24eca5fbb 100644
--- a/actionmailer/test/asset_host_test.rb
+++ b/actionmailer/test/asset_host_test.rb
@@ -29,7 +29,7 @@ class AssetHostTest < Test::Unit::TestCase
assert_equal %Q{<img alt="Somelogo" src="http://www.example.com/images/somelogo.png" />}, mail.body.to_s.strip
end
- def test_asset_host_as_one_arguement_proc
+ def test_asset_host_as_one_argument_proc
AssetHostMailer.config.asset_host = Proc.new { |source|
if source.starts_with?('/images')
"http://images.example.com"
@@ -41,7 +41,7 @@ class AssetHostTest < Test::Unit::TestCase
assert_equal %Q{<img alt="Somelogo" src="http://images.example.com/images/somelogo.png" />}, mail.body.to_s.strip
end
- def test_asset_host_as_two_arguement_proc
+ def test_asset_host_as_two_argument_proc
ActionController::Base.config.asset_host = Proc.new {|source,request|
if request && request.ssl?
"https://www.example.com"
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index 7ed9d4a5c0..1b793d255e 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -32,21 +32,21 @@ class BaseTest < ActiveSupport::TestCase
end
test "mail() with bcc, cc, content_type, charset, mime_version, reply_to and date" do
- @time = Time.now.beginning_of_day.to_datetime
+ time = Time.now.beginning_of_day.to_datetime
email = BaseMailer.welcome(:bcc => 'bcc@test.lindsaar.net',
:cc => 'cc@test.lindsaar.net',
:content_type => 'multipart/mixed',
:charset => 'iso-8559-1',
:mime_version => '2.0',
:reply_to => 'reply-to@test.lindsaar.net',
- :date => @time)
+ :date => time)
assert_equal(['bcc@test.lindsaar.net'], email.bcc)
assert_equal(['cc@test.lindsaar.net'], email.cc)
assert_equal('multipart/mixed; charset=iso-8559-1', email.content_type)
assert_equal('iso-8559-1', email.charset)
assert_equal('2.0', email.mime_version)
assert_equal(['reply-to@test.lindsaar.net'], email.reply_to)
- assert_equal(@time, email.date)
+ assert_equal(time, email.date)
end
test "mail() renders the template using the method being processed" do
diff --git a/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb b/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb
new file mode 100644
index 0000000000..f5340283f1
--- /dev/null
+++ b/actionmailer/test/fixtures/i18n_test_mailer/mail_with_i18n_subject.erb
@@ -0,0 +1,4 @@
+Hello there,
+
+Mr. <%= @recipient %>. Be greeted, new member!
+
diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb
new file mode 100644
index 0000000000..7040ae6f8d
--- /dev/null
+++ b/actionmailer/test/i18n_with_controller_test.rb
@@ -0,0 +1,46 @@
+require 'abstract_unit'
+require 'action_controller'
+
+class I18nTestMailer < ActionMailer::Base
+ configure do |c|
+ c.assets_dir = ''
+ end
+
+ def mail_with_i18n_subject(recipient)
+ @recipient = recipient
+ I18n.locale = :de
+ mail(:to => recipient, :subject => "#{I18n.t :email_subject} #{recipient}",
+ :from => "system@loudthinking.com", :date => Time.local(2004, 12, 12))
+ end
+end
+
+class TestController < ActionController::Base
+ def send_mail
+ I18nTestMailer.mail_with_i18n_subject("test@localhost").deliver
+ render :text => 'Mail sent'
+ end
+end
+
+class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ match ':controller(/:action(/:id))'
+ end
+
+ def app
+ Routes
+ end
+
+ def setup
+ I18n.backend.store_translations('de', :email_subject => '[Signed up] Welcome')
+ end
+
+ def teardown
+ I18n.locale = :en
+ end
+
+ def test_send_mail
+ get '/test/send_mail'
+ assert_equal "Mail sent", @response.body
+ end
+end
diff --git a/actionmailer/test/old_base/tmail_compat_test.rb b/actionmailer/test/old_base/tmail_compat_test.rb
index 23706e99ff..51558c2bfa 100644
--- a/actionmailer/test/old_base/tmail_compat_test.rb
+++ b/actionmailer/test/old_base/tmail_compat_test.rb
@@ -1,6 +1,14 @@
require 'abstract_unit'
class TmailCompatTest < ActiveSupport::TestCase
+ def setup
+ @silence = ActiveSupport::Deprecation.silenced
+ ActiveSupport::Deprecation.silenced = false
+ end
+
+ def teardown
+ ActiveSupport::Deprecation.silenced = @silence
+ end
def test_set_content_type_raises_deprecation_warning
mail = Mail.new
@@ -31,5 +39,4 @@ class TmailCompatTest < ActiveSupport::TestCase
end
assert_equal mail.content_transfer_encoding, "base64"
end
-
end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index acd9bd5b63..fc3410ba6e 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -1,6 +1,18 @@
*Rails 3.1.0 (unreleased)*
-* url_for and named url helpers now accept :subdomain and :domain as options [Josh Kalderimis]
+* 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]
@@ -29,23 +41,24 @@
* 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.2 (unreleased)*
* 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, maintaing just the helper with the same name as the controller. [José Valim]
-
-* See http://github.com/rails/rails/compare/v3.0.0_RC...v3.0.0_RC2 for gory details
+* 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]
diff --git a/actionpack/MIT-LICENSE b/actionpack/MIT-LICENSE
index a345a2419d..7ad1051066 100644
--- a/actionpack/MIT-LICENSE
+++ b/actionpack/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 0ad33cfe26..a28d78f688 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -262,7 +262,7 @@ methods:
layout "weblog/layout"
def index
- @posts = Post.find(:all)
+ @posts = Post.all
end
def show
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index b7d1d8c2af..f6bc5e0d37 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -21,11 +21,11 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
- s.add_dependency('rack-cache', '~> 0.5.3')
+ s.add_dependency('rack-cache', '~> 1.0.0')
s.add_dependency('builder', '~> 3.0.0')
s.add_dependency('i18n', '~> 0.5.0')
s.add_dependency('rack', '~> 1.2.1')
- s.add_dependency('rack-test', '~> 0.5.6')
+ s.add_dependency('rack-test', '~> 0.5.7')
s.add_dependency('rack-mount', '~> 0.6.13')
s.add_dependency('tzinfo', '~> 0.3.23')
s.add_dependency('erubis', '~> 2.6.6')
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index f169ab7c3a..95992c2698 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -13,7 +13,7 @@ module AbstractController
# Override AbstractController::Base's process_action to run the
# process_action callbacks around the normal behavior.
- def process_action(method_name)
+ def process_action(method_name, *args)
run_callbacks(:process_action, method_name) do
super
end
diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb
index 606f7eedec..4ee54474cc 100644
--- a/actionpack/lib/abstract_controller/layouts.rb
+++ b/actionpack/lib/abstract_controller/layouts.rb
@@ -265,11 +265,11 @@ module AbstractController
raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil"
when nil
if name
- _prefix = "layouts" unless _implied_layout_name =~ /\blayouts/
+ _prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"]
self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def _layout
- if template_exists?("#{_implied_layout_name}", #{_prefix.inspect})
+ if template_exists?("#{_implied_layout_name}", #{_prefixes.inspect})
"#{_implied_layout_name}"
else
super
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index 91b75273fa..691310d5d2 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -13,14 +13,15 @@ module AbstractController
# This is a class to fix I18n global state. Whenever you provide I18n.locale during a request,
# it will trigger the lookup_context and consequently expire the cache.
class I18nProxy < ::I18n::Config #:nodoc:
- attr_reader :i18n_config, :lookup_context
+ attr_reader :original_config, :lookup_context
- def initialize(i18n_config, lookup_context)
- @i18n_config, @lookup_context = i18n_config, lookup_context
+ def initialize(original_config, lookup_context)
+ original_config = original_config.original_config if original_config.respond_to?(:original_config)
+ @original_config, @lookup_context = original_config, lookup_context
end
def locale
- @i18n_config.locale
+ @original_config.locale
end
def locale=(value)
@@ -60,6 +61,20 @@ module AbstractController
end
end
end
+
+ def parent_prefixes
+ @parent_prefixes ||= begin
+ parent_controller = superclass
+ prefixes = []
+
+ until parent_controller.abstract?
+ prefixes << parent_controller.controller_path
+ parent_controller = parent_controller.superclass
+ end
+
+ prefixes
+ end
+ end
end
attr_writer :view_context_class
@@ -98,7 +113,7 @@ module AbstractController
def render_to_string(*args, &block)
options = _normalize_args(*args, &block)
_normalize_options(options)
- render_to_body(options)
+ render_to_body(options).tap { self.response_body = nil }
end
# Raw rendering of a template to a Rack-compatible body.
@@ -114,9 +129,12 @@ module AbstractController
view_context.render(options)
end
- # The prefix used in render "foo" shortcuts.
- def _prefix
- controller_path
+ # The prefixes used in render "foo" shortcuts.
+ def _prefixes
+ @_prefixes ||= begin
+ parent_prefixes = self.class.parent_prefixes
+ parent_prefixes.dup.unshift(controller_path)
+ end
end
private
@@ -156,7 +174,7 @@ module AbstractController
end
if (options.keys & [:partial, :file, :template, :once]).empty?
- options[:prefix] ||= _prefix
+ options[:prefixes] ||= _prefixes
end
options[:template] ||= (options[:action] || action_name).to_s
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 48308cbb60..81c0698fb8 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -24,7 +24,7 @@ module ActionController
#
# Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
# after executing code in the action. For example, the +index+ action of the PostsController would render the
- # template <tt>app/views/posts/index.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
+ # template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
#
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
# new post), it initiates a redirect instead. This redirect works by returning an external
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index a4bac3caed..a1c582560c 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -103,12 +103,14 @@ module ActionController #:nodoc:
end
def _save_fragment(name, options)
- return unless caching_allowed?
-
content = response_body
content = content.join if content.is_a?(Array)
- write_fragment(name, content, options)
+ if caching_allowed?
+ write_fragment(name, content, options)
+ else
+ content
+ end
end
protected
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index 37c155b9cd..0be04b70a1 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -1,52 +1,72 @@
module ActionController #:nodoc:
module Caching
- # Fragment caching is used for caching various blocks within templates without caching the entire action as a whole. This is 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 cache helper available in the Action View. A template with caching might look something like:
+ # Fragment caching is used for caching various blocks within
+ # views without caching the entire action as a whole. This is
+ # 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:
#
# <b>Hello <%= @name %></b>
+ #
# <% cache do %>
# All the topics in the system:
# <%= render :partial => "topic", :collection => Topic.find(:all) %>
# <% end %>
#
- # This cache will bind to 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 <tt>expire_fragment(:controller => "topics", :action => "list")</tt>.
+ # 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 of limited use if you need to cache multiple fragments per action or if the action itself is cached using
- # <tt>caches_action</tt>, so we also have the option to qualify the name of the cached fragment with something like:
+ # 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.
+ # 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(:controller => "topics",
+ # :action => "list",
+ # :action_suffix => "all_topics")
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
+ # 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
# 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)
end
- # Writes <tt>content</tt> to the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
+ # Writes <tt>content</tt> to the location signified by
+ # <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats).
def write_fragment(key, content, options = nil)
return content unless cache_configured?
key = fragment_cache_key(key)
instrument_fragment_cache :write_fragment, key do
- content = content.html_safe.to_str if content.respond_to?(:html_safe)
+ content = content.to_str
cache_store.write(key, content, options)
end
content
end
- # Reads a cached fragment from the location signified by <tt>key</tt> (see <tt>expire_fragment</tt> for acceptable formats)
+ # Reads a cached fragment from the location signified by <tt>key</tt>
+ # (see <tt>expire_fragment</tt> for acceptable formats).
def read_fragment(key, options = nil)
return unless cache_configured?
@@ -57,7 +77,8 @@ module ActionController #:nodoc:
end
end
- # Check if a cached fragment from the location signified by <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats)
+ # Check if a cached fragment from the location signified by
+ # <tt>key</tt> exists (see <tt>expire_fragment</tt> for acceptable formats)
def fragment_exist?(key, options = nil)
return unless cache_configured?
key = fragment_cache_key(key)
@@ -70,6 +91,7 @@ module ActionController #:nodoc:
# Removes fragments from the cache.
#
# +key+ can take one of three forms:
+ #
# * String - This would normally take the form of a path, like
# <tt>pages/45/notes</tt>.
# * Hash - Treated as an implicit call to +url_for+, like
diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb
index 3e57d2c236..8c583c7ce0 100644
--- a/actionpack/lib/action_controller/caching/pages.rb
+++ b/actionpack/lib/action_controller/caching/pages.rb
@@ -106,7 +106,7 @@ module ActionController #:nodoc:
end
def page_cache_path(path, extension = nil)
- page_cache_directory + page_cache_file(path, extension)
+ page_cache_directory.to_s + page_cache_file(path, extension)
end
def instrument_page_cache(name, path)
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 3b19310a69..3fae697cc3 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -16,7 +16,11 @@ module ActionController
payload = event.payload
additions = ActionController::Base.log_process_action(payload)
- message = "Completed #{payload[:status]} #{Rack::Utils::HTTP_STATUS_CODES[payload[:status]]} in %.0fms" % event.duration
+ status = payload[:status]
+ if status.nil? && payload[:exception].present?
+ status = Rack::Utils.status_code(ActionDispatch::ShowExceptions.rescue_responses[payload[:exception].first]) rescue nil
+ end
+ message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in %.0fms" % event.duration
message << " (#{additions.join(" | ")})" unless additions.blank?
info(message)
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 329798e84f..e5db31061b 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -36,19 +36,68 @@ module ActionController
action = action.to_s
raise "MiddlewareStack#build requires an app" unless app
- reverse.inject(app) do |a, middleware|
+ middlewares.reverse.inject(app) do |a, middleware|
middleware.valid?(action) ?
middleware.build(a) : a
end
end
end
- # Provides a way to get a valid Rack application from a controller.
+ # <tt>ActionController::Metal</tt> is the simplest possible controller, providing a
+ # valid Rack interface without the additional niceties provided by
+ # <tt>ActionController::Base</tt>.
+ #
+ # A sample metal controller might look like this:
+ #
+ # class HelloController < ActionController::Metal
+ # def index
+ # self.response_body = "Hello World!"
+ # end
+ # end
+ #
+ # And then to route requests to your metal controller, you would add
+ # something like this to <tt>config/routes.rb</tt>:
+ #
+ # match 'hello', :to => HelloController.action(:index)
+ #
+ # The +action+ method returns a valid Rack application for the \Rails
+ # router to dispatch to.
+ #
+ # == Rendering Helpers
+ #
+ # <tt>ActionController::Metal</tt> by default provides no utilities for rendering
+ # views, partials, or other responses aside from explicitly calling of
+ # <tt>response_body=</tt>, <tt>content_type=</tt>, and <tt>status=</tt>. To
+ # add the render helpers you're used to having in a normal controller, you
+ # can do the following:
+ #
+ # class HelloController < ActionController::Metal
+ # include ActionController::Rendering
+ # append_view_path "#{Rails.root}/app/views"
+ #
+ # def index
+ # render "hello/index"
+ # end
+ # end
+ #
+ # == Redirection Helpers
+ #
+ # To add redirection helpers to your metal controller, do the following:
+ #
+ # class HelloController < ActionController::Metal
+ # include ActionController::Redirecting
+ # include Rails.application.routes.url_helpers
+ #
+ # def index
+ # redirect_to root_url
+ # end
+ # end
+ #
+ # == Other Helpers
+ #
+ # You can refer to the modules included in <tt>ActionController::Base</tt> to see
+ # other features you can bring into your metal controller.
#
- # In AbstractController, dispatching is triggered directly by calling #process on a new controller.
- # <tt>ActionController::Metal</tt> provides an <tt>action</tt> method that returns a valid Rack application for a
- # given action. Other rack builders, such as Rack::Builder, Rack::URLMap, and the \Rails router,
- # can dispatch directly to actions returned by controllers in your application.
class Metal < AbstractController::Base
abstract!
@@ -133,7 +182,7 @@ module ActionController
end
def response_body=(val)
- body = val.respond_to?(:each) ? val : [val]
+ body = val.nil? ? nil : (val.respond_to?(:each) ? val : [val])
super body
end
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
index 282dcf66b3..cfa7004048 100644
--- a/actionpack/lib/action_controller/metal/implicit_render.rb
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -12,10 +12,10 @@ module ActionController
def method_for_action(action_name)
super || begin
- if template_exists?(action_name.to_s, _prefix)
+ if template_exists?(action_name.to_s, _prefixes)
"default_render"
end
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 9ba37134b8..a2e06fe0a6 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -63,13 +63,13 @@ module ActionController #:nodoc:
# might look something like this:
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
# end
#
# Here's the same action, with web-service support baked in:
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
#
# respond_to do |format|
# format.html
@@ -155,7 +155,7 @@ module ActionController #:nodoc:
# Respond to also allows you to specify a common block for different formats by using any:
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
#
# respond_to do |format|
# format.html
@@ -178,7 +178,7 @@ module ActionController #:nodoc:
# respond_to :html, :xml, :json
#
# def index
- # @people = Person.find(:all)
+ # @people = Person.all
# respond_with(@person)
# end
# end
@@ -208,8 +208,8 @@ module ActionController #:nodoc:
# It also accepts a block to be given. It's used to overwrite a default
# response:
#
- # def destroy
- # @user = User.find(params[:id])
+ # def create
+ # @user = User.new(params[:user])
# flash[:notice] = "User was successfully created." if @user.save
#
# respond_with(@user) do |format|
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index d6f6ab1855..38711c8462 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -2,6 +2,7 @@ require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/object/blank'
module ActionController
+ # See <tt>Renderers.add</tt>
def self.add_renderer(key, &block)
Renderers.add(key, &block)
end
@@ -39,7 +40,43 @@ module ActionController
nil
end
+ # Hash of available renderers, mapping a renderer name to its proc.
+ # Default keys are :json, :js, :xml and :update.
RENDERERS = {}
+
+ # Adds a new renderer to call within controller actions.
+ # A renderer is invoked by passing its name as an option to
+ # <tt>AbstractController::Rendering#render</tt>. To create a renderer
+ # pass it a name and a block. The block takes two arguments, the first
+ # is the value paired with its key and the second is the remaining
+ # hash of options passed to +render+.
+ #
+ # === Example
+ # Create a csv renderer:
+ #
+ # ActionController::Renderers.add :csv do |obj, options|
+ # filename = options[:filename] || 'data'
+ # str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s
+ # send_data str, :type => Mime::CSV,
+ # :disposition => "attachment; filename=#{filename}.csv"
+ # end
+ #
+ # Note that we used Mime::CSV for the csv mime type as it comes with Rails.
+ # For a custom renderer, you'll need to register a mime type with
+ # <tt>Mime::Type.register</tt>.
+ #
+ # To use the csv renderer in a controller action:
+ #
+ # def show
+ # @csvable = Csvable.find(params[:id])
+ # respond_to do |format|
+ # format.html
+ # format.csv { render :csv => @csvable, :filename => @csvable.name }
+ # }
+ # end
+ # To use renderers and their mime types in more concise ways, see
+ # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
+ # <tt>ActionController::MimeResponds#respond_with</tt>
def self.add(key, &block)
define_method("_render_option_#{key}", &block)
RENDERERS[key] = block
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 14cc547dd0..32d52c84c4 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -6,7 +6,7 @@ module ActionController
# Before processing, set the request formats in current controller formats.
def process_action(*) #:nodoc:
- self.formats = request.formats.map { |x| x.to_sym }
+ self.formats = request.formats.map { |x| x.ref }
super
end
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 148efbb081..1cd93a188c 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -66,30 +66,29 @@ module ActionController #:nodoc:
# * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified.
def protect_from_forgery(options = {})
self.request_forgery_protection_token ||= :authenticity_token
- before_filter :verify_authenticity_token, options
+ prepend_before_filter :verify_authenticity_token, options
end
end
protected
-
- def protect_from_forgery(options = {})
- self.request_forgery_protection_token ||= :authenticity_token
- before_filter :verify_authenticity_token, options
- end
-
# The actual before_filter that is used. Modify this to change how you handle unverified requests.
def verify_authenticity_token
- verified_request? || raise(ActionController::InvalidAuthenticityToken)
+ verified_request? || handle_unverified_request
+ end
+
+ def handle_unverified_request
+ reset_session
end
# Returns true or false if a request is verified. Checks:
#
- # * is the format restricted? By default, only HTML requests are checked.
# * is it a GET request? Gets should be safe and idempotent
# * Does the form_authenticity_token match the given token value from the params?
+ # * Does the X-CSRF-Token header match the form_authenticity_token
def verified_request?
- !protect_against_forgery? || request.forgery_whitelisted? ||
- form_authenticity_token == params[request_forgery_protection_token]
+ !protect_against_forgery? || request.get? ||
+ form_authenticity_token == params[request_forgery_protection_token] ||
+ form_authenticity_token == request.headers['X-CSRF-Token']
end
# Sets the token value for the current session.
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index 38d32211cc..4b45413cf8 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -77,8 +77,6 @@ module ActionController #:nodoc:
#
# respond_with(@project, :manager, @task)
#
- # Check <code>polymorphic_url</code> documentation for more examples.
- #
class Responder
attr_reader :controller, :request, :format, :resource, :resources, :options
@@ -115,7 +113,7 @@ module ActionController #:nodoc:
# Main entry point for responder responsible to dispatch to the proper format.
#
def respond
- method = :"to_#{format}"
+ method = "to_#{format}"
respond_to?(method) ? send(method) : to_format
end
@@ -171,7 +169,7 @@ module ActionController #:nodoc:
# Checks whether the resource responds to the current format or not.
#
def resourceful?
- resource.respond_to?(:"to_#{format}")
+ resource.respond_to?("to_#{format}")
end
# Returns the resource location by retrieving it from the options or
diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb
index 699c44c62c..dce3c2fe88 100644
--- a/actionpack/lib/action_controller/railties/paths.rb
+++ b/actionpack/lib/action_controller/railties/paths.rb
@@ -16,6 +16,14 @@ module ActionController
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
klass.helper :all
end
+
+ if app.config.serve_static_assets && namespace
+ paths = namespace._railtie.config.paths
+
+ klass.config.assets_dir = paths["public"].first
+ klass.config.javascripts_dir = paths["public/javascripts"].first
+ klass.config.stylesheets_dir = paths["public/stylesheets"].first
+ end
end
end
end
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
index 3e5d23b5c1..09dd08898c 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
@@ -170,7 +170,7 @@ module HTML
def contains_bad_protocols?(attr_name, value)
uri_attributes.include?(attr_name) &&
- (value =~ /(^[^\/:]*):|(&#0*58)|(&#x70)|(%|&#37;)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first))
+ (value =~ /(^[^\/:]*):|(&#0*58)|(&#x70)|(%|&#37;)3A/ && !allowed_protocols.include?(value.split(protocol_separator).first.downcase))
end
end
end
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 50faf666e6..49971fc9f8 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -53,6 +53,7 @@ module ActionDispatch
autoload :Flash
autoload :Head
autoload :ParamsParser
+ autoload :Reloader
autoload :RemoteIp
autoload :Rescue
autoload :ShowExceptions
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index 1d2f7e4f19..4f4cb96a74 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -43,7 +43,7 @@ module ActionDispatch
alias :etag? :etag
def initialize(*)
- status, header, body = super
+ super
@cache_control = {}
@etag = self["ETag"]
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index 5b87a80c1b..7c9ebe7c7b 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -216,7 +216,11 @@ module Mime
end
def to_sym
- @symbol || @string.to_sym
+ @symbol
+ end
+
+ def ref
+ to_sym || to_s
end
def ===(list)
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 08f30e068d..f07ac44f7a 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -2,6 +2,7 @@ require 'tempfile'
require 'stringio'
require 'strscan'
+require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/string/access'
require 'active_support/inflector'
@@ -133,8 +134,9 @@ module ActionDispatch
end
def forgery_whitelisted?
- get? || xhr? || content_mime_type.nil? || !content_mime_type.verify_request?
+ get?
end
+ deprecate :forgery_whitelisted? => "it is just an alias for 'get?' now, update your code"
def media_type
content_mime_type.to_s
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 796cd8c09b..535ff42b90 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -28,8 +28,11 @@ module ActionDispatch
rewritten_url = ""
unless options[:only_path]
- rewritten_url << (options[:protocol] || "http")
- rewritten_url << "://" unless rewritten_url.match("://")
+ unless options[:protocol] == false
+ rewritten_url << (options[:protocol] || "http")
+ rewritten_url << ":" unless rewritten_url.match(%r{:|//})
+ end
+ rewritten_url << "//" unless rewritten_url.match("//")
rewritten_url << rewrite_authentication(options)
rewritten_url << host_or_subdomain_and_domain(options)
rewritten_url << ":#{options.delete(:port)}" if options[:port]
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
index 0bb950d1cc..1bb2ad7f67 100644
--- a/actionpack/lib/action_dispatch/middleware/callbacks.rb
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,32 +1,14 @@
+require 'active_support/core_ext/module/delegation'
+
module ActionDispatch
# Provide callbacks to be executed before and after the request dispatch.
- #
- # It also provides a to_prepare callback, which is performed in all requests
- # in development by only once in production and notification callback for async
- # operations.
- #
class Callbacks
include ActiveSupport::Callbacks
define_callbacks :call, :rescuable => true
- define_callbacks :prepare, :scope => :name
- # Add a preparation callback. Preparation callbacks are run before every
- # request in development mode, and before the first request in production mode.
- #
- # If a symbol with a block is given, the symbol is used as an identifier.
- # That allows to_prepare to be called again with the same identifier to
- # replace the existing callback. Passing an identifier is a suggested
- # practice if the code adding a preparation block may be reloaded.
- def self.to_prepare(*args, &block)
- first_arg = args.first
- if first_arg.is_a?(Symbol) && block_given?
- remove_method :"__#{first_arg}" if method_defined?(:"__#{first_arg}")
- define_method :"__#{first_arg}", &block
- set_callback(:prepare, :"__#{first_arg}")
- else
- set_callback(:prepare, *args, &block)
- end
+ class << self
+ delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
end
def self.before(*args, &block)
@@ -37,14 +19,13 @@ module ActionDispatch
set_callback(:call, :after, *args, &block)
end
- def initialize(app, prepare_each_request = false)
- @app, @prepare_each_request = app, prepare_each_request
- _run_prepare_callbacks
+ def initialize(app, unused = nil)
+ ActiveSupport::Deprecation.warn "Passing a second argument to ActionDispatch::Callbacks.new is deprecated." unless unused.nil?
+ @app = app
end
def call(env)
- _run_call_callbacks do
- _run_prepare_callbacks if @prepare_each_request
+ run_callbacks :call do
@app.call(env)
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index b0a4e3d949..7ac608f0a8 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -90,17 +90,14 @@ module ActionDispatch
# **.**, ***.** style TLDs like co.uk or com.au
#
# www.example.co.uk gives:
- # $1 => example
- # $2 => co.uk
+ # $& => example.co.uk
#
# example.com gives:
- # $1 => example
- # $2 => com
+ # $& => example.com
#
# lots.of.subdomains.example.local gives:
- # $1 => example
- # $2 => local
- DOMAIN_REGEXP = /([^.]*)\.([^.]*|..\...|...\...)$/
+ # $& => example.local
+ DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/
def self.build(request)
secret = request.env[TOKEN_KEY]
@@ -131,8 +128,17 @@ module ActionDispatch
options[:path] ||= "/"
if options[:domain] == :all
- @host =~ DOMAIN_REGEXP
- options[:domain] = ".#{$1}.#{$2}"
+ # if there is a provided tld length then we use it otherwise default domain regexp
+ domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
+
+ # if host is not ip and matches domain regexp
+ # (ip confirms to domain regexp so we explicitly check for ip)
+ options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
+ ".#{$&}"
+ end
+ elsif options[:domain].is_a? Array
+ # if host matches one of the supplied domains without a dot in front of it
+ options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] }
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb
new file mode 100644
index 0000000000..29289a76b4
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/reloader.rb
@@ -0,0 +1,76 @@
+module ActionDispatch
+ # ActionDispatch::Reloader provides prepare and cleanup callbacks,
+ # intended to assist with code reloading during development.
+ #
+ # Prepare callbacks are run before each request, and cleanup callbacks
+ # after each request. In this respect they are analogs of ActionDispatch::Callback's
+ # before and after callbacks. However, cleanup callbacks are not called until the
+ # request is fully complete -- that is, after #close has been called on
+ # the response body. This is important for streaming responses such as the
+ # following:
+ #
+ # self.response_body = lambda { |response, output|
+ # # code here which refers to application models
+ # }
+ #
+ # Cleanup callbacks will not be called until after the response_body lambda
+ # is evaluated, ensuring that it can refer to application models and other
+ # classes before they are unloaded.
+ #
+ # By default, ActionDispatch::Reloader is included in the middleware stack
+ # only in the development environment; specifically, when config.cache_classes
+ # is false. Callbacks may be registered even when it is not included in the
+ # middleware stack, but are executed only when +ActionDispatch::Reloader.prepare!+
+ # or +ActionDispatch::Reloader.cleanup!+ are called manually.
+ #
+ class Reloader
+ include ActiveSupport::Callbacks
+
+ define_callbacks :prepare, :scope => :name
+ define_callbacks :cleanup, :scope => :name
+
+ # Add a prepare callback. Prepare callbacks are run before each request, prior
+ # to ActionDispatch::Callback's before callbacks.
+ def self.to_prepare(*args, &block)
+ set_callback(:prepare, *args, &block)
+ end
+
+ # Add a cleanup callback. Cleanup callbacks are run after each request is
+ # complete (after #close is called on the response body).
+ def self.to_cleanup(*args, &block)
+ set_callback(:cleanup, *args, &block)
+ end
+
+ # Execute all prepare callbacks.
+ def self.prepare!
+ new(nil).run_callbacks :prepare
+ end
+
+ # Execute all cleanup callbacks.
+ def self.cleanup!
+ new(nil).run_callbacks :cleanup
+ end
+
+ def initialize(app)
+ @app = app
+ end
+
+ module CleanupOnClose
+ def close
+ super if defined?(super)
+ ensure
+ ActionDispatch::Reloader.cleanup!
+ end
+ end
+
+ def call(env)
+ run_callbacks :prepare
+ response = @app.call(env)
+ response[2].extend(CleanupOnClose)
+ response
+ rescue Exception
+ run_callbacks :cleanup
+ raise
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index 71e736ce9f..dbe3206808 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -43,20 +43,20 @@ module ActionDispatch
end
def call(env)
- status, headers, body = @app.call(env)
-
- # Only this middleware cares about RoutingError. So, let's just raise
- # it here.
- # TODO: refactor this middleware to handle the X-Cascade scenario without
- # having to raise an exception.
- if headers['X-Cascade'] == 'pass'
- raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}"
+ begin
+ status, headers, body = @app.call(env)
+ exception = nil
+
+ # Only this middleware cares about RoutingError. So, let's just raise
+ # it here.
+ if headers['X-Cascade'] == 'pass'
+ raise ActionController::RoutingError, "No route matches #{env['PATH_INFO'].inspect}"
+ end
+ rescue Exception => exception
+ raise exception if env['action_dispatch.show_exceptions'] == false
end
- [status, headers, body]
- rescue Exception => exception
- raise exception if env['action_dispatch.show_exceptions'] == false
- render_exception(env, exception)
+ exception ? render_exception(env, exception) : [status, headers, body]
end
private
diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb
index e3cd779756..a4308f528c 100644
--- a/actionpack/lib/action_dispatch/middleware/stack.rb
+++ b/actionpack/lib/action_dispatch/middleware/stack.rb
@@ -2,17 +2,26 @@ require "active_support/inflector/methods"
require "active_support/dependencies"
module ActionDispatch
- class MiddlewareStack < Array
+ class MiddlewareStack
class Middleware
- attr_reader :args, :block
+ attr_reader :args, :block, :name, :classcache
def initialize(klass_or_name, *args, &block)
- @ref = ActiveSupport::Dependencies::Reference.new(klass_or_name)
+ @klass = nil
+
+ if klass_or_name.respond_to?(:name)
+ @klass = klass_or_name
+ @name = @klass.name
+ else
+ @name = klass_or_name.to_s
+ end
+
+ @classcache = ActiveSupport::Dependencies::Reference
@args, @block = args, block
end
def klass
- @ref.get
+ @klass || classcache[@name]
end
def ==(middleware)
@@ -22,7 +31,7 @@ module ActionDispatch
when Class
klass == middleware
else
- normalize(@ref.name) == normalize(middleware)
+ normalize(@name) == normalize(middleware)
end
end
@@ -41,18 +50,39 @@ module ActionDispatch
end
end
- # Use this instead of super to work around a warning.
- alias :array_initialize :initialize
+ include Enumerable
+
+ attr_accessor :middlewares
def initialize(*args)
- array_initialize(*args)
+ @middlewares = []
yield(self) if block_given?
end
+ def each
+ @middlewares.each { |x| yield x }
+ end
+
+ def size
+ middlewares.size
+ end
+
+ def last
+ middlewares.last
+ end
+
+ def [](i)
+ middlewares[i]
+ end
+
+ def initialize_copy(other)
+ self.middlewares = other.middlewares.dup
+ end
+
def insert(index, *args, &block)
index = assert_index(index, :before)
middleware = self.class::Middleware.new(*args, &block)
- super(index, middleware)
+ middlewares.insert(index, middleware)
end
alias_method :insert_before, :insert
@@ -67,21 +97,25 @@ module ActionDispatch
delete(target)
end
+ def delete(target)
+ middlewares.delete target
+ end
+
def use(*args, &block)
middleware = self.class::Middleware.new(*args, &block)
- push(middleware)
+ middlewares.push(middleware)
end
def build(app = nil, &block)
app ||= block
raise "MiddlewareStack#build requires an app" unless app
- reverse.inject(app) { |a, e| e.build(a) }
+ middlewares.reverse.inject(app) { |a, e| e.build(a) }
end
protected
def assert_index(index, where)
- i = index.is_a?(Integer) ? index : self.index(index)
+ i = index.is_a?(Integer) ? index : middlewares.index(index)
raise "No such middleware to insert #{where}: #{index.inspect}" unless i
i
end
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index 913b899e20..c57f694c4d 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -3,10 +3,10 @@ require 'rack/utils'
module ActionDispatch
class FileHandler
def initialize(at, root)
- @at, @root = at.chomp('/'), root.chomp('/')
- @compiled_at = (Regexp.compile(/^#{Regexp.escape(at)}/) unless @at.blank?)
- @compiled_root = Regexp.compile(/^#{Regexp.escape(root)}/)
- @file_server = ::Rack::File.new(@root)
+ @at, @root = at.chomp('/'), root.chomp('/')
+ @compiled_at = @at.blank? ? nil : /^#{Regexp.escape(at)}/
+ @compiled_root = /^#{Regexp.escape(root)}/
+ @file_server = ::Rack::File.new(@root)
end
def match?(path)
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
index bd6ffbab5d..50d8ca9484 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
@@ -6,5 +6,5 @@
</h1>
<pre><%=h @exception.message %></pre>
-<%= render :file => "rescues/_trace.erb" %>
-<%= render :file => "rescues/_request_and_response.erb" %>
+<%= render :template => "rescues/_trace" %>
+<%= render :template => "rescues/_request_and_response" %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
index 02fa18211d..c658559be9 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/template_error.erb
@@ -13,9 +13,5 @@
<p><%=h @exception.sub_template_message %></p>
-<% @real_exception = @exception
- @exception = @exception.original_exception || @exception %>
-<%= render :file => "rescues/_trace.erb" %>
-<% @exception = @real_exception %>
-
-<%= render :file => "rescues/_request_and_response.erb" %>
+<%= render :template => "rescues/_trace" %>
+<%= render :template => "rescues/_request_and_response" %>
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index 8810227a59..43fd93adf6 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -56,6 +56,18 @@ module ActionDispatch
# resources :posts, :comments
# end
#
+ # Alternately, you can add prefixes to your path without using a separate
+ # directory by using +scope+. +scope+ takes additional options which
+ # apply to all enclosed routes.
+ #
+ # scope :path => "/cpanel", :as => 'admin' do
+ # resources :posts, :comments
+ # end
+ #
+ # For more, see <tt>Routing::Mapper::Resources#resources</tt>,
+ # <tt>Routing::Mapper::Scoping#namespace</tt>, and
+ # <tt>Routing::Mapper::Scoping#scope</tt>.
+ #
# == Named routes
#
# Routes can be named by passing an <tt>:as</tt> option,
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 430fcdbe07..589df218a8 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -22,18 +22,22 @@ module ActionDispatch
@app, @constraints, @request = app, constraints, request
end
- def call(env)
+ def matches?(env)
req = @request.new(env)
@constraints.each { |constraint|
if constraint.respond_to?(:matches?) && !constraint.matches?(req)
- return [ 404, {'X-Cascade' => 'pass'}, [] ]
+ return false
elsif constraint.respond_to?(:call) && !constraint.call(*constraint_args(constraint, req))
- return [ 404, {'X-Cascade' => 'pass'}, [] ]
+ return false
end
}
- @app.call(env)
+ return true
+ end
+
+ def call(env)
+ matches?(env) ? @app.call(env) : [ 404, {'X-Cascade' => 'pass'}, [] ]
end
private
@@ -247,7 +251,7 @@ module ActionDispatch
#
# root :to => 'pages#main'
#
- # For options, see the +match+ method's documentation, as +root+ uses it internally.
+ # For options, see +match+, as +root+ uses it internally.
#
# You should put the root route at the top of <tt>config/routes.rb</tt>,
# because this means it will be matched first. As this is the most popular route
@@ -256,15 +260,114 @@ module ActionDispatch
match '/', options.reverse_merge(:as => :root)
end
- # When you set up a regular route, you supply a series of symbols that
- # Rails maps to parts of an incoming HTTP request.
+ # Matches a url pattern to one or more routes. Any symbols in a pattern
+ # are interpreted as url query parameters and thus available as +params+
+ # in an action:
+ #
+ # # sets :controller, :action and :id in params
+ # match ':controller/:action/:id'
+ #
+ # Two of these symbols are special, +:controller+ maps to the controller
+ # and +:action+ to the controller's action. A pattern can also map
+ # wildcard segments (globs) to params:
+ #
+ # match 'songs/*category/:title' => 'songs#show'
+ #
+ # # 'songs/rock/classic/stairway-to-heaven' sets
+ # # params[:category] = 'rock/classic'
+ # # params[:title] = 'stairway-to-heaven'
+ #
+ # When a pattern points to an internal route, the route's +:action+ and
+ # +:controller+ should be set in options or hash shorthand. Examples:
+ #
+ # match 'photos/:id' => 'photos#show'
+ # match 'photos/:id', :to => 'photos#show'
+ # match 'photos/:id', :controller => 'photos', :action => 'show'
+ #
+ # A pattern can also point to a +Rack+ endpoint i.e. anything that
+ # responds to +call+:
+ #
+ # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" }
+ # match 'photos/:id' => PhotoRackApp
+ # # Yes, controller actions are just rack endpoints
+ # match 'photos/:id' => PhotosController.action(:show)
+ #
+ # === Options
+ #
+ # Any options not seen here are passed on as params with the url.
+ #
+ # [:controller]
+ # The route's controller.
+ #
+ # [:action]
+ # The route's action.
+ #
+ # [:path]
+ # The path prefix for the routes.
+ #
+ # [:module]
+ # The namespace for :controller.
+ #
+ # match 'path' => 'c#a', :module => 'sekret', :controller => 'posts'
+ # #=> Sekret::PostsController
+ #
+ # See <tt>Scoping#namespace</tt> for its scope equivalent.
+ #
+ # [:as]
+ # The name used to generate routing helpers.
+ #
+ # [:via]
+ # Allowed HTTP verb(s) for route.
+ #
+ # match 'path' => 'c#a', :via => :get
+ # match 'path' => 'c#a', :via => [:get, :post]
+ #
+ # [:to]
+ # Points to a +Rack+ endpoint. Can be an object that responds to
+ # +call+ or a string representing a controller's action.
+ #
+ # match 'path', :to => 'controller#action'
+ # match 'path', :to => lambda { [200, {}, "Success!"] }
+ # match 'path', :to => RackApp
+ #
+ # [:on]
+ # Shorthand for wrapping routes in a specific RESTful context. Valid
+ # values are :member, :collection, and :new. Only use within
+ # <tt>resource(s)</tt> block. For example:
+ #
+ # resource :bar do
+ # match 'foo' => 'c#a', :on => :member, :via => [:get, :post]
+ # end
#
- # match ':controller/:action/:id/:user_id'
+ # Is equivalent to:
#
- # Two of these symbols are special: :controller maps to the name of a
- # controller in your application, and :action maps to the name of an
- # action within that controller. Anything other than :controller or
- # :action will be available to the action as part of params.
+ # resource :bar do
+ # member do
+ # match 'foo' => 'c#a', :via => [:get, :post]
+ # end
+ # end
+ #
+ # [:constraints]
+ # Constrains parameters with a hash of regular expressions or an
+ # object that responds to #matches?
+ #
+ # match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ }
+ #
+ # class Blacklist
+ # def matches?(request) request.remote_ip == '1.2.3.4' end
+ # end
+ # match 'path' => 'c#a', :constraints => Blacklist.new
+ #
+ # See <tt>Scoping#constraints</tt> for more examples with its scope
+ # equivalent.
+ #
+ # [:defaults]
+ # Sets defaults for parameters
+ #
+ # # Sets params[:format] to 'jpg' by default
+ # match 'path' => 'c#a', :defaults => { :format => 'jpg' }
+ #
+ # See <tt>Scoping#defaults</tt> for its scope equivalent.
def match(path, options=nil)
mapping = Mapping.new(@set, @scope, path, options || {}).to_route
@set.add_route(*mapping)
@@ -279,6 +382,8 @@ module ActionDispatch
#
# mount(SomeRackApp => "some_route")
#
+ # For options, see +match+, as +mount+ uses it internally.
+ #
# All mounted applications come with routing helpers to access them.
# These are named after the class specified, so for the above example
# the helper is either +some_rack_app_path+ or +some_rack_app_url+.
@@ -349,7 +454,7 @@ module ActionDispatch
module HttpHelpers
# Define a route that only recognizes HTTP GET.
- # For supported arguments, see +match+.
+ # For supported arguments, see <tt>Base#match</tt>.
#
# Example:
#
@@ -359,7 +464,7 @@ module ActionDispatch
end
# Define a route that only recognizes HTTP POST.
- # For supported arguments, see +match+.
+ # For supported arguments, see <tt>Base#match</tt>.
#
# Example:
#
@@ -369,7 +474,7 @@ module ActionDispatch
end
# Define a route that only recognizes HTTP PUT.
- # For supported arguments, see +match+.
+ # For supported arguments, see <tt>Base#match</tt>.
#
# Example:
#
@@ -379,7 +484,7 @@ module ActionDispatch
end
# Define a route that only recognizes HTTP PUT.
- # For supported arguments, see +match+.
+ # For supported arguments, see <tt>Base#match</tt>.
#
# Example:
#
@@ -458,51 +563,38 @@ module ActionDispatch
super
end
- # === Supported options
- # [:module]
- # If you want to route /posts (without the prefix /admin) to
- # Admin::PostsController, you could use
- #
- # scope :module => "admin" do
- # resources :posts
- # end
- #
- # [:path]
- # If you want to prefix the route, you could use
+ # Scopes a set of routes to the given default options.
#
- # scope :path => "/admin" do
- # resources :posts
- # end
+ # Take the following route definition as an example:
#
- # This will prefix all of the +posts+ resource's requests with '/admin'
- #
- # [:as]
- # Prefixes the routing helpers in this scope with the specified label.
+ # scope :path => ":account_id", :as => "account" do
+ # resources :projects
+ # end
#
- # scope :as => "sekret" do
- # resources :posts
- # end
+ # This generates helpers such as +account_projects_path+, just like +resources+ does.
+ # The difference here being that the routes generated are like /rails/projects/2,
+ # rather than /accounts/rails/projects/2.
#
- # Helpers such as +posts_path+ will now be +sekret_posts_path+
+ # === Options
#
- # [:shallow_path]
+ # Takes same options as <tt>Base#match</tt> and <tt>Resources#resources</tt>.
#
- # Prefixes nested shallow routes with the specified path.
+ # === Examples
#
- # scope :shallow_path => "sekret" do
- # resources :posts do
- # resources :comments, :shallow => true
- # end
+ # # route /posts (without the prefix /admin) to Admin::PostsController
+ # scope :module => "admin" do
+ # resources :posts
+ # end
#
- # The +comments+ resource here will have the following routes generated for it:
+ # # prefix the posts resource's requests with '/admin'
+ # scope :path => "/admin" do
+ # resources :posts
+ # end
#
- # post_comments GET /sekret/posts/:post_id/comments(.:format)
- # post_comments POST /sekret/posts/:post_id/comments(.:format)
- # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format)
- # edit_comment GET /sekret/comments/:id/edit(.:format)
- # comment GET /sekret/comments/:id(.:format)
- # comment PUT /sekret/comments/:id(.:format)
- # comment DELETE /sekret/comments/:id(.:format)
+ # # prefix the routing helper name: sekret_posts_path instead of posts_path
+ # scope :as => "sekret" do
+ # resources :posts
+ # end
def scope(*args)
options = args.extract_options!
options = options.dup
@@ -558,50 +650,38 @@ module ActionDispatch
#
# This generates the following routes:
#
- # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"}
- # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"}
- # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"}
- # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"}
- # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"}
- # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"}
- # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"}
- # === Supported options
+ # admin_posts GET /admin/posts(.:format) {:action=>"index", :controller=>"admin/posts"}
+ # admin_posts POST /admin/posts(.:format) {:action=>"create", :controller=>"admin/posts"}
+ # new_admin_post GET /admin/posts/new(.:format) {:action=>"new", :controller=>"admin/posts"}
+ # edit_admin_post GET /admin/posts/:id/edit(.:format) {:action=>"edit", :controller=>"admin/posts"}
+ # admin_post GET /admin/posts/:id(.:format) {:action=>"show", :controller=>"admin/posts"}
+ # admin_post PUT /admin/posts/:id(.:format) {:action=>"update", :controller=>"admin/posts"}
+ # admin_post DELETE /admin/posts/:id(.:format) {:action=>"destroy", :controller=>"admin/posts"}
#
- # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ options all default to the name of the namespace.
+ # === Options
#
- # [:path]
- # The path prefix for the routes.
+ # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+
+ # options all default to the name of the namespace.
+ #
+ # For options, see <tt>Base#match</tt>. For +:shallow_path+ option, see
+ # <tt>Resources#resources</tt>.
#
+ # === Examples
+ #
+ # # accessible through /sekret/posts rather than /admin/posts
# namespace :admin, :path => "sekret" do
# resources :posts
# end
#
- # All routes for the above +resources+ will be accessible through +/sekret/posts+, rather than +/admin/posts+
- #
- # [:module]
- # The namespace for the controllers.
- #
+ # # maps to Sekret::PostsController rather than Admin::PostsController
# namespace :admin, :module => "sekret" do
# resources :posts
# end
#
- # The +PostsController+ here should go in the +Sekret+ namespace and so it should be defined like this:
- #
- # class Sekret::PostsController < ApplicationController
- # # code go here
+ # # generates sekret_posts_path rather than admin_posts_path
+ # namespace :admin, :as => "sekret" do
+ # resources :posts
# end
- #
- # [:as]
- # Changes the name used in routing helpers for this namespace.
- #
- # namespace :admin, :as => "sekret" do
- # resources :posts
- # end
- #
- # Routing helpers such as +admin_posts_path+ will now be +sekret_posts_path+.
- #
- # [:shallow_path]
- # See the +scope+ method.
def namespace(path, options = {})
path = path.to_s
options = { :path => path, :as => path, :module => path,
@@ -668,9 +748,9 @@ module ActionDispatch
end
# Allows you to set default parameters for a route, such as this:
- # defaults :id => 'home' do
- # match 'scoped_pages/(:id)', :to => 'pages#show'
- # end
+ # defaults :id => 'home' do
+ # match 'scoped_pages/(:id)', :to => 'pages#show'
+ # end
# Using this, the +:id+ parameter here will default to 'home'.
def defaults(defaults = {})
scope(:defaults => defaults) { yield }
@@ -767,6 +847,14 @@ module ActionDispatch
# resources :posts, :comments
# end
#
+ # By default the :id parameter doesn't accept dots. If you need to
+ # use dots as part of the :id parameter add a constraint which
+ # overrides this restriction, e.g:
+ #
+ # resources :articles, :id => /[^\/]+/
+ #
+ # This allows any character other than a slash as part of your :id.
+ #
module Resources
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
# a path appended since they fit properly in their scope level.
@@ -815,7 +903,8 @@ module ActionDispatch
alias :member_name :singular
- # Checks for uncountable plurals, and appends "_index" if they're.
+ # Checks for uncountable plurals, and appends "_index" if the plural
+ # and singular form are the same.
def collection_name
singular == plural ? "#{plural}_index" : plural
end
@@ -894,6 +983,9 @@ module ActionDispatch
# GET /geocoder/edit
# PUT /geocoder
# DELETE /geocoder
+ #
+ # === Options
+ # Takes same options as +resources+.
def resource(*resources, &block)
options = resources.extract_options!
@@ -955,7 +1047,9 @@ module ActionDispatch
# PUT /photos/:id/comments/:id
# DELETE /photos/:id/comments/:id
#
- # === Supported options
+ # === Options
+ # Takes same options as <tt>Base#match</tt> as well as:
+ #
# [:path_names]
# Allows you to change the paths of the seven default actions.
# Paths not specified are not changed.
@@ -964,20 +1058,59 @@ module ActionDispatch
#
# The above example will now change /posts/new to /posts/brand_new
#
- # [:module]
- # Set the module where the controller can be found. Defaults to nothing.
+ # [:only]
+ # Only generate routes for the given actions.
#
- # resources :posts, :module => "admin"
+ # resources :cows, :only => :show
+ # resources :cows, :only => [:show, :index]
#
- # All requests to the posts resources will now go to +Admin::PostsController+.
+ # [:except]
+ # Generate all routes except for the given actions.
#
- # [:path]
+ # resources :cows, :except => :show
+ # resources :cows, :except => [:show, :index]
+ #
+ # [:shallow]
+ # Generates shallow routes for nested resource(s). When placed on a parent resource,
+ # generates shallow routes for all nested resources.
+ #
+ # resources :posts, :shallow => true do
+ # resources :comments
+ # end
+ #
+ # Is the same as:
+ #
+ # resources :posts do
+ # resources :comments
+ # end
+ # resources :comments
+ #
+ # [:shallow_path]
+ # Prefixes nested shallow routes with the specified path.
+ #
+ # scope :shallow_path => "sekret" do
+ # resources :posts do
+ # resources :comments, :shallow => true
+ # end
+ # end
+ #
+ # The +comments+ resource here will have the following routes generated for it:
+ #
+ # post_comments GET /sekret/posts/:post_id/comments(.:format)
+ # post_comments POST /sekret/posts/:post_id/comments(.:format)
+ # new_post_comment GET /sekret/posts/:post_id/comments/new(.:format)
+ # edit_comment GET /sekret/comments/:id/edit(.:format)
+ # comment GET /sekret/comments/:id(.:format)
+ # comment PUT /sekret/comments/:id(.:format)
+ # comment DELETE /sekret/comments/:id(.:format)
#
- # Set a path prefix for this resource.
+ # === Examples
#
- # resources :posts, :path => "admin"
+ # # routes call Admin::PostsController
+ # resources :posts, :module => "admin"
#
- # All actions for this resource will now be at +/admin/posts+.
+ # # resource actions are at /admin/posts.
+ # resources :posts, :path => "admin"
def resources(*resources, &block)
options = resources.extract_options!
@@ -1099,7 +1232,7 @@ module ActionDispatch
end
def shallow
- scope(:shallow => true) do
+ scope(:shallow => true, :shallow_path => @scope[:path]) do
yield
end
end
@@ -1309,7 +1442,7 @@ module ActionDispatch
name = case @scope[:scope_level]
when :nested
- [member_name, prefix]
+ [name_prefix, prefix]
when :collection
[prefix, name_prefix, collection_name]
when :new
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 49e237f8db..82c4fadb50 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -99,11 +99,9 @@ module ActionDispatch
record = extract_record(record_or_hash_or_array)
record = record.to_model if record.respond_to?(:to_model)
- args = case record_or_hash_or_array
- when Hash; [ record_or_hash_or_array ]
- when Array; record_or_hash_or_array.dup
- else [ record_or_hash_or_array ]
- end
+ args = Array === record_or_hash_or_array ?
+ record_or_hash_or_array.dup :
+ [ record_or_hash_or_array ]
inflection = if options[:action] && options[:action].to_s == "new"
args.pop
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 03bfe178e5..fc86d52a3a 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -50,12 +50,13 @@ module ActionDispatch
private
def controller_reference(controller_param)
+ controller_name = "#{controller_param.camelize}Controller"
+
unless controller = @controllers[controller_param]
- controller_name = "#{controller_param.camelize}Controller"
controller = @controllers[controller_param] =
- ActiveSupport::Dependencies.ref(controller_name)
+ ActiveSupport::Dependencies.reference(controller_name)
end
- controller.get
+ controller.get(controller_name)
end
def dispatch(controller, action, env)
@@ -450,7 +451,7 @@ module ActionDispatch
end
def raise_routing_error
- raise ActionController::RoutingError.new("No route matches #{options.inspect}")
+ raise ActionController::RoutingError, "No route matches #{options.inspect}"
end
def different_controller?
@@ -540,7 +541,9 @@ module ActionDispatch
end
dispatcher = route.app
- dispatcher = dispatcher.app while dispatcher.is_a?(Mapper::Constraints)
+ while dispatcher.is_a?(Mapper::Constraints) && dispatcher.matches?(env) do
+ dispatcher = dispatcher.app
+ end
if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false)
dispatcher.prepare_params!(params)
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index 1558c3ae05..77a15f3e97 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -20,7 +20,7 @@ module ActionDispatch
#
# You can also pass an explicit status number like <tt>assert_response(501)</tt>
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
- # See ActionDispatch::StatusCodes for a full list.
+ # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
#
# ==== Examples
#
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index 1390b74a95..11e8c63fa0 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -37,9 +37,6 @@ module ActionDispatch
#
# # Test a custom route
# assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1')
- #
- # # Check a Simply RESTful generated route
- # assert_recognizes list_items_url, 'items/list'
def assert_recognizes(expected_options, path, extras={}, message=nil)
request = recognized_request_for(path)
@@ -124,7 +121,8 @@ module ActionDispatch
options[:controller] = "/#{controller}"
end
- assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
+ generate_options = options.dup.delete_if{ |k,v| defaults.key?(k) }
+ assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
end
# A helper to make it easier to test different route configurations.
diff --git a/actionpack/lib/action_pack.rb b/actionpack/lib/action_pack.rb
index 1a1497385a..914b13dbfb 100644
--- a/actionpack/lib/action_pack.rb
+++ b/actionpack/lib/action_pack.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index dada64a86f..60665387b6 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 15944138f7..ab8c6259c5 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -18,7 +18,7 @@ module ActionView #:nodoc:
# following loop for names:
#
# <b>Names of all the people</b>
- # <% for person in @people %>
+ # <% @people.each do |person| %>
# Name: <%= person.name %><br/>
# <% end %>
#
@@ -172,6 +172,14 @@ module ActionView #:nodoc:
class << self
delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
delegate :logger, :to => 'ActionController::Base', :allow_nil => true
+
+ def cache_template_loading
+ ActionView::Resolver.caching?
+ end
+
+ def cache_template_loading=(value)
+ ActionView::Resolver.caching = value
+ end
end
attr_accessor :_template
@@ -224,8 +232,8 @@ module ActionView #:nodoc:
@controller_path ||= controller && controller.controller_path
end
- def controller_prefix
- @controller_prefix ||= controller && controller._prefix
+ def controller_prefixes
+ @controller_prefixes ||= controller && controller._prefixes
end
ActiveSupport.run_load_hooks(:action_view, self)
diff --git a/actionpack/lib/action_view/helpers.rb b/actionpack/lib/action_view/helpers.rb
index 41013c800c..d338ce616a 100644
--- a/actionpack/lib/action_view/helpers.rb
+++ b/actionpack/lib/action_view/helpers.rb
@@ -18,7 +18,7 @@ module ActionView #:nodoc:
autoload :JavaScriptHelper, "action_view/helpers/javascript_helper"
autoload :NumberHelper
autoload :PrototypeHelper
- autoload :RawOutputHelper
+ autoload :OutputSafetyHelper
autoload :RecordTagHelper
autoload :SanitizeHelper
autoload :ScriptaculousHelper
@@ -48,7 +48,7 @@ module ActionView #:nodoc:
include JavaScriptHelper
include NumberHelper
include PrototypeHelper
- include RawOutputHelper
+ include OutputSafetyHelper
include RecordTagHelper
include SanitizeHelper
include ScriptaculousHelper
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 e52797042f..52eb43a1cd 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
@@ -11,7 +11,9 @@ module ActionView
attr_reader :config, :asset_paths
class_attribute :expansions
- self.expansions = { }
+ def self.inherited(base)
+ base.expansions = { }
+ end
def initialize(config, asset_paths)
@config = config
@@ -69,9 +71,21 @@ module ActionView
if sources.first == :all
collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}")
else
- sources.collect do |source|
- determine_source(source, expansions)
- end.flatten
+ sources.inject([]) do |list, source|
+ determined_source = determine_source(source, expansions)
+ update_source_list(list, determined_source)
+ end
+ end
+ end
+
+ def update_source_list(list, source)
+ case source
+ when String
+ list.delete(source)
+ list << source
+ when Array
+ updated_sources = source - list
+ list.concat(updated_sources)
end
end
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
index b4e61f2034..014a03c54d 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb
@@ -21,7 +21,7 @@ module ActionView
@controller = controller
end
- # Add the the extension +ext+ if not present. Return full URLs otherwise untouched.
+ # Add the extension +ext+ if not present. Return full URLs otherwise untouched.
# Prefix with <tt>/dir/</tt> if lacking a leading +/+. Account for relative URL
# roots. Rewrite the asset path for cache-busting asset ids. Include
# asset host, if configured, with the correct request protocol.
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 6581e1d6f2..b9126af944 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
@@ -33,13 +33,21 @@ module ActionView
all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application'
((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq
else
- expanded_sources = sources.collect do |source|
- determine_source(source, expansions)
- end.flatten
- expanded_sources << "application" if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}"))
+ expanded_sources = sources.inject([]) do |list, source|
+ determined_source = determine_source(source, expansions)
+ update_source_list(list, determined_source)
+ end
+ add_application_js(expanded_sources, sources)
expanded_sources
end
end
+
+ def add_application_js(expanded_sources, sources)
+ if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}"))
+ expanded_sources.delete('application')
+ expanded_sources << "application"
+ end
+ end
end
@@ -59,7 +67,10 @@ module ActionView
# <script type="text/javascript" src="/javascripts/body.js"></script>
# <script type="text/javascript" src="/javascripts/tail.js"></script>
def register_javascript_expansion(expansions)
- JavascriptIncludeTag.expansions.merge!(expansions)
+ js_expansions = JavascriptIncludeTag.expansions
+ expansions.each do |key, values|
+ js_expansions[key] = (js_expansions[key] || []) | Array(values) if values
+ end
end
end
@@ -170,4 +181,4 @@ module ActionView
end
end
-end \ No newline at end of file
+end
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 d02b28d7f6..f3e041de95 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
@@ -44,7 +44,10 @@ module ActionView
# <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
# <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
def register_stylesheet_expansion(expansions)
- StylesheetIncludeTag.expansions.merge!(expansions)
+ style_expansions = StylesheetIncludeTag.expansions
+ expansions.each do |key, values|
+ style_expansions[key] = (style_expansions[key] || []) | Array(values) if values
+ end
end
end
@@ -141,4 +144,4 @@ module ActionView
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
index f544a9d147..385378ea29 100644
--- a/actionpack/lib/action_view/helpers/cache_helper.rb
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -2,31 +2,29 @@ module ActionView
# = Action View Cache Helper
module Helpers
module CacheHelper
- # This helper to exposes a method for caching of view fragments.
- # See ActionController::Caching::Fragments for usage instructions.
+ # This helper exposes a method for caching fragments of a view
+ # rather than an entire action or page. This technique is useful
+ # caching pieces like menus, lists of newstopics, static HTML
+ # fragments, and so on. This method takes a block that contains
+ # the content you wish to cache.
#
- # A method for caching fragments of a view rather than an entire
- # action or page. This technique is useful caching pieces like
- # menus, lists of news topics, static HTML fragments, and so on.
- # This method takes a block that contains the content you wish
- # to cache. See ActionController::Caching::Fragments for more
- # information.
+ # See ActionController::Caching::Fragments for usage instructions.
#
# ==== Examples
- # If you wanted to cache a navigation menu, you could do the
- # following.
+ # If you want to cache a navigation menu, you can do following:
#
# <% cache do %>
# <%= render :partial => "menu" %>
# <% end %>
#
- # You can also cache static content...
+ # You can also cache static content:
#
# <% cache do %>
# <p>Hello users! Welcome to our website!</p>
# <% end %>
#
- # ...and static content mixed with RHTML content.
+ # Static content with embedded ruby content can be cached as
+ # well:
#
# <% cache do %>
# Topics:
@@ -46,8 +44,8 @@ module ActionView
private
# TODO: Create an object that has caching read/write on it
def fragment_for(name = {}, options = nil, &block) #:nodoc:
- if controller.fragment_exist?(name, options)
- controller.read_fragment(name, options)
+ if fragment = controller.read_fragment(name, options)
+ fragment
else
# VIEW TODO: Make #capture usable outside of ERB
# This dance is needed because Builder can't use capture
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index 875ec9b77b..dc8e4bc316 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -1,5 +1,6 @@
require 'date'
require 'action_view/helpers/tag_helper'
+require 'active_support/core_ext/date/conversions'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/object/with_options'
@@ -566,6 +567,27 @@ module ActionView
def select_year(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_year
end
+
+ # Returns an html time tag for the given date or time.
+ #
+ # ==== Examples
+ # time_tag Date.today # =>
+ # <time datetime="2010-11-04">November 04, 2010</time>
+ # time_tag Time.now # =>
+ # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
+ # time_tag Date.yesterday, 'Yesterday' # =>
+ # <time datetime="2010-11-03">Yesterday</time>
+ # time_tag Date.today, :pubdate => true # =>
+ # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time>
+ #
+ def time_tag(date_or_time, *args)
+ options = args.extract_options!
+ format = options.delete(:format) || :long
+ content = args.first || I18n.l(date_or_time, :format => format)
+ datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339
+
+ content_tag(:time, content, options.reverse_merge(:datetime => datetime))
+ end
end
class DateTimeSelector #:nodoc:
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index ef5bbd8ae3..befaa3e8d9 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -298,6 +298,23 @@ module ActionView
#
# If you don't need to attach a form to a model instance, then check out
# FormTagHelper#form_tag.
+ #
+ # === Form to external resources
+ #
+ # When you build forms to external resources sometimes you need to set an authenticity token or just render a form
+ # without it, for example when you submit data to a payment gateway number and types of fields could be limited.
+ #
+ # To set an authenticity token you need to pass an <tt>:authenticity_token</tt> parameter
+ #
+ # <%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
+ # ...
+ # <% end %>
+ #
+ # If you don't want to an authenticity token field be rendered at all just pass <tt>false</tt>:
+ #
+ # <%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
+ # ...
+ # <% end %>
def form_for(record, options = {}, &proc)
raise ArgumentError, "Missing block" unless block_given?
@@ -314,6 +331,8 @@ module ActionView
end
options[:html][:remote] = options.delete(:remote)
+ options[:html][:authenticity_token] = options.delete(:authenticity_token)
+
builder = options[:parent_builder] = instantiate_builder(object_name, object, options, &proc)
fields_for = fields_for(object_name, object, options, &proc)
default_options = builder.multipart? ? { :multipart => true } : {}
@@ -530,8 +549,11 @@ module ActionView
# <% end %>
# ...
# <% end %>
- def fields_for(record, record_object = nil, options = nil, &block)
- capture(instantiate_builder(record, record_object, options, &block), &block)
+ def fields_for(record, record_object = nil, options = {}, &block)
+ builder = instantiate_builder(record, record_object, options, &block)
+ output = capture(builder, &block)
+ output.concat builder.hidden_field(:id) if output && options[:hidden_field_id] && !builder.emitted_hidden_id?
+ output
end
# Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
@@ -858,8 +880,7 @@ module ActionView
end
end
- module InstanceTagMethods #:nodoc:
- extend ActiveSupport::Concern
+ class InstanceTag
include Helpers::CaptureHelper, Context, Helpers::TagHelper, Helpers::FormTagHelper
attr_reader :object, :method_name, :object_name
@@ -1025,7 +1046,7 @@ module ActionView
self.class.value_before_type_cast(object, @method_name)
end
- module ClassMethods
+ class << self
def value(object, method_name)
object.send method_name if object
end
@@ -1111,11 +1132,7 @@ module ActionView
end
end
- class InstanceTag
- include InstanceTagMethods
- end
-
- class FormBuilder #:nodoc:
+ class FormBuilder
# The methods which wrap a form helper call.
class_attribute :field_helpers
self.field_helpers = (FormHelper.instance_method_names - ['form_for'])
@@ -1248,7 +1265,7 @@ module ActionView
def submit(value=nil, options={})
value, options = nil, value if value.is_a?(Hash)
value ||= submit_default_value
- @template.submit_tag(value, options.reverse_merge(:id => "#{object_name}_submit"))
+ @template.submit_tag(value, options)
end
def emitted_hidden_id?
@@ -1309,14 +1326,8 @@ module ActionView
def fields_for_nested_model(name, object, options, block)
object = convert_to_model(object)
- if object.persisted?
- @template.fields_for(name, object, options) do |builder|
- block.call(builder)
- @template.concat builder.hidden_field(:id) unless builder.emitted_hidden_id?
- end
- else
- @template.fields_for(name, object, options, &block)
- end
+ options[:hidden_field_id] = object.persisted?
+ @template.fields_for(name, object, options, &block)
end
def nested_child_index(name)
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index 6ac8577785..7698602022 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -533,7 +533,7 @@ module ActionView
else
selected = Array.wrap(selected)
options = selected.extract_options!.symbolize_keys
- [ options[:selected] || selected , options[:disabled] ]
+ [ options.include?(:selected) ? options[:selected] : selected, options[:disabled] ]
end
end
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 50f065f03d..71f8534cbf 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -25,6 +25,9 @@ module ActionView
# * <tt>:method</tt> - The method to use when submitting the form, usually either "get" or "post".
# If "put", "delete", or another verb is used, a hidden input with name <tt>_method</tt>
# is added to simulate the verb over post.
+ # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to
+ # pass custom authenticity token string, or to not add authenticity_token field at all
+ # (by passing <tt>false</tt>).
# * A list of parameters to feed to the URL the form will be posted to.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behaviour. By default this behaviour is an ajax submit.
@@ -47,6 +50,12 @@ module ActionView
# <%= form_tag('/posts', :remote => true) %>
# # => <form action="/posts" method="post" data-remote="true">
#
+ # form_tag('http://far.away.com/form', :authenticity_token => false)
+ # # form without authenticity token
+ #
+ # form_tag('http://far.away.com/form', :authenticity_token => "cf50faa3fe97702ca1ae")
+ # # form with custom authenticity token
+ #
def form_tag(url_for_options = {}, options = {}, *parameters_for_url, &block)
html_options = html_options_for_form(url_for_options, options, *parameters_for_url)
if block_given?
@@ -68,7 +77,7 @@ module ActionView
# * Any other key creates standard HTML attributes for the tag.
#
# ==== Examples
- # select_tag "people", options_from_collection_for_select(@people, "name", "id")
+ # select_tag "people", options_from_collection_for_select(@people, "id", "name")
# # <select id="people" name="people"><option value="1">David</option></select>
#
# select_tag "people", "<option>David</option>"
@@ -112,6 +121,7 @@ module ActionView
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:size</tt> - The number of visible characters that will fit in the input.
# * <tt>:maxlength</tt> - The maximum number of characters that the browser will allow the user to enter.
+ # * <tt>:placeholder</tt> - The text contained in the field by default which is removed when the field receives focus.
# * Any other key creates standard HTML attributes for the tag.
#
# ==== Examples
@@ -121,6 +131,9 @@ module ActionView
# text_field_tag 'query', 'Enter your search query here'
# # => <input id="query" name="query" type="text" value="Enter your search query here" />
#
+ # text_field_tag 'search', nil, :placeholder => 'Enter search term...'
+ # # => <input id="search" name="search" placeholder="Enter search term..." type="text" />
+ #
# text_field_tag 'request', nil, :class => 'special_input'
# # => <input class="special_input" id="request" name="request" type="text" />
#
@@ -397,6 +410,59 @@ module ActionView
tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys)
end
+ # Creates a button element that defines a <tt>submit</tt> button,
+ # <tt>reset</tt>button or a generic button which can be used in
+ # JavaScript, for example. You can use the button tag as a regular
+ # submit tag but it isn't supported in legacy browsers. However,
+ # the button tag allows richer labels such as images and emphasis,
+ # so this helper will also accept a block.
+ #
+ # ==== Options
+ # * <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.
+ # * <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.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Examples
+ # button_tag
+ # # => <button name="button" type="submit">Button</button>
+ #
+ # button_tag(:type => 'button') do
+ # content_tag(:strong, 'Ask me!')
+ # end
+ # # => <button name="button" type="button">
+ # <strong>Ask me!</strong>
+ # </button>
+ #
+ # button_tag "Checkout", :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.stringify_keys!
+
+ if disable_with = options.delete("disable_with")
+ options["data-disable-with"] = disable_with
+ end
+
+ if confirm = options.delete("confirm")
+ options["data-confirm"] = confirm
+ end
+
+ options.reverse_merge! 'name' => 'button', 'type' => 'submit'
+
+ content_tag :button, content_or_options || 'Button', options, &block
+ end
+
# Displays an image which when clicked will submit the form.
#
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
@@ -530,6 +596,7 @@ module ActionView
html_options["action"] = url_for(url_for_options, *parameters_for_url)
html_options["accept-charset"] = "UTF-8"
html_options["data-remote"] = true if html_options.delete("remote")
+ html_options["authenticity_token"] = html_options.delete("authenticity_token") if html_options.has_key?("authenticity_token")
end
end
@@ -537,6 +604,7 @@ module ActionView
snowman_tag = tag(:input, :type => "hidden",
:name => "utf8", :value => "&#x2713;".html_safe)
+ authenticity_token = html_options.delete("authenticity_token")
method = html_options.delete("method").to_s
method_tag = case method
@@ -545,10 +613,10 @@ module ActionView
''
when /^post$/i, "", nil
html_options["method"] = "post"
- token_tag
+ token_tag(authenticity_token)
else
html_options["method"] = "post"
- tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag
+ tag(:input, :type => "hidden", :name => "_method", :value => method) + token_tag(authenticity_token)
end
tags = snowman_tag << method_tag
@@ -568,11 +636,12 @@ module ActionView
output.safe_concat("</form>")
end
- def token_tag
- unless protect_against_forgery?
+ def token_tag(token)
+ if token == false || !protect_against_forgery?
''
else
- tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
+ token = form_authenticity_token if token.nil?
+ tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token)
end
end
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index a9400c347f..26f8dce3c3 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -270,12 +270,13 @@ module ActionView
digits, rounded_number = 1, 0
else
digits = (Math.log10(number.abs) + 1).floor
- rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision)
+ rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
+ digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
end
precision -= digits
precision = precision > 0 ? precision : 0 #don't let it be negative
else
- rounded_number = BigDecimal.new((number * (10 ** precision)).to_s).round.to_f / 10 ** precision
+ rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
end
formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
if strip_insignificant_zeros
diff --git a/actionpack/lib/action_view/helpers/output_safety_helper.rb b/actionpack/lib/action_view/helpers/output_safety_helper.rb
new file mode 100644
index 0000000000..a035dd70ad
--- /dev/null
+++ b/actionpack/lib/action_view/helpers/output_safety_helper.rb
@@ -0,0 +1,38 @@
+require 'active_support/core_ext/string/output_safety'
+
+module ActionView #:nodoc:
+ # = Action View Raw Output Helper
+ module Helpers #:nodoc:
+ module OutputSafetyHelper
+ # This method outputs without escaping a string. Since escaping tags is
+ # now default, this can be used when you don't want Rails to automatically
+ # escape tags. This is not recommended if the data is coming from the user's
+ # input.
+ #
+ # For example:
+ #
+ # <%=raw @user.name %>
+ def raw(stringish)
+ stringish.to_s.html_safe
+ end
+
+ # This method returns a html safe string similar to what <tt>Array#join</tt>
+ # would return. All items in the array, including the supplied separator, are
+ # html escaped unless they are html safe, and the returned string is marked
+ # as html safe.
+ #
+ # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
+ # # => "<p>foo</p>&lt;br /&gt;&lt;p&gt;bar&lt;/p&gt;"
+ #
+ # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
+ # # => "<p>foo</p><br /><p>bar</p>"
+ #
+ def safe_join(array, sep=$,)
+ sep ||= "".html_safe
+ sep = ERB::Util.html_escape(sep)
+
+ array.map { |i| ERB::Util.html_escape(i) }.join(sep).html_safe
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/raw_output_helper.rb b/actionpack/lib/action_view/helpers/raw_output_helper.rb
deleted file mode 100644
index 216683a2e0..0000000000
--- a/actionpack/lib/action_view/helpers/raw_output_helper.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module ActionView #:nodoc:
- # = Action View Raw Output Helper
- module Helpers #:nodoc:
- module RawOutputHelper
- # This method outputs without escaping a string. Since escaping tags is
- # now default, this can be used when you don't want Rails to automatically
- # escape tags. This is not recommended if the data is coming from the user's
- # input.
- #
- # For example:
- #
- # <%=raw @user.name %>
- def raw(stringish)
- stringish.to_s.html_safe
- end
- end
- end
-end \ No newline at end of file
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
index ee51617a2b..786af5ca58 100644
--- a/actionpack/lib/action_view/helpers/tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -14,7 +14,7 @@ module ActionView
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
autoplay controls loop selected hidden scoped async
defer reversed ismap seemless muted required
- autofocus novalidate formnovalidate open).to_set
+ autofocus novalidate formnovalidate open pubdate).to_set
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
# Returns an empty HTML tag of type +name+ which by default is XHTML
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 3d276000a1..2d3c5fe7e7 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -234,6 +234,10 @@ module ActionView
#
# You can pass any HTML attributes into <tt>html_options</tt>. These
# will be added to all created paragraphs.
+ #
+ # ==== Options
+ # * <tt>:sanitize</tt> - If +false+, does not sanitize +text+.
+ #
# ==== Examples
# my_text = "Here is some basic text...\n...with a line break."
#
@@ -247,6 +251,9 @@ module ActionView
#
# simple_format("Look ma! A class!", :class => 'description')
# # => "<p class='description'>Look ma! A class!</p>"
+ #
+ # simple_format("<span>I'm allowed!</span> It's true.", {}, :sanitize => false)
+ # # => "<p><span>I'm allowed!</span> It's true.</p>"
def simple_format(text, html_options={}, options={})
text = ''.html_safe if text.nil?
start_tag = tag('p', html_options, true)
@@ -459,7 +466,7 @@ module ActionView
end
AUTO_LINK_RE = %r{
- (?: ([\w+.:-]+:)// | www\. )
+ (?: ([0-9A-Za-z+.:-]+:)// | www\. )
[^\s<]+
}x
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index c23315b344..2cd2dca711 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -253,8 +253,9 @@ module ActionView
# using the +link_to+ method with the <tt>:method</tt> modifier as described in
# the +link_to+ documentation.
#
- # The generated form element has a class name of <tt>button_to</tt>
- # to allow styling of the form itself and its children. You can control
+ # By default, the generated form element has a class name of <tt>button_to</tt>
+ # 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
@@ -275,6 +276,8 @@ module ActionView
# processed normally, otherwise no action is taken.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behaviour. By default this behaviour is an ajax submit.
+ # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
+ # be placed
#
# ==== Examples
# <%= button_to "New", :action => "new" %>
@@ -283,6 +286,12 @@ module ActionView
# # </form>"
#
#
+ # <%= button_to "New", :action => "new", :form_class => "new-thing" %>
+ # # => "<form method="post" action="/controller/new" class="new-thing">
+ # # <div><input value="New" type="submit" /></div>
+ # # </form>"
+ #
+ #
# <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
# :confirm => "Are you sure?", :method => :delete %>
# # => "<form method="post" action="/images/delete/1" class="button_to">
@@ -312,6 +321,7 @@ module ActionView
end
form_method = method.to_s == 'get' ? 'get' : 'post'
+ form_class = html_options.delete('form_class') || 'button_to'
remote = html_options.delete('remote')
@@ -327,7 +337,7 @@ module ActionView
html_options.merge!("type" => "submit", "value" => name)
- ("<form method=\"#{form_method}\" action=\"#{ERB::Util.html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"button_to\"><div>" +
+ ("<form method=\"#{form_method}\" action=\"#{ERB::Util.html_escape(url)}\" #{"data-remote=\"true\"" if remote} class=\"#{ERB::Util.html_escape(form_class)}\"><div>" +
method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe
end
@@ -487,13 +497,14 @@ module ActionView
email_address_obfuscated = email_address.dup
email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at")
email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot")
-
case encode
when "javascript"
- string =
- "document.write('#{content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))}');".unpack('C*').map { |c|
- sprintf("%%%x", c)
- }.join
+ string = ''
+ html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe))
+ html = escape_javascript(html)
+ "document.write('#{html}');".each_byte do |c|
+ string << sprintf("%%%x", c)
+ end
"<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe
when "hex"
email_address_encoded = email_address_obfuscated.unpack('C*').map {|c|
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index d524c68450..06c607931d 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -78,17 +78,17 @@ module ActionView
@view_paths = ActionView::Base.process_view_paths(paths)
end
- def find(name, prefix = nil, partial = false, keys = [])
- @view_paths.find(*args_for_lookup(name, prefix, partial, keys))
+ def find(name, prefixes = [], partial = false, keys = [])
+ @view_paths.find(*args_for_lookup(name, prefixes, partial, keys))
end
alias :find_template :find
- def find_all(name, prefix = nil, partial = false, keys = [])
- @view_paths.find_all(*args_for_lookup(name, prefix, partial, keys))
+ def find_all(name, prefixes = [], partial = false, keys = [])
+ @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys))
end
- def exists?(name, prefix = nil, partial = false, keys = [])
- @view_paths.exists?(*args_for_lookup(name, prefix, partial, keys))
+ def exists?(name, prefixes = [], partial = false, keys = [])
+ @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys))
end
alias :template_exists? :exists?
@@ -107,18 +107,26 @@ module ActionView
protected
- def args_for_lookup(name, prefix, partial, keys) #:nodoc:
- name, prefix = normalize_name(name, prefix)
- [name, prefix, partial || false, @details, details_key, keys]
+ def args_for_lookup(name, prefixes, partial, keys) #:nodoc:
+ name, prefixes = normalize_name(name, prefixes)
+ [name, prefixes, partial || false, @details, details_key, keys]
end
# Support legacy foo.erb names even though we now ignore .erb
# as well as incorrectly putting part of the path in the template
# name instead of the prefix.
- def normalize_name(name, prefix) #:nodoc:
+ def normalize_name(name, prefixes) #:nodoc:
name = name.to_s.gsub(handlers_regexp, '')
parts = name.split('/')
- return parts.pop, [prefix, *parts].compact.join("/")
+ name = parts.pop
+
+ prefixes = if prefixes.blank?
+ [parts.join('/')]
+ else
+ prefixes.map { |prefix| [prefix, *parts].compact.join('/') }
+ end
+
+ return name, prefixes
end
def default_handlers #:nodoc:
@@ -156,11 +164,11 @@ module ActionView
@frozen_formats = true
end
- # Overload formats= to reject [:"*/*"] values.
+ # Overload formats= to reject ["*/*"] values.
def formats=(values)
if values && values.size == 1
value = values.first
- values = nil if value == :"*/*"
+ values = nil if value == "*/*"
values << :html if value == :js
end
super(values)
@@ -178,11 +186,11 @@ module ActionView
end
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
- # to i18n_config, it means that it's has a copy of the original I18n configuration and it's
+ # to original_config, it means that it's has a copy of the original I18n configuration and it's
# acting as proxy, which we need to skip.
def locale=(value)
if value
- config = I18n.config.respond_to?(:i18n_config) ? I18n.config.i18n_config : I18n.config
+ config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
config.locale = value
end
@@ -237,4 +245,4 @@ module ActionView
include Details
include ViewPaths
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb
index cd3f130dc4..c181689e62 100644
--- a/actionpack/lib/action_view/partials.rb
+++ b/actionpack/lib/action_view/partials.rb
@@ -12,19 +12,19 @@ module ActionView
#
# <%= render :partial => "account" %>
#
- # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable
+ # This would render "advertiser/_account.html.erb" and pass the instance variable @account in as a local variable
# +account+ to the template for display.
#
# In another template for Advertiser#buy, we could have:
#
# <%= render :partial => "account", :locals => { :account => @buyer } %>
#
- # <% for ad in @advertisements %>
+ # <% @advertisements.each do |ad| %>
# <%= render :partial => "ad", :locals => { :ad => ad } %>
# <% end %>
#
- # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then
- # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display.
+ # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then
+ # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display.
#
# == The :as and :object options
#
@@ -40,16 +40,16 @@ module ActionView
# With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we
# wanted it to be +agreement+ instead of +contract+ we'd do:
#
- # <%= render :partial => "contract", :as => :agreement %>
+ # <%= render :partial => "contract", :as => 'agreement' %>
#
# The <tt>:object</tt> option can be used to directly specify which object is rendered into the partial;
# useful when the template's object is elsewhere, in a different ivar or in a local variable for instance.
- #
+ #
# Revisiting a previous example we could have written this code:
- #
+ #
# <%= render :partial => "account", :object => @buyer %>
#
- # <% for ad in @advertisements %>
+ # <% @advertisements.each do |ad| %>
# <%= render :partial => "ad", :object => ad %>
# <% end %>
#
@@ -64,12 +64,12 @@ module ActionView
#
# <%= render :partial => "ad", :collection => @advertisements %>
#
- # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An
+ # This will render "advertiser/_ad.html.erb" 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+.
#
# The <tt>:as</tt> option may be used when rendering partials.
- #
+ #
# You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option.
# The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial:
#
@@ -89,7 +89,7 @@ module ActionView
#
# <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %>
#
- # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from.
+ # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from.
#
# == Rendering objects with the RecordIdentifier
#
diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb
index fa35120a0d..e3de3e1eac 100644
--- a/actionpack/lib/action_view/path_set.rb
+++ b/actionpack/lib/action_view/path_set.rb
@@ -11,13 +11,15 @@ module ActionView #:nodoc:
end
def find(*args)
- find_all(*args).first || raise(MissingTemplate.new(self, "#{args[1]}/#{args[0]}", args[3], args[2]))
+ find_all(*args).first || raise(MissingTemplate.new(self, *args))
end
- def find_all(*args)
- each do |resolver|
- templates = resolver.find_all(*args)
- return templates unless templates.empty?
+ def find_all(path, prefixes = [], *args)
+ prefixes.each do |prefix|
+ each do |resolver|
+ templates = resolver.find_all(path, prefix, *args)
+ return templates unless templates.empty?
+ end
end
[]
end
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
index 71cd1a788a..501ec07b09 100644
--- a/actionpack/lib/action_view/railtie.rb
+++ b/actionpack/lib/action_view/railtie.rb
@@ -35,5 +35,13 @@ module ActionView
end
end
end
+
+ initializer "action_view.caching" do |app|
+ ActiveSupport.on_load(:action_view) do
+ if app.config.action_view.cache_template_loading.nil?
+ ActionView::Resolver.caching = app.config.cache_classes
+ end
+ end
+ end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
index 317479ad4c..94c0a8a8fb 100644
--- a/actionpack/lib/action_view/renderer/partial_renderer.rb
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -108,11 +108,11 @@ module ActionView
locals << @variable_counter if @collection
find_template(path, locals)
end
- end
+ end
def find_template(path=@path, locals=@locals.keys)
- prefix = @view.controller_prefix unless path.include?(?/)
- @lookup_context.find_template(path, prefix, true, locals)
+ prefixes = path.include?(?/) ? [] : @view.controller_prefixes
+ @lookup_context.find_template(path, prefixes, true, locals)
end
def collection_with_template
@@ -152,14 +152,14 @@ module ActionView
object = object.to_model if object.respond_to?(:to_model)
object.class.model_name.partial_path.dup.tap do |partial|
- path = @view.controller_prefix
+ path = @view.controller_prefixes.first
partial.insert(0, "#{File.dirname(path)}/") if partial.include?(?/) && path.include?(?/)
end
end
end
def retrieve_variable(path)
- variable = @options[:as] || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym
+ variable = @options[:as].try(:to_sym) || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym
variable_counter = :"#{variable}_counter" if @collection
[variable, variable_counter]
end
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
index ece3f621b6..9ae1636131 100644
--- a/actionpack/lib/action_view/renderer/template_renderer.rb
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -22,14 +22,14 @@ module ActionView
def render_once(options)
paths, locals = options[:once], options[:locals] || {}
layout, keys = options[:layout], locals.keys
- prefix = options.fetch(:prefix, @view.controller_prefix)
+ prefixes = options.fetch(:prefixes, @view.controller_prefixes)
raise "render :once expects a String or an Array to be given" unless paths
render_with_layout(layout, locals) do
contents = []
Array.wrap(paths).each do |path|
- template = find_template(path, prefix, false, keys)
+ template = find_template(path, prefixes, false, keys)
contents << render_template(template, nil, locals) if @rendered.add?(template)
end
contents.join("\n")
@@ -43,13 +43,13 @@ module ActionView
if options.key?(:text)
Template::Text.new(options[:text], formats.try(:first))
elsif options.key?(:file)
- with_fallbacks { find_template(options[:file], options[:prefix], false, keys) }
+ with_fallbacks { find_template(options[:file], options[:prefixes], false, keys) }
elsif options.key?(:inline)
handler = Template.handler_for_extension(options[:type] || "erb")
Template.new(options[:inline], "inline template", handler, :locals => keys)
elsif options.key?(:template)
options[:template].respond_to?(:render) ?
- options[:template] : find_template(options[:template], options[:prefix], false, keys)
+ options[:template] : find_template(options[:template], options[:prefixes], false, keys)
end
end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index 0d8373ef14..96d506fac5 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -123,7 +123,7 @@ module ActionView
@locals = details[:locals] || []
@virtual_path = details[:virtual_path]
@updated_at = details[:updated_at] || Time.now
- @formats = Array.wrap(format).map(&:to_sym)
+ @formats = Array.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f }
end
# Render a template. If the template was not compiled yet, it is done
@@ -163,7 +163,7 @@ module ActionView
name = pieces.pop
partial = !!name.sub!(/^_/, "")
lookup.disable_cache do
- lookup.find_template(name, pieces.join('/'), partial, @locals)
+ lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
end
end
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index ff256738a9..e246646963 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -27,7 +27,7 @@ module ActionView
class MissingTemplate < ActionViewError #:nodoc:
attr_reader :path
- def initialize(paths, path, details, partial)
+ def initialize(paths, path, prefixes, partial, details, *)
@path = path
display_paths = paths.compact.map{ |p| p.to_s.inspect }.join(", ")
template_type = if partial
@@ -38,7 +38,11 @@ module ActionView
'template'
end
- super("Missing #{template_type} #{path} with #{details.inspect} in view paths #{display_paths}")
+ searched_paths = prefixes.map { |prefix| [prefix, path].join("/") }
+
+ out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n"
+ out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join
+ super out
end
end
@@ -52,6 +56,7 @@ module ActionView
attr_reader :original_exception, :backtrace
def initialize(template, assigns, original_exception)
+ super(original_exception.message)
@template, @assigns, @original_exception = template, assigns.dup, original_exception
@sub_templates = nil
@backtrace = original_exception.backtrace
@@ -61,10 +66,6 @@ module ActionView
@template.identifier
end
- def message
- ActiveSupport::Deprecation.silence { original_exception.message }
- end
-
def sub_template_message
if @sub_templates
"Trace of template inclusion: " +
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index a17454da28..4d999fb3b2 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -5,6 +5,13 @@ require "action_view/template"
module ActionView
# = Action View Resolver
class Resolver
+ cattr_accessor :caching
+ self.caching = true
+
+ class << self
+ alias :caching? :caching
+ end
+
def initialize
@cached = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2|
h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } }
@@ -23,9 +30,7 @@ module ActionView
private
- def caching?
- @caching ||= !defined?(Rails.application) || Rails.application.config.cache_classes
- end
+ delegate :caching?, :to => "self.class"
# This is what child classes implement. No defaults are needed
# because Resolver guarantees that the arguments are present and
@@ -42,7 +47,7 @@ module ActionView
path
end
- # Hnadles templates caching. If a key is given and caching is on
+ # Handles templates caching. If a key is given and caching is on
# always check the cache before hitting the resolver. Otherwise,
# it always hits the resolver but check if the resolver is fresher
# before returning it.
@@ -104,18 +109,27 @@ module ActionView
def query(path, exts, formats)
query = File.join(@path, path)
- exts.each do |ext|
- query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << ',}'
- end
+ query << exts.map { |ext|
+ "{#{ext.compact.map { |e| ".#{e}" }.join(',')},}"
+ }.join
- Dir[query].reject { |p| File.directory?(p) }.map do |p|
- handler, format = extract_handler_and_format(p, formats)
+ query.gsub!(/\{\.html,/, "{.html,.text.html,")
+ query.gsub!(/\{\.text,/, "{.text,.text.plain,")
+
+ templates = []
+ sanitizer = Hash.new { |h,k| h[k] = Dir["#{File.dirname(k)}/*"] }
+
+ Dir[query].each do |p|
+ next if File.directory?(p) || !sanitizer[p].include?(p)
+ handler, format = extract_handler_and_format(p, formats)
contents = File.open(p, "rb") {|io| io.read }
- Template.new(contents, File.expand_path(p), handler,
+ templates << Template.new(contents, File.expand_path(p), handler,
:virtual_path => path, :format => format, :updated_at => mtime(p))
end
+
+ templates
end
# Returns the file mtime from the filesystem.
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index 4026f7a40e..2ce109ea99 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -156,10 +156,8 @@ module ActionView
# The instance of ActionView::Base that is used by +render+.
def view
@view ||= begin
- view = ActionView::Base.new(ActionController::Base.view_paths, {}, @controller)
+ view = @controller.view_context
view.singleton_class.send :include, _helpers
- view.singleton_class.send :include, @controller._routes.url_helpers
- view.singleton_class.send :delegate, :alert, :notice, :to => "request.flash"
view.extend(Locals)
view.locals = self.locals
view.output_buffer = self.output_buffer
@@ -171,6 +169,7 @@ module ActionView
INTERNAL_IVARS = %w{
@__name__
+ @__io__
@_assertion_wrapped
@_assertions
@_result
diff --git a/actionpack/lib/action_view/testing/resolvers.rb b/actionpack/lib/action_view/testing/resolvers.rb
index 55583096e0..5c5cab7c7d 100644
--- a/actionpack/lib/action_view/testing/resolvers.rb
+++ b/actionpack/lib/action_view/testing/resolvers.rb
@@ -13,7 +13,11 @@ module ActionView #:nodoc:
@hash = hash
end
- private
+ def to_s
+ @hash.keys.join(', ')
+ end
+
+ private
def query(path, exts, formats)
query = ""
diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb
index 19855490b4..981c023d38 100644
--- a/actionpack/test/abstract/abstract_controller_test.rb
+++ b/actionpack/test/abstract/abstract_controller_test.rb
@@ -30,14 +30,14 @@ module AbstractController
class RenderingController < AbstractController::Base
include ::AbstractController::Rendering
- def _prefix() end
+ def _prefixes
+ []
+ end
def render(options = {})
if options.is_a?(String)
options = {:_template_name => options}
end
-
- options[:_prefix] = _prefix
super
end
@@ -116,8 +116,8 @@ module AbstractController
name.underscore
end
- def _prefix
- self.class.prefix
+ def _prefixes
+ [self.class.prefix]
end
end
@@ -157,10 +157,10 @@ module AbstractController
private
def self.layout(formats)
begin
- find_template(name.underscore, {:formats => formats}, :_prefix => "layouts")
+ find_template(name.underscore, {:formats => formats}, :_prefixes => ["layouts"])
rescue ActionView::MissingTemplate
begin
- find_template("application", {:formats => formats}, :_prefix => "layouts")
+ find_template("application", {:formats => formats}, :_prefixes => ["layouts"])
rescue ActionView::MissingTemplate
end
end
diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb
index 2d02078020..3bdde86291 100644
--- a/actionpack/test/abstract/callbacks_test.rb
+++ b/actionpack/test/abstract/callbacks_test.rb
@@ -22,7 +22,7 @@ module AbstractController
class TestCallbacks1 < ActiveSupport::TestCase
test "basic callbacks work" do
controller = Callback1.new
- result = controller.process(:index)
+ controller.process(:index)
assert_equal "Hello world", controller.response_body
end
end
@@ -62,7 +62,7 @@ module AbstractController
end
test "before_filter works" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
@@ -78,7 +78,7 @@ module AbstractController
test "before_filter with overwritten condition" do
@controller = Callback2Overwrite.new
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "", @controller.response_body
end
end
@@ -103,12 +103,12 @@ module AbstractController
end
test "before_filter works with procs" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
test "after_filter works with procs" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Goodbye", @controller.instance_variable_get("@second")
end
end
@@ -152,7 +152,7 @@ module AbstractController
end
test "when :except is specified, an after filter is not triggered on that action" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert !@controller.instance_variable_defined?("@authenticated")
end
end
@@ -186,17 +186,17 @@ module AbstractController
end
test "when :only is specified with an array, a before filter is triggered on that action" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello, World", @controller.response_body
end
test "when :only is specified with an array, a before filter is not triggered on other actions" do
- result = @controller.process(:sekrit_data)
+ @controller.process(:sekrit_data)
assert_equal "true", @controller.response_body
end
test "when :except is specified with an array, an after filter is not triggered on that action" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert !@controller.instance_variable_defined?("@authenticated")
end
end
@@ -216,12 +216,12 @@ module AbstractController
end
test "when a callback is modified in a child with :only, it works for the :only action" do
- result = @controller.process(:index)
+ @controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
test "when a callback is modified in a child with :only, it does not work for other actions" do
- result = @controller.process(:not_index)
+ @controller.process(:not_index)
assert_equal "", @controller.response_body
end
end
@@ -246,5 +246,26 @@ module AbstractController
end
end
+ class CallbacksWithArgs < ControllerWithCallbacks
+ set_callback :process_action, :before, :first
+
+ def first
+ @text = "Hello world"
+ end
+
+ def index(text)
+ self.response_body = @text + text
+ end
+ end
+
+ class TestCallbacksWithArgs < ActiveSupport::TestCase
+ test "callbacks still work when invoking process with multiple args" do
+ controller = CallbacksWithArgs.new
+ controller.process(:index, " Howdy!")
+ assert_equal "Hello world Howdy!", controller.response_body
+ end
+ end
+
+
end
end
diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb
index 25dc8bd804..b9293d1241 100644
--- a/actionpack/test/abstract/render_test.rb
+++ b/actionpack/test/abstract/render_test.rb
@@ -6,8 +6,8 @@ module AbstractController
class ControllerRenderer < AbstractController::Base
include AbstractController::Rendering
- def _prefix
- "renderer"
+ def _prefixes
+ %w[renderer]
end
self.view_paths = [ActionView::FixtureResolver.new(
diff --git a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
index 43c534c111..99f09286ff 100644
--- a/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
+++ b/actionpack/test/activerecord/render_partial_with_record_identification_test.rb
@@ -11,7 +11,7 @@ class RenderPartialWithRecordIdentificationController < ActionController::Base
render :partial => @topic.replies
end
- def render_with_named_scope
+ def render_with_scope
render :partial => Reply.base
end
@@ -62,8 +62,8 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase
assert_equal 'Birdman is better!', @response.body
end
- def test_rendering_partial_with_named_scope
- get :render_with_named_scope
+ def test_rendering_partial_with_scope
+ get :render_with_scope
assert_template 'replies/_reply'
assert_equal 'Birdman is better!Nuh uh!', @response.body
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index c7b54eb0ba..01f3e8f2b6 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -156,6 +156,17 @@ class PageCachingTest < ActionController::TestCase
assert_page_not_cached :ok
end
+ def test_page_caching_directory_set_as_pathname
+ begin
+ ActionController::Base.page_cache_directory = Pathname.new(FILE_STORE_PATH)
+ get :ok
+ assert_response :ok
+ assert_page_cached :ok
+ ensure
+ ActionController::Base.page_cache_directory = FILE_STORE_PATH
+ end
+ end
+
private
def assert_page_cached(action, message = "#{action} should have been cached")
assert page_cached?(action), message
@@ -257,7 +268,6 @@ class ActionCachingMockController
end
def request
- mocked_path = @mock_path
Object.new.instance_eval(<<-EVAL)
def path; '#{@mock_path}' end
def format; 'all' end
@@ -416,7 +426,6 @@ class ActionCacheTest < ActionController::TestCase
get :index
assert_response :success
- new_cached_time = content_to_cache
assert_not_equal cached_time, @response.body
end
@@ -550,6 +559,11 @@ class ActionCacheTest < ActionController::TestCase
assert_response 404
end
+ def test_four_oh_four_renders_content
+ get :four_oh_four
+ assert_equal "404'd!", @response.body
+ end
+
def test_simple_runtime_error_returns_500_for_multiple_requests
get :simple_runtime_error
assert_response 500
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 68febf425d..330fa276d0 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -664,7 +664,7 @@ class FilterTest < ActionController::TestCase
end
def test_prepending_and_appending_around_filter
- controller = test_process(MixedFilterController)
+ test_process(MixedFilterController)
assert_equal " before aroundfilter before procfilter before appended aroundfilter " +
" after appended aroundfilter after procfilter after aroundfilter ",
MixedFilterController.execution_log
@@ -677,26 +677,26 @@ class FilterTest < ActionController::TestCase
end
def test_before_filter_rendering_breaks_filtering_chain_for_after_filter
- response = test_process(RenderingController)
+ test_process(RenderingController)
assert_equal %w( before_filter_rendering ), assigns["ran_filter"]
assert !assigns["ran_action"]
end
def test_before_filter_redirects_breaks_filtering_chain_for_after_filter
- response = test_process(BeforeFilterRedirectionController)
+ test_process(BeforeFilterRedirectionController)
assert_response :redirect
assert_equal "http://test.host/filter_test/before_filter_redirection/target_of_redirection", redirect_to_url
assert_equal %w( before_filter_redirects ), assigns["ran_filter"]
end
def test_before_filter_rendering_breaks_filtering_chain_for_preprend_after_filter
- response = test_process(RenderingForPrependAfterFilterController)
+ test_process(RenderingForPrependAfterFilterController)
assert_equal %w( before_filter_rendering ), assigns["ran_filter"]
assert !assigns["ran_action"]
end
def test_before_filter_redirects_breaks_filtering_chain_for_preprend_after_filter
- response = test_process(BeforeFilterRedirectionForPrependAfterFilterController)
+ test_process(BeforeFilterRedirectionForPrependAfterFilterController)
assert_response :redirect
assert_equal "http://test.host/filter_test/before_filter_redirection_for_prepend_after_filter/target_of_redirection", redirect_to_url
assert_equal %w( before_filter_redirects ), assigns["ran_filter"]
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index e6fe0b1f04..ddfa3df552 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -32,6 +32,11 @@ module Another
cache_page("Super soaker", "/index.html")
render :nothing => true
end
+
+ def with_exception
+ raise Exception
+ end
+
end
end
@@ -139,20 +144,20 @@ class ACLogSubscriberTest < ActionController::TestCase
wait
assert_equal 4, logs.size
- assert_match(/Exist fragment\? views\/foo/, logs[1])
+ assert_match(/Read fragment views\/foo/, logs[1])
assert_match(/Write fragment views\/foo/, logs[2])
ensure
@controller.config.perform_caching = true
end
-
+
def test_with_fragment_cache_and_percent_in_key
@controller.config.perform_caching = true
get :with_fragment_cache_and_percent_in_key
wait
assert_equal 4, logs.size
- assert_match(/Exist fragment\? views\/foo%bar/, logs[1])
- assert_match(/Write fragment views\/foo%bar/, logs[2])
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
ensure
@controller.config.perform_caching = true
end
@@ -169,6 +174,16 @@ class ACLogSubscriberTest < ActionController::TestCase
@controller.config.perform_caching = true
end
+ def test_process_action_with_exception_includes_http_status_code
+ begin
+ get :with_exception
+ wait
+ rescue Exception
+ end
+ assert_equal 2, logs.size
+ assert_match(/Completed 500/, logs.last)
+ end
+
def logs
@logs ||= @logger.logged(:info)
end
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index 98c9d43b93..5debf96232 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -565,7 +565,7 @@ class RespondWithController < ActionController::Base
def using_resource_with_action
respond_with(resource, :action => :foo) do |format|
- format.html { raise ActionView::MissingTemplate.new([], "foo/bar", {}, false) }
+ format.html { raise ActionView::MissingTemplate.new([], "bar", ["foo"], {}, false) }
end
end
@@ -658,7 +658,7 @@ class RespondWithControllerTest < ActionController::TestCase
@request.accept = "application/json"
get :using_hash_resource
assert_equal "application/json", @response.content_type
- assert_equal %Q[{"result":["david",13]}], @response.body
+ assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body
end
def test_using_resource_with_block
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 543c02b2c5..3ca29f1bcf 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -35,7 +35,7 @@ module BareMetalTest
class HeadTest < ActiveSupport::TestCase
test "head works on its own" do
- status, headers, body = HeadController.action(:index).call(Rack::MockRequest.env_for("/"))
+ status = HeadController.action(:index).call(Rack::MockRequest.env_for("/")).first
assert_equal 404, status
end
end
diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb
index b98a22dfcc..5fd5946619 100644
--- a/actionpack/test/controller/new_base/content_negotiation_test.rb
+++ b/actionpack/test/controller/new_base/content_negotiation_test.rb
@@ -7,6 +7,10 @@ module ContentNegotiation
self.view_paths = [ActionView::FixtureResolver.new(
"content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!"
)]
+
+ def all
+ render :text => self.formats.inspect
+ end
end
class TestContentNegotiation < Rack::TestCase
@@ -14,5 +18,10 @@ module ContentNegotiation
get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*"
assert_body "Hello world */*!"
end
+
+ test "Not all mimes are converted to symbol" do
+ get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another"
+ assert_body '[:text, "mime/another"]'
+ end
end
end
diff --git a/actionpack/test/controller/new_base/render_once_test.rb b/actionpack/test/controller/new_base/render_once_test.rb
index 3035ed4ff2..175abf8a7e 100644
--- a/actionpack/test/controller/new_base/render_once_test.rb
+++ b/actionpack/test/controller/new_base/render_once_test.rb
@@ -18,8 +18,8 @@ module RenderTemplate
self.view_paths = [RESOLVER]
- def _prefix
- "test"
+ def _prefixes
+ %w(test)
end
def multiple
@@ -39,11 +39,11 @@ module RenderTemplate
end
def with_prefix
- render :once => "result", :prefix => "other"
+ render :once => "result", :prefixes => %w(other)
end
def with_nil_prefix
- render :once => "test/result", :prefix => nil
+ render :once => "test/result", :prefixes => []
end
end
diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb
index d800ea264d..83b0d039ad 100644
--- a/actionpack/test/controller/new_base/render_partial_test.rb
+++ b/actionpack/test/controller/new_base/render_partial_test.rb
@@ -9,7 +9,10 @@ module RenderPartial
"render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>",
"render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>",
"render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>",
- "render_partial/basic/_final.json.erb" => "{ final: json }"
+ "render_partial/basic/_final.json.erb" => "{ final: json }",
+ "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>",
+ "render_partial/basic/_overriden.html.erb" => "ParentPartial!",
+ "render_partial/child/_overriden.html.erb" => "OverridenPartial!"
)]
def html_with_json_inside_json
@@ -20,7 +23,13 @@ module RenderPartial
@test_unchanged = 'hello'
render :action => "basic"
end
+
+ def overriden
+ @test_unchanged = 'hello'
+ end
end
+
+ class ChildController < BasicController; end
class TestPartial < Rack::TestCase
testing BasicController
@@ -37,4 +46,18 @@ module RenderPartial
end
end
+ class TestInheritedPartial < Rack::TestCase
+ testing ChildController
+
+ test "partial from parent controller gets picked if missing in child one" do
+ get :changing
+ assert_response("goodbyeBasicPartial!goodbye")
+ end
+
+ test "partial from child controller gets picked" do
+ get :overriden
+ assert_response("goodbyeOverridenPartial!goodbye")
+ end
+ end
+
end
diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb
index df97a2725b..d6062bfa8c 100644
--- a/actionpack/test/controller/new_base/render_test.rb
+++ b/actionpack/test/controller/new_base/render_test.rb
@@ -6,7 +6,11 @@ module Render
"render/blank_render/index.html.erb" => "Hello world!",
"render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>",
"render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>",
- "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>"
+ "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>",
+ "render/blank_render/overriden_with_own_view_paths_appended.html.erb" => "parent content",
+ "render/blank_render/overriden_with_own_view_paths_prepended.html.erb" => "parent content",
+ "render/blank_render/overriden.html.erb" => "parent content",
+ "render/child_render/overriden.html.erb" => "child content"
)]
def index
@@ -21,6 +25,15 @@ module Render
render :action => "access_action_name"
end
+ def overriden_with_own_view_paths_appended
+ end
+
+ def overriden_with_own_view_paths_prepended
+ end
+
+ def overriden
+ end
+
private
def secretz
@@ -35,6 +48,11 @@ module Render
end
end
+ class ChildRenderController < BlankRenderController
+ append_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_appended.html.erb" => "child content")
+ prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content")
+ end
+
class RenderTest < Rack::TestCase
test "render with blank" do
with_routing do |set|
@@ -94,4 +112,26 @@ module Render
assert_body "Controller Name: blank_render"
end
end
+
+ class TestViewInheritance < Rack::TestCase
+ test "Template from child controller gets picked over parent one" do
+ get "/render/child_render/overriden"
+ assert_body "child content"
+ end
+
+ test "Template from child controller with custom view_paths prepended gets picked over parent one" do
+ get "/render/child_render/overriden_with_own_view_paths_prepended"
+ assert_body "child content"
+ end
+
+ test "Template from child controller with custom view_paths appended gets picked over parent one" do
+ get "/render/child_render/overriden_with_own_view_paths_appended"
+ assert_body "child content"
+ end
+
+ test "Template from parent controller gets picked if missing in child controller" do
+ get "/render/child_render/index"
+ assert_body "Hello world!"
+ end
+ end
end
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
index 6dd2a9f23d..fc604a2db3 100644
--- a/actionpack/test/controller/render_json_test.rb
+++ b/actionpack/test/controller/render_json_test.rb
@@ -26,6 +26,10 @@ class RenderJsonTest < ActionController::TestCase
render :json => nil
end
+ def render_json_render_to_string
+ render :text => render_to_string(:json => '[]')
+ end
+
def render_json_hello_world
render :json => ActiveSupport::JSON.encode(:hello => 'world')
end
@@ -76,6 +80,12 @@ class RenderJsonTest < ActionController::TestCase
assert_equal 'application/json', @response.content_type
end
+ def test_render_json_render_to_string
+ get :render_json_render_to_string
+ assert_equal '[]', @response.body
+ end
+
+
def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index fca8de60bc..be492152f2 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -125,6 +125,10 @@ class TestController < ActionController::Base
render :action => "hello_world"
end
+ def render_action_upcased_hello_world
+ render :action => "Hello_world"
+ end
+
def render_action_hello_world_as_string
render "hello_world"
end
@@ -742,6 +746,12 @@ class RenderTest < ActionController::TestCase
assert_template "test/hello_world"
end
+ def test_render_action_upcased
+ assert_raise ActionView::MissingTemplate do
+ get :render_action_upcased_hello_world
+ end
+ end
+
# :ported:
def test_render_action_hello_world_as_string
get :render_action_hello_world_as_string
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
index 0a39feb7fe..e624f11773 100644
--- a/actionpack/test/controller/request/test_request_test.rb
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -29,8 +29,7 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase
end
def test_session_id_different_on_each_call
- prev_id =
assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id])
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 2c9aa6187b..d520b5e512 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -12,6 +12,14 @@ module RequestForgeryProtectionActions
render :inline => "<%= button_to('New', '/') {} %>"
end
+ def external_form
+ render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>"
+ end
+
+ def external_form_without_protection
+ render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>"
+ end
+
def unsafe
render :text => 'pwn'
end
@@ -20,6 +28,14 @@ module RequestForgeryProtectionActions
render :inline => "<%= csrf_meta_tags %>"
end
+ def external_form_for
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>"
+ end
+
+ def form_for_without_protection
+ render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>"
+ end
+
def rescue_action(e) raise e end
end
@@ -29,6 +45,16 @@ class RequestForgeryProtectionController < ActionController::Base
protect_from_forgery :only => %w(index meta)
end
+class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base
+ include RequestForgeryProtectionActions
+ protect_from_forgery :only => %w(index meta)
+
+ def handle_unverified_request
+ raise(ActionController::InvalidAuthenticityToken)
+ end
+end
+
+
class FreeCookieController < RequestForgeryProtectionController
self.allow_forgery_protection = false
@@ -51,152 +77,92 @@ end
# common test methods
module RequestForgeryProtectionTests
- def teardown
- ActionController::Base.request_forgery_protection_token = nil
+ def setup
+ @token = "cf50faa3fe97702ca1ae"
+
+ ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
+ ActionController::Base.request_forgery_protection_token = :authenticity_token
end
+
def test_should_render_form_with_token_tag
- get :index
+ assert_not_blocked do
+ get :index
+ end
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
end
def test_should_render_button_to_with_token_tag
- get :show_button
+ assert_not_blocked do
+ get :show_button
+ end
assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token
end
def test_should_allow_get
- get :index
- assert_response :success
+ assert_not_blocked { get :index }
end
def test_should_allow_post_without_token_on_unsafe_action
- post :unsafe
- assert_response :success
- end
-
- def test_should_not_allow_html_post_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html }
- end
-
- def test_should_not_allow_html_put_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html }
- end
-
- def test_should_not_allow_html_delete_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html }
- end
-
- def test_should_allow_api_formatted_post_without_token
- assert_nothing_raised do
- post :index, :format => 'xml'
- end
- end
-
- def test_should_not_allow_api_formatted_put_without_token
- assert_nothing_raised do
- put :index, :format => 'xml'
- end
- end
-
- def test_should_allow_api_formatted_delete_without_token
- assert_nothing_raised do
- delete :index, :format => 'xml'
- end
+ assert_not_blocked { post :unsafe }
end
- def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- post :index, :format => 'xml'
- end
+ def test_should_not_allow_post_without_token
+ assert_blocked { post :index }
end
- def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- put :index, :format => 'xml'
- end
+ def test_should_not_allow_post_without_token_irrespective_of_format
+ assert_blocked { post :index, :format=>'xml' }
end
- def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- delete :index, :format => 'xml'
- end
+ def test_should_not_allow_put_without_token
+ assert_blocked { put :index }
end
- def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
- post :index, :format => 'xml'
- end
- end
-
- def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
- put :index, :format => 'xml'
- end
- end
-
- def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token
- assert_raise(ActionController::InvalidAuthenticityToken) do
- @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s
- delete :index, :format => 'xml'
- end
+ def test_should_not_allow_delete_without_token
+ assert_blocked { delete :index }
end
- def test_should_allow_xhr_post_without_token
- assert_nothing_raised { xhr :post, :index }
+ def test_should_not_allow_xhr_post_without_token
+ assert_blocked { xhr :post, :index }
end
- def test_should_allow_xhr_put_without_token
- assert_nothing_raised { xhr :put, :index }
+ def test_should_allow_post_with_token
+ assert_not_blocked { post :index, :authenticity_token => @token }
end
- def test_should_allow_xhr_delete_without_token
- assert_nothing_raised { xhr :delete, :index }
+ def test_should_allow_put_with_token
+ assert_not_blocked { put :index, :authenticity_token => @token }
end
- def test_should_allow_xhr_post_with_encoded_form_content_type_without_token
- @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s
- assert_nothing_raised { xhr :post, :index }
+ def test_should_allow_delete_with_token
+ assert_not_blocked { delete :index, :authenticity_token => @token }
end
- def test_should_allow_post_with_token
- post :index, :authenticity_token => @token
- assert_response :success
+ def test_should_allow_post_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { post :index }
end
- def test_should_allow_put_with_token
- put :index, :authenticity_token => @token
- assert_response :success
+ def test_should_allow_delete_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { delete :index }
end
- def test_should_allow_delete_with_token
- delete :index, :authenticity_token => @token
- assert_response :success
+ def test_should_allow_put_with_token_in_header
+ @request.env['HTTP_X_CSRF_TOKEN'] = @token
+ assert_not_blocked { put :index }
end
- def test_should_allow_post_with_xml
- @request.env['CONTENT_TYPE'] = Mime::XML.to_s
- post :index, :format => 'xml'
+ def assert_blocked
+ session[:something_like_user_id] = 1
+ yield
+ assert_nil session[:something_like_user_id], "session values are still present"
assert_response :success
end
- def test_should_allow_put_with_xml
- @request.env['CONTENT_TYPE'] = Mime::XML.to_s
- put :index, :format => 'xml'
- assert_response :success
- end
-
- def test_should_allow_delete_with_xml
- @request.env['CONTENT_TYPE'] = Mime::XML.to_s
- delete :index, :format => 'xml'
+ def assert_not_blocked
+ assert_nothing_raised { yield }
assert_response :success
end
end
@@ -205,16 +171,6 @@ end
class RequestForgeryProtectionControllerTest < ActionController::TestCase
include RequestForgeryProtectionTests
- def setup
- @controller = RequestForgeryProtectionController.new
- @request = ActionController::TestRequest.new
- @request.format = :html
- @response = ActionController::TestResponse.new
- @token = "cf50faa3fe97702ca1ae"
-
- ActiveSupport::SecureRandom.stubs(:base64).returns(@token)
- ActionController::Base.request_forgery_protection_token = :authenticity_token
- end
test 'should emit a csrf-token meta tag' do
ActiveSupport::SecureRandom.stubs(:base64).returns(@token + '<=?')
@@ -226,6 +182,15 @@ class RequestForgeryProtectionControllerTest < ActionController::TestCase
end
end
+class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase
+ include RequestForgeryProtectionTests
+ def assert_blocked
+ assert_raises(ActionController::InvalidAuthenticityToken) do
+ yield
+ end
+ end
+end
+
class FreeCookieControllerTest < ActionController::TestCase
def setup
@controller = FreeCookieController.new
@@ -258,13 +223,23 @@ class FreeCookieControllerTest < ActionController::TestCase
end
end
+
+
+
+
class CustomAuthenticityParamControllerTest < ActionController::TestCase
def setup
+ ActionController::Base.request_forgery_protection_token = :custom_token_name
+ super
+ end
+
+ def teardown
ActionController::Base.request_forgery_protection_token = :authenticity_token
+ super
end
def test_should_allow_custom_token
- post :index, :authenticity_token => 'foobar'
+ post :index, :custom_token_name => 'foobar'
assert_response :ok
end
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 89f0d03c56..5f6f1b61c0 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -701,7 +701,7 @@ class RouteSetTest < ActiveSupport::TestCase
set.draw do
match '/users/index' => 'users#index'
end
- params = set.recognize_path('/users/index', :method => :get)
+ set.recognize_path('/users/index', :method => :get)
assert_equal 1, set.routes.size
end
@@ -980,7 +980,7 @@ class RouteSetTest < ActiveSupport::TestCase
match '/profile' => 'profile#index'
end
- params = set.recognize_path("/profile") rescue nil
+ set.recognize_path("/profile") rescue nil
assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
end
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 1f62d29e80..1c28da33bd 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -95,16 +95,29 @@ module AbstractController
)
end
- def test_protocol_with_and_without_separator
+ def test_protocol_with_and_without_separators
add_host!
assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https')
)
assert_equal('https://www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https:')
+ )
+ assert_equal('https://www.basecamphq.com/c/a/i',
W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://')
)
end
+ def test_without_protocol
+ add_host!
+ assert_equal('//www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => '//')
+ )
+ assert_equal('//www.basecamphq.com/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => false)
+ )
+ end
+
def test_trailing_slash
add_host!
options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'}
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index 6ba4c6c48d..621fb79915 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -216,7 +216,7 @@ class WebServiceTest < ActionDispatch::IntegrationTest
def test_typecast_as_yaml
with_test_route_set do
with_params_parsers Mime::YAML => :yaml do
- yaml = <<-YAML
+ yaml = (<<-YAML).strip
---
data:
a: 15
diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb
index d3aa55a1ba..eed2eca2ab 100644
--- a/actionpack/test/dispatch/callbacks_test.rb
+++ b/actionpack/test/dispatch/callbacks_test.rb
@@ -1,6 +1,6 @@
require 'abstract_unit'
-class DispatcherTest < Test::Unit::TestCase
+class DispatcherTest < ActiveSupport::TestCase
class Foo
cattr_accessor :a, :b
end
@@ -13,65 +13,9 @@ class DispatcherTest < Test::Unit::TestCase
def setup
Foo.a, Foo.b = 0, 0
- ActionDispatch::Callbacks.reset_callbacks(:prepare)
ActionDispatch::Callbacks.reset_callbacks(:call)
end
- def test_prepare_callbacks_with_cache_classes
- a = b = c = nil
- ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
- ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 }
- ActionDispatch::Callbacks.to_prepare { |*args| c = 3 }
-
- # Ensure to_prepare callbacks are not run when defined
- assert_nil a || b || c
-
- # Run callbacks
- dispatch
-
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
-
- # Make sure they are only run once
- a = b = c = nil
- dispatch
- assert_nil a || b || c
- end
-
- def test_prepare_callbacks_without_cache_classes
- a = b = c = nil
- ActionDispatch::Callbacks.to_prepare { |*args| a = b = c = 1 }
- ActionDispatch::Callbacks.to_prepare { |*args| b = c = 2 }
- ActionDispatch::Callbacks.to_prepare { |*args| c = 3 }
-
- # Ensure to_prepare callbacks are not run when defined
- assert_nil a || b || c
-
- # Run callbacks
- dispatch(false)
-
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
-
- # Make sure they are run again
- a = b = c = nil
- dispatch(false)
- assert_equal 1, a
- assert_equal 2, b
- assert_equal 3, c
- end
-
- def test_to_prepare_with_identifier_replaces
- ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a, Foo.b = 1, 1 }
- ActionDispatch::Callbacks.to_prepare(:unique_id) { |*args| Foo.a = 2 }
-
- dispatch
- assert_equal 2, Foo.a
- assert_equal 0, Foo.b
- end
-
def test_before_and_after_callbacks
ActionDispatch::Callbacks.before { |*args| Foo.a += 1; Foo.b += 1 }
ActionDispatch::Callbacks.after { |*args| Foo.a += 1; Foo.b += 1 }
@@ -85,10 +29,22 @@ class DispatcherTest < Test::Unit::TestCase
assert_equal 4, Foo.b
end
+ def test_to_prepare_and_cleanup_delegation
+ prepared = cleaned = false
+ ActionDispatch::Callbacks.to_prepare { prepared = true }
+ ActionDispatch::Callbacks.to_prepare { cleaned = true }
+
+ ActionDispatch::Reloader.prepare!
+ assert prepared
+
+ ActionDispatch::Reloader.cleanup!
+ assert cleaned
+ end
+
private
- def dispatch(cache_classes = true, &block)
- @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new, !cache_classes)
+ def dispatch(&block)
+ @dispatcher ||= ActionDispatch::Callbacks.new(block || DummyApp.new)
@dispatcher.call({'rack.input' => StringIO.new('')})
end
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 5ec7f12cc1..1cfea6aa12 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -95,6 +95,26 @@ class CookiesTest < ActionController::TestCase
head :ok
end
+ def set_cookie_with_domain_and_tld
+ cookies[:user_name] = {:value => "rizwanreza", :domain => :all, :tld_length => 2}
+ head :ok
+ end
+
+ def delete_cookie_with_domain_and_tld
+ cookies.delete(:user_name, :domain => :all, :tld_length => 2)
+ head :ok
+ end
+
+ def set_cookie_with_domains
+ cookies[:user_name] = {:value => "rizwanreza", :domain => %w(example1.com example2.com .example3.com)}
+ head :ok
+ end
+
+ def delete_cookie_with_domains
+ cookies.delete(:user_name, :domain => %w(example1.com example2.com .example3.com))
+ head :ok
+ end
+
def symbol_key
cookies[:user_name] = "david"
head :ok
@@ -295,12 +315,94 @@ class CookiesTest < ActionController::TestCase
assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
end
+ def test_cookie_with_all_domain_option_using_localhost
+ @request.host = "localhost"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_ipv4_address
+ @request.host = "192.168.1.1"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_ipv6_address
+ @request.host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
+ get :set_cookie_with_domain
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
def test_deleting_cookie_with_all_domain_option
get :delete_cookie_with_domain
assert_response :success
assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
end
+ def test_cookie_with_all_domain_option_and_tld_length
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.com; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_a_non_standard_tld_and_tld_length
+ @request.host = "two.subdomains.nextangle.local"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_cookie_with_all_domain_option_using_host_with_port_and_tld_length
+ @request.host = "nextangle.local:3000"
+ get :set_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.nextangle.local; path=/"
+ end
+
+ def test_deleting_cookie_with_all_domain_option_and_tld_length
+ get :delete_cookie_with_domain_and_tld
+ assert_response :success
+ assert_cookie_header "user_name=; domain=.nextangle.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
+ def test_cookie_with_several_preset_domains_using_one_of_these_domains
+ @request.host = "example1.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=example1.com; path=/"
+ end
+
+ def test_cookie_with_several_preset_domains_using_other_domain
+ @request.host = "other-domain.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; path=/"
+ end
+
+ def test_cookie_with_several_preset_domains_using_shared_domain
+ @request.host = "example3.com"
+ get :set_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=rizwanreza; domain=.example3.com; path=/"
+ end
+
+ def test_deletings_cookie_with_several_preset_domains_using_one_of_these_domains
+ @request.host = "example2.com"
+ get :delete_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=; domain=example2.com; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
+ def test_deletings_cookie_with_several_preset_domains_using_other_domain
+ @request.host = "other-domain.com"
+ get :delete_cookie_with_domains
+ assert_response :success
+ assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
def test_cookies_hash_is_indifferent_access
[:symbol_key, :string_key].each do |cookie_key|
get cookie_key
diff --git a/actionpack/test/dispatch/middleware_stack/middleware_test.rb b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
new file mode 100644
index 0000000000..9607f026db
--- /dev/null
+++ b/actionpack/test/dispatch/middleware_stack/middleware_test.rb
@@ -0,0 +1,77 @@
+require 'abstract_unit'
+require 'action_dispatch/middleware/stack'
+
+module ActionDispatch
+ class MiddlewareStack
+ class MiddlewareTest < ActiveSupport::TestCase
+ class Omg; end
+
+ {
+ 'concrete' => Omg,
+ 'anonymous' => Class.new
+ }.each do |name, klass|
+
+ define_method("test_#{name}_klass") do
+ mw = Middleware.new klass
+ assert_equal klass, mw.klass
+ end
+
+ define_method("test_#{name}_==") do
+ mw1 = Middleware.new klass
+ mw2 = Middleware.new klass
+ assert_equal mw1, mw2
+ end
+
+ end
+
+ def test_string_class
+ mw = Middleware.new Omg.name
+ assert_equal Omg, mw.klass
+ end
+
+ def test_double_equal_works_with_classes
+ k = Class.new
+ mw = Middleware.new k
+ assert_operator mw, :==, k
+
+ result = mw != Class.new
+ assert result, 'middleware should not equal other anon class'
+ end
+
+ def test_double_equal_works_with_strings
+ mw = Middleware.new Omg
+ assert_operator mw, :==, Omg.name
+ end
+
+ def test_double_equal_normalizes_strings
+ mw = Middleware.new Omg
+ assert_operator mw, :==, "::#{Omg.name}"
+ end
+
+ def test_middleware_loads_classnames_from_cache
+ mw = Class.new(Middleware) {
+ attr_accessor :classcache
+ }.new(Omg.name)
+
+ fake_cache = { mw.name => Omg }
+ mw.classcache = fake_cache
+
+ assert_equal Omg, mw.klass
+
+ fake_cache[mw.name] = Middleware
+ assert_equal Middleware, mw.klass
+ end
+
+ def test_middleware_always_returns_class
+ mw = Class.new(Middleware) {
+ attr_accessor :classcache
+ }.new(Omg)
+
+ fake_cache = { mw.name => Middleware }
+ mw.classcache = fake_cache
+
+ assert_equal Omg, mw.klass
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index 9782f328fc..11cf68fdb3 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -131,6 +131,13 @@ class MimeTypeTest < ActiveSupport::TestCase
assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" }
end
+ test "references gives preference to symbols before strings" do
+ assert_equal :html, Mime::HTML.ref
+ another = Mime::Type.lookup("foo/bar")
+ assert_nil another.to_sym
+ assert_equal "foo/bar", another.ref
+ end
+
test "regexp matcher" do
assert Mime::JS =~ "text/javascript"
assert Mime::JS =~ "application/javascript"
diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb
new file mode 100644
index 0000000000..eaabc1feb3
--- /dev/null
+++ b/actionpack/test/dispatch/reloader_test.rb
@@ -0,0 +1,138 @@
+require 'abstract_unit'
+
+class ReloaderTest < Test::Unit::TestCase
+ Reloader = ActionDispatch::Reloader
+
+ def test_prepare_callbacks
+ a = b = c = nil
+ Reloader.to_prepare { |*args| a = b = c = 1 }
+ Reloader.to_prepare { |*args| b = c = 2 }
+ Reloader.to_prepare { |*args| c = 3 }
+
+ # Ensure to_prepare callbacks are not run when defined
+ assert_nil a || b || c
+
+ # Run callbacks
+ call_and_return_body
+
+ assert_equal 1, a
+ assert_equal 2, b
+ assert_equal 3, c
+ end
+
+ class MyBody < Array
+ def initialize(&block)
+ @on_close = block
+ end
+
+ def foo
+ "foo"
+ end
+
+ def bar
+ "bar"
+ end
+
+ def close
+ @on_close.call if @on_close
+ end
+ end
+
+ def test_returned_body_object_always_responds_to_close
+ body = call_and_return_body
+ assert_respond_to body, :close
+ end
+
+ def test_returned_body_object_behaves_like_underlying_object
+ body = call_and_return_body do
+ b = MyBody.new
+ b << "hello"
+ b << "world"
+ [200, { "Content-Type" => "text/html" }, b]
+ end
+ assert_equal 2, body.size
+ assert_equal "hello", body[0]
+ assert_equal "world", body[1]
+ assert_equal "foo", body.foo
+ assert_equal "bar", body.bar
+ end
+
+ def test_it_calls_close_on_underlying_object_when_close_is_called_on_body
+ close_called = false
+ body = call_and_return_body do
+ b = MyBody.new do
+ close_called = true
+ end
+ [200, { "Content-Type" => "text/html" }, b]
+ end
+ body.close
+ assert close_called
+ end
+
+ def test_returned_body_object_responds_to_all_methods_supported_by_underlying_object
+ body = call_and_return_body do
+ [200, { "Content-Type" => "text/html" }, MyBody.new]
+ end
+ assert_respond_to body, :size
+ assert_respond_to body, :each
+ assert_respond_to body, :foo
+ assert_respond_to body, :bar
+ end
+
+ def test_cleanup_callbacks_are_called_when_body_is_closed
+ cleaned = false
+ Reloader.to_cleanup { cleaned = true }
+
+ body = call_and_return_body
+ assert !cleaned
+
+ body.close
+ assert cleaned
+ end
+
+ def test_prepare_callbacks_arent_called_when_body_is_closed
+ prepared = false
+ Reloader.to_prepare { prepared = true }
+
+ body = call_and_return_body
+ prepared = false
+
+ body.close
+ assert !prepared
+ end
+
+ def test_manual_reloading
+ prepared = cleaned = false
+ Reloader.to_prepare { prepared = true }
+ Reloader.to_cleanup { cleaned = true }
+
+ Reloader.prepare!
+ assert prepared
+ assert !cleaned
+
+ prepared = cleaned = false
+ Reloader.cleanup!
+ assert !prepared
+ assert cleaned
+ end
+
+ def test_cleanup_callbacks_are_called_on_exceptions
+ cleaned = false
+ Reloader.to_cleanup { cleaned = true }
+
+ begin
+ call_and_return_body do
+ raise "error"
+ end
+ rescue
+ end
+
+ assert cleaned
+ end
+
+ private
+ def call_and_return_body(&block)
+ @reloader ||= Reloader.new(block || proc {[200, {}, 'response']})
+ @reloader.call({'rack.input' => StringIO.new('')})[2]
+ end
+end
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 75b674ec1a..dd5bf5ec2d 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -427,7 +427,7 @@ class RequestTest < ActiveSupport::TestCase
begin
request = stub_request(mock_rack_env)
request.parameters
- rescue TypeError => e
+ rescue TypeError
# rack will raise a TypeError when parsing this query string
end
assert_equal({}, request.parameters)
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index ab26d1a645..6f38714b2e 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -18,7 +18,7 @@ class ResponseTest < ActiveSupport::TestCase
body.each { |part| parts << part }
assert_equal ["Hello, World!"], parts
end
-
+
test "status handled properly in initialize" do
assert_equal 200, ActionDispatch::Response.new('200 OK').status
end
@@ -26,7 +26,7 @@ class ResponseTest < ActiveSupport::TestCase
test "utf8 output" do
@response.body = [1090, 1077, 1089, 1090].pack("U*")
- status, headers, body = @response.to_a
+ status, headers, _ = @response.to_a
assert_equal 200, status
assert_equal({
"Content-Type" => "text/html; charset=utf-8"
@@ -52,20 +52,20 @@ class ResponseTest < ActiveSupport::TestCase
test "content type" do
[204, 304].each do |c|
@response.status = c.to_s
- status, headers, body = @response.to_a
+ _, headers, _ = @response.to_a
assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
end
[200, 302, 404, 500].each do |c|
@response.status = c.to_s
- status, headers, body = @response.to_a
+ _, headers, _ = @response.to_a
assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
end
end
test "does not include Status header" do
@response.status = "200 OK"
- status, headers, body = @response.to_a
+ _, headers, _ = @response.to_a
assert !headers.has_key?('Status')
end
diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb
new file mode 100644
index 0000000000..9f95d82129
--- /dev/null
+++ b/actionpack/test/dispatch/routing_assertions_test.rb
@@ -0,0 +1,103 @@
+require 'abstract_unit'
+require 'controller/fake_controllers'
+
+class SecureArticlesController < ArticlesController; end
+class BlockArticlesController < ArticlesController; end
+
+class RoutingAssertionsTest < ActionController::TestCase
+
+ def setup
+ @routes = ActionDispatch::Routing::RouteSet.new
+ @routes.draw do
+ resources :articles
+
+ scope 'secure', :constraints => { :protocol => 'https://' } do
+ resources :articles, :controller => 'secure_articles'
+ end
+
+ scope 'block', :constraints => lambda { |r| r.ssl? } do
+ resources :articles, :controller => 'block_articles'
+ end
+ end
+ end
+
+ def test_assert_generates
+ assert_generates('/articles', { :controller => 'articles', :action => 'index' })
+ assert_generates('/articles/1', { :controller => 'articles', :action => 'show', :id => '1' })
+ end
+
+ def test_assert_generates_with_defaults
+ assert_generates('/articles/1/edit', { :controller => 'articles', :action => 'edit' }, { :id => '1' })
+ end
+
+ def test_assert_generates_with_extras
+ assert_generates('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, {}, { :page => '1' })
+ end
+
+ def test_assert_recognizes
+ assert_recognizes({ :controller => 'articles', :action => 'index' }, '/articles')
+ assert_recognizes({ :controller => 'articles', :action => 'show', :id => '1' }, '/articles/1')
+ end
+
+ def test_assert_recognizes_with_extras
+ assert_recognizes({ :controller => 'articles', :action => 'index', :page => '1' }, '/articles', { :page => '1' })
+ end
+
+ def test_assert_recognizes_with_method
+ assert_recognizes({ :controller => 'articles', :action => 'create' }, { :path => '/articles', :method => :post })
+ assert_recognizes({ :controller => 'articles', :action => 'update', :id => '1' }, { :path => '/articles/1', :method => :put })
+ end
+
+ def test_assert_recognizes_with_hash_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'http://test.host/secure/articles')
+ end
+ assert_recognizes({ :controller => 'secure_articles', :action => 'index' }, 'https://test.host/secure/articles')
+ end
+
+ def test_assert_recognizes_with_block_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'http://test.host/block/articles')
+ end
+ assert_recognizes({ :controller => 'block_articles', :action => 'index' }, 'https://test.host/block/articles')
+ end
+
+ def test_assert_routing
+ assert_routing('/articles', :controller => 'articles', :action => 'index')
+ end
+
+ def test_assert_routing_with_defaults
+ assert_routing('/articles/1/edit', { :controller => 'articles', :action => 'edit', :id => '1' }, { :id => '1' })
+ end
+
+ def test_assert_routing_with_extras
+ assert_routing('/articles', { :controller => 'articles', :action => 'index', :page => '1' }, { }, { :page => '1' })
+ end
+
+ def test_assert_routing_with_hash_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_routing('http://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' })
+ end
+ assert_routing('https://test.host/secure/articles', { :controller => 'secure_articles', :action => 'index' })
+ end
+
+ def test_assert_routing_with_block_constraint
+ assert_raise(ActionController::RoutingError) do
+ assert_routing('http://test.host/block/articles', { :controller => 'block_articles', :action => 'index' })
+ end
+ assert_routing('https://test.host/block/articles', { :controller => 'block_articles', :action => 'index' })
+ end
+
+ def test_with_routing
+ with_routing do |routes|
+ routes.draw do
+ resources :articles, :path => 'artikel'
+ end
+
+ assert_routing('/artikel', :controller => 'articles', :action => 'index')
+ assert_raise(ActionController::RoutingError) do
+ assert_routing('/articles', { :controller => 'articles', :action => 'index' })
+ end
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 4bf7880294..1a96587836 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -187,7 +187,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
resources :posts, :only => [:index, :show] do
- resources :comments, :except => :destroy
+ namespace :admin do
+ root :to => "index#index"
+ end
+ resources :comments, :except => :destroy do
+ get "views" => "comments#views", :as => :views
+ end
end
resource :past, :only => :destroy
@@ -205,6 +210,14 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ scope '/hello' do
+ shallow do
+ resources :notes do
+ resources :trackbacks
+ end
+ end
+ end
+
resources :threads, :shallow => true do
resource :owner
resources :messages do
@@ -1676,6 +1689,60 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_shallow_nested_resources_within_scope
+ with_test_routes do
+
+ get '/hello/notes/1/trackbacks'
+ assert_equal 'trackbacks#index', @response.body
+ assert_equal '/hello/notes/1/trackbacks', note_trackbacks_path(:note_id => 1)
+
+ get '/hello/notes/1/edit'
+ assert_equal 'notes#edit', @response.body
+ assert_equal '/hello/notes/1/edit', edit_note_path(:id => '1')
+
+ get '/hello/notes/1/trackbacks/new'
+ assert_equal 'trackbacks#new', @response.body
+ assert_equal '/hello/notes/1/trackbacks/new', new_note_trackback_path(:note_id => 1)
+
+ get '/hello/trackbacks/1'
+ assert_equal 'trackbacks#show', @response.body
+ assert_equal '/hello/trackbacks/1', trackback_path(:id => '1')
+
+ get '/hello/trackbacks/1/edit'
+ assert_equal 'trackbacks#edit', @response.body
+ assert_equal '/hello/trackbacks/1/edit', edit_trackback_path(:id => '1')
+
+ put '/hello/trackbacks/1'
+ assert_equal 'trackbacks#update', @response.body
+
+ post '/hello/notes/1/trackbacks'
+ assert_equal 'trackbacks#create', @response.body
+
+ delete '/hello/trackbacks/1'
+ assert_equal 'trackbacks#destroy', @response.body
+
+ get '/hello/notes'
+ assert_equal 'notes#index', @response.body
+
+ post '/hello/notes'
+ assert_equal 'notes#create', @response.body
+
+ get '/hello/notes/new'
+ assert_equal 'notes#new', @response.body
+ assert_equal '/hello/notes/new', new_note_path
+
+ get '/hello/notes/1'
+ assert_equal 'notes#show', @response.body
+ assert_equal '/hello/notes/1', note_path(:id => 1)
+
+ put '/hello/notes/1'
+ assert_equal 'notes#update', @response.body
+
+ delete '/hello/notes/1'
+ assert_equal 'notes#destroy', @response.body
+ end
+ end
+
def test_custom_resource_routes_are_scoped
with_test_routes do
assert_equal '/customers/recent', recent_customers_path
@@ -2246,6 +2313,18 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_nested_route_in_nested_resource
+ get "/posts/1/comments/2/views"
+ assert_equal "comments#views", @response.body
+ assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2')
+ end
+
+ def test_root_in_deeply_nested_scope
+ get "/posts/1/admin"
+ assert_equal "admin/index#index", @response.body
+ assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1')
+ end
+
private
def with_test_routes
yield
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index 256d0781c7..27f55fd7ab 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -194,7 +194,6 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
with_test_route_set do
get '/set_session_value'
assert_response :success
- session_payload = response.body
assert_equal "_myapp_session=#{response.body}; path=/; HttpOnly",
headers['Set-Cookie']
diff --git a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
new file mode 100644
index 0000000000..5db0822f07
--- /dev/null
+++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
@@ -0,0 +1,4 @@
+Before
+<%= render :partial => "test/partial.html.erb" %>
+<%= yield %>
+After
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index fbcc99a17a..a1a6b5f1d0 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -54,6 +54,9 @@ class AssetTagHelperTest < ActionView::TestCase
def teardown
config.perform_caching = false
ENV.delete('RAILS_ASSET_ID')
+
+ JavascriptIncludeTag.expansions.clear
+ StylesheetIncludeTag.expansions.clear
end
AutoDiscoveryToTag = {
@@ -92,6 +95,7 @@ class AssetTagHelperTest < ActionView::TestCase
%(javascript_include_tag(:all)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag(:all, :recursive => true)) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/subdir/subdir.js" type="text/javascript"></script>\n<script src="/javascripts/version.1.0.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag(:defaults, "bank")) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
+ %(javascript_include_tag(:defaults, "application")) => %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag("bank", :defaults)) => %(<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>),
%(javascript_include_tag("http://example.com/all")) => %(<script src="http://example.com/all" type="text/javascript"></script>),
@@ -262,10 +266,40 @@ class AssetTagHelperTest < ActionView::TestCase
assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>), javascript_include_tag('controls', :robbery, 'effects')
end
+ def test_custom_javascript_expansions_return_unique_set
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :defaults => %w(prototype effects dragdrop controls rails application)
+ assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults)
+ end
+
def test_custom_javascript_expansions_and_defaults_puts_application_js_at_the_end
ENV["RAILS_ASSET_ID"] = ""
ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"]
- assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls',:defaults, :robbery, 'effects')
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls',:defaults, :robbery, 'effects')
+ end
+
+ def test_javascript_include_tag_should_not_output_the_same_asset_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('prototype', 'effects', :defaults)
+ end
+
+ def test_javascript_include_tag_should_not_output_the_same_expansion_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag(:defaults, :defaults)
+ end
+
+ def test_single_javascript_asset_keys_should_take_precedence_over_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls', :defaults, 'effects')
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/rails.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), javascript_include_tag('controls', 'effects', :defaults)
+ end
+
+ def test_registering_javascript_expansions_merges_with_existing_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank']
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['robber']
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :can_merge => ['bank']
+ assert_dom_equal %(<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>), javascript_include_tag(:can_merge)
end
def test_custom_javascript_expansions_with_undefined_symbol
@@ -273,6 +307,14 @@ class AssetTagHelperTest < ActionView::TestCase
assert_raise(ArgumentError) { javascript_include_tag('first', :monkey, 'last') }
end
+ def test_custom_javascript_and_stylesheet_expansion_with_same_name
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_javascript_expansion :robbery => ["bank", "robber"]
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :robbery => ["money", "security"]
+ assert_dom_equal %(<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/bank.js" type="text/javascript"></script>\n<script src="/javascripts/robber.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>), javascript_include_tag('controls', :robbery, 'effects')
+ assert_dom_equal %(<link href="/stylesheets/style.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/money.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/security.css" rel="stylesheet" type="text/css" media="screen" />\n<link href="/stylesheets/print.css" rel="stylesheet" type="text/css" media="screen" />), stylesheet_link_tag('style', :robbery, 'print')
+ end
+
def test_reset_javascript_expansions
JavascriptIncludeTag.expansions.clear
assert_raise(ArgumentError) { javascript_include_tag(:defaults) }
@@ -314,11 +356,42 @@ class AssetTagHelperTest < ActionView::TestCase
assert_dom_equal %(<link href="/stylesheets/version.1.0.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/subdir/subdir.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('version.1.0', :robbery, 'subdir/subdir')
end
+ def test_custom_stylesheet_expansions_return_unique_set
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london)
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:cities)
+ end
+
+ def test_stylesheet_link_tag_should_not_output_the_same_asset_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('wellington', 'wellington', 'amsterdam')
+ end
+
+ def test_stylesheet_link_tag_should_not_output_the_same_expansion_twice
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london)
+ assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:cities, :cities)
+ end
+
+ def test_single_stylesheet_asset_keys_should_take_precedence_over_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :cities => %w(wellington amsterdam london)
+ assert_dom_equal %(<link href="/stylesheets/london.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag('london', :cities)
+ end
+
def test_custom_stylesheet_expansions_with_undefined_symbol
ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :monkey => nil
assert_raise(ArgumentError) { stylesheet_link_tag('first', :monkey, 'last') }
end
+ def test_registering_stylesheet_expansions_merges_with_existing_expansions
+ ENV["RAILS_ASSET_ID"] = ""
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank']
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['robber']
+ ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :can_merge => ['bank']
+ assert_dom_equal %(<link href="/stylesheets/bank.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/stylesheets/robber.css" media="screen" rel="stylesheet" type="text/css" />), stylesheet_link_tag(:can_merge)
+ end
+
def test_image_path
ImagePathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) }
end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 55c384e68f..aca2fef170 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -1882,10 +1882,17 @@ class DateHelperTest < ActionView::TestCase
end
def test_datetime_select_defaults_to_time_zone_now_when_config_time_zone_is_set
- time = stub(:year => 2004, :month => 6, :day => 15, :hour => 16, :min => 35, :sec => 0)
- time_zone = mock()
- time_zone.expects(:now).returns time
- Time.zone_default = time_zone
+ # The love zone is UTC+0
+ mytz = Class.new(ActiveSupport::TimeZone) {
+ attr_accessor :now
+ }.create('tenderlove', 0)
+
+ now = Time.mktime(2004, 6, 15, 16, 35, 0)
+ mytz.now = now
+ Time.zone = mytz
+
+ assert_equal mytz, Time.zone
+
@post = Post.new
expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}
@@ -1912,7 +1919,7 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, datetime_select("post", "updated_at")
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_datetime_select_with_html_options_within_fields_for
@@ -2700,6 +2707,32 @@ class DateHelperTest < ActionView::TestCase
assert time_select("post", "written_on", :ignore_date => true).html_safe?
end
+ def test_time_tag_with_date
+ date = Date.today
+ expected = "<time datetime=\"#{date.rfc3339}\">#{I18n.l(date, :format => :long)}</time>"
+ assert_equal expected, time_tag(date)
+ end
+
+ def test_time_tag_with_time
+ time = Time.now
+ expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :long)}</time>"
+ assert_equal expected, time_tag(time)
+ end
+
+ def test_time_tag_pubdate_option
+ assert_match /<time.*pubdate="pubdate">.*<\/time>/, time_tag(Time.now, :pubdate => true)
+ end
+
+ def test_time_tag_with_given_text
+ assert_match /<time.*>Right now<\/time>/, time_tag(Time.now, 'Right now')
+ end
+
+ def test_time_tag_with_different_format
+ time = Time.now
+ expected = "<time datetime=\"#{time.xmlschema}\">#{I18n.l(time, :format => :short)}</time>"
+ assert_equal expected, time_tag(time, :format => :short)
+ end
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 2c60096475..31da26de7f 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -630,7 +630,7 @@ class FormHelperTest < ActionView::TestCase
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
"<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='commit' id='post_submit' type='submit' value='Create post' />"
+ "<input name='commit' type='submit' value='Create post' />"
end
assert_dom_equal expected, output_buffer
@@ -709,7 +709,7 @@ class FormHelperTest < ActionView::TestCase
"<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='other_name[secret]' value='0' type='hidden' />" +
"<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" +
- "<input name='commit' id='other_name_submit' value='Create post' type='submit' />"
+ "<input name='commit' value='Create post' type='submit' />"
end
assert_dom_equal expected, output_buffer
@@ -731,7 +731,7 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
-
+
def test_form_for_with_search_field
# Test case for bug which would emit an "object" attribute
# when used with form_for using a search_field form helper
@@ -843,7 +843,7 @@ class FormHelperTest < ActionView::TestCase
end
expected = whole_form('/posts', 'new_post', 'new_post') do
- "<input name='commit' id='post_submit' type='submit' value='Create Post' />"
+ "<input name='commit' type='submit' value='Create Post' />"
end
assert_dom_equal expected, output_buffer
@@ -859,7 +859,7 @@ class FormHelperTest < ActionView::TestCase
end
expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
- "<input name='commit' id='post_submit' type='submit' value='Confirm Post changes' />"
+ "<input name='commit' type='submit' value='Confirm Post changes' />"
end
assert_dom_equal expected, output_buffer
@@ -875,7 +875,7 @@ class FormHelperTest < ActionView::TestCase
end
expected = whole_form do
- "<input name='commit' class='extra' id='post_submit' type='submit' value='Save changes' />"
+ "<input name='commit' class='extra' type='submit' value='Save changes' />"
end
assert_dom_equal expected, output_buffer
@@ -891,7 +891,7 @@ class FormHelperTest < ActionView::TestCase
end
expected = whole_form('/posts/123', 'another_post_edit', 'another_post_edit', :method => 'put') do
- "<input name='commit' id='another_post_submit' type='submit' value='Update your Post' />"
+ "<input name='commit' type='submit' value='Update your Post' />"
end
assert_dom_equal expected, output_buffer
@@ -1084,6 +1084,25 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_inline_block
+ @post.author = Author.new(321)
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ concat f.fields_for(:author) { |af|
+ af.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' +
+ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement
@post.author = Author.new(321)
@@ -1127,6 +1146,29 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_inline_block
+ @post.comments = Array.new(2) { |id| Comment.new(id + 1) }
+
+ form_for(@post) do |f|
+ concat f.text_field(:title)
+ @post.comments.each do |comment|
+ concat f.fields_for(:comments, comment) { |cf|
+ cf.text_field(:name)
+ }
+ end
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do
+ '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' +
+ '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' +
+ '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' +
+ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' +
+ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement
@post.comments = Array.new(2) { |id| Comment.new(id + 1) }
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index bc04398afa..69b1d4ff7b 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -7,7 +7,7 @@ class FormOptionsHelperTest < ActionView::TestCase
tests ActionView::Helpers::FormOptionsHelper
silence_warnings do
- Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin)
+ Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments)
Continent = Struct.new('Continent', :continent_name, :countries)
Country = Struct.new('Country', :country_id, :country_name)
Firm = Struct.new('Firm', :time_zone)
@@ -130,6 +130,13 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_boolean_array_options_for_select_with_selection_and_disabled_value
+ assert_dom_equal(
+ "<option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option>",
+ options_for_select([ true, false ], :selected => false, :disabled => nil)
+ )
+ end
+
def test_array_options_for_string_include_in_other_string_bug_fix
assert_dom_equal(
"<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>",
@@ -177,7 +184,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer
- albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")]
+ albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")]
assert_dom_equal(
%(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>),
options_from_collection_for_select(albums, "id", "genre", :selected => "1")
@@ -185,7 +192,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_preselected_value_as_integer_and_option_value_is_string
- albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")]
+ albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")]
assert_dom_equal(
%(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>),
@@ -194,7 +201,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_preselected_value_as_string_and_option_value_is_float
- albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
assert_dom_equal(
%(<option value="1.0">rap</option>\n<option value="2.0" selected="selected">pop</option>),
@@ -203,7 +210,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_preselected_value_as_nil
- albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
assert_dom_equal(
%(<option value="1.0">rap</option>\n<option value="2.0">pop</option>),
@@ -212,7 +219,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_disabled_value_as_nil
- albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
assert_dom_equal(
%(<option value="1.0">rap</option>\n<option value="2.0">pop</option>),
@@ -221,7 +228,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_disabled_value_as_array
- albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")]
assert_dom_equal(
%(<option disabled="disabled" value="1.0">rap</option>\n<option disabled="disabled" value="2.0">pop</option>),
@@ -230,7 +237,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_collection_options_with_preselected_values_as_string_array_and_option_value_is_float
- albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ]
+ albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ]
assert_dom_equal(
%(<option value="1.0" selected="selected">rap</option>\n<option value="2.0">pop</option>\n<option value="3.0" selected="selected">country</option>),
@@ -364,6 +371,15 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_select_with_boolean_method
+ @post = Post.new
+ @post.allow_comments = false
+ assert_dom_equal(
+ "<select id=\"post_allow_comments\" name=\"post[allow_comments]\"><option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option></select>",
+ select("post", "allow_comments", %w( true false ))
+ )
+ end
+
def test_select_under_fields_for
@post = Post.new
@post.category = "<mus>"
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index f3933a25b9..f8671f2980 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -385,6 +385,57 @@ class FormTagHelperTest < ActionView::TestCase
)
end
+ def test_button_tag
+ assert_dom_equal(
+ %(<button name="button" type="submit">Button</button>),
+ button_tag
+ )
+ end
+
+ def test_button_tag_with_submit_type
+ assert_dom_equal(
+ %(<button name="button" type="submit">Save</button>),
+ button_tag("Save", :type => "submit")
+ )
+ end
+
+ def test_button_tag_with_button_type
+ assert_dom_equal(
+ %(<button name="button" type="button">Button</button>),
+ button_tag("Button", :type => "button")
+ )
+ end
+
+ def test_button_tag_with_reset_type
+ assert_dom_equal(
+ %(<button name="button" type="reset">Reset</button>),
+ button_tag("Reset", :type => "reset")
+ )
+ end
+
+ def test_button_tag_with_disabled_option
+ assert_dom_equal(
+ %(<button name="button" type="reset" disabled="disabled">Reset</button>),
+ button_tag("Reset", :type => "reset", :disabled => true)
+ )
+ end
+
+ def test_button_tag_escape_content
+ assert_dom_equal(
+ %(<button name="button" type="reset" disabled="disabled">&lt;b&gt;Reset&lt;/b&gt;</button>),
+ button_tag("<b>Reset</b>", :type => "reset", :disabled => true)
+ )
+ end
+
+ def test_button_tag_with_block
+ assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' })
+ end
+
+ def test_button_tag_with_block_and_options
+ output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') }
+ assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output)
+ end
+
def test_image_submit_tag_with_confirmation
assert_dom_equal(
%(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb
index 3e80317b30..fcc3782f04 100644
--- a/actionpack/test/template/html-scanner/sanitizer_test.rb
+++ b/actionpack/test/template/html-scanner/sanitizer_test.rb
@@ -130,6 +130,13 @@ class SanitizerTest < ActionController::TestCase
assert sanitizer.send(:contains_bad_protocols?, 'src', "#{proto}://bad")
end
end
+
+ def test_should_accept_good_protocols_ignoring_case
+ sanitizer = HTML::WhiteListSanitizer.new
+ HTML::WhiteListSanitizer.allowed_protocols.each do |proto|
+ assert !sanitizer.send(:contains_bad_protocols?, 'src', "#{proto.capitalize}://good")
+ end
+ end
def test_should_accept_good_protocols
sanitizer = HTML::WhiteListSanitizer.new
diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb
index 435936b19f..8b8b005a1d 100644
--- a/actionpack/test/template/log_subscriber_test.rb
+++ b/actionpack/test/template/log_subscriber_test.rb
@@ -57,7 +57,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_partial_with_implicit_path
- @view.stubs(:controller_prefix).returns("test")
+ @view.stubs(:controller_prefixes).returns(%w(test))
@view.render(Customer.new("david"), :greeting => "hi")
wait
@@ -74,7 +74,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_collection_with_implicit_path
- @view.stubs(:controller_prefix).returns("test")
+ @view.stubs(:controller_prefixes).returns(%w(test))
@view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi")
wait
@@ -83,7 +83,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_collection_template_without_path
- @view.stubs(:controller_prefix).returns("test")
+ @view.stubs(:controller_prefixes).returns(%w(test))
@view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi")
wait
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
index c9dd27cf2a..8d063e66b0 100644
--- a/actionpack/test/template/lookup_context_test.rb
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -47,7 +47,7 @@ class LookupContextTest < ActiveSupport::TestCase
end
test "handles */* formats" do
- @lookup_context.formats = [:"*/*"]
+ @lookup_context.formats = ["*/*"]
assert_equal Mime::SET, @lookup_context.formats
end
@@ -73,25 +73,25 @@ class LookupContextTest < ActiveSupport::TestCase
assert_equal :pt, I18n.locale
assert_equal :pt, @lookup_context.locale
ensure
- I18n.config = I18n.config.i18n_config
+ I18n.config = I18n.config.original_config
end
assert_equal :pt, I18n.locale
end
test "find templates using the given view paths and configured details" do
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal "Hello world!", template.source
@lookup_context.locale = :da
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal "Hey verden", template.source
end
test "found templates respects given formats if one cannot be found from template or handler" do
ActionView::Template::Handlers::ERB.expects(:default_format).returns(nil)
@lookup_context.formats = [:text]
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal [:text], template.formats
end
@@ -137,44 +137,44 @@ class LookupContextTest < ActiveSupport::TestCase
test "gives the key forward to the resolver, so it can be used as cache key" do
@lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo")
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# Now we are going to change the template, but it won't change the returned template
# since we will hit the cache.
@lookup_context.view_paths.first.hash["test/_foo.erb"] = "Bar"
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# This time we will change the locale. The updated template should be picked since
# lookup_context generated a new key after we changed the locale.
@lookup_context.locale = :da
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Bar", template.source
# Now we will change back the locale and it will still pick the old template.
# This is expected because lookup_context will reuse the previous key for :en locale.
@lookup_context.locale = :en
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# Finally, we can expire the cache. And the expected template will be used.
@lookup_context.view_paths.first.clear_cache
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Bar", template.source
end
test "can disable the cache on demand" do
@lookup_context.view_paths = ActionView::FixtureResolver.new("test/_foo.erb" => "Foo")
- old_template = @lookup_context.find("foo", "test", true)
+ old_template = @lookup_context.find("foo", %w(test), true)
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal template, old_template
assert @lookup_context.cache
template = @lookup_context.disable_cache do
assert !@lookup_context.cache
- @lookup_context.find("foo", "test", true)
+ @lookup_context.find("foo", %w(test), true)
end
assert @lookup_context.cache
@@ -182,11 +182,11 @@ class LookupContextTest < ActiveSupport::TestCase
end
test "data can be stored in cached templates" do
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
template.data["cached"] = "data"
assert_equal "Hello world!", template.source
- template = @lookup_context.find("hello_world", "test")
+ template = @lookup_context.find("hello_world", %w(test))
assert_equal "data", template.data["cached"]
assert_equal "Hello world!", template.source
end
@@ -200,54 +200,74 @@ class LookupContextWithFalseCaching < ActiveSupport::TestCase
end
test "templates are always found in the resolver but timestamp is checked before being compiled" do
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# Now we are going to change the template, but it won't change the returned template
# since the timestamp is the same.
@resolver.hash["test/_foo.erb"][0] = "Bar"
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
# Now update the timestamp.
@resolver.hash["test/_foo.erb"][1] = Time.now.utc
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Bar", template.source
end
test "if no template was found in the second lookup, with no cache, raise error" do
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
@resolver.hash.clear
assert_raise ActionView::MissingTemplate do
- @lookup_context.find("foo", "test", true)
+ @lookup_context.find("foo", %w(test), true)
end
end
test "if no template was cached in the first lookup, retrieval should work in the second call" do
@resolver.hash.clear
assert_raise ActionView::MissingTemplate do
- @lookup_context.find("foo", "test", true)
+ @lookup_context.find("foo", %w(test), true)
end
@resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)]
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "Foo", template.source
end
test "data can be stored as long as template was not updated" do
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
template.data["cached"] = "data"
assert_equal "Foo", template.source
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_equal "data", template.data["cached"]
assert_equal "Foo", template.source
@resolver.hash["test/_foo.erb"][1] = Time.now.utc
- template = @lookup_context.find("foo", "test", true)
+ template = @lookup_context.find("foo", %w(test), true)
assert_nil template.data["cached"]
assert_equal "Foo", template.source
end
-end \ No newline at end of file
+end
+
+class TestMissingTemplate < ActiveSupport::TestCase
+ def setup
+ @lookup_context = ActionView::LookupContext.new("/Path/to/views", {})
+ end
+
+ test "if no template was found we get a helpful error message including the inheritance chain" do
+ e = assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", %w(parent child))
+ end
+ assert_match %r{Missing template parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message
+ end
+
+ test "if no partial was found we get a helpful error message including the inheritance chain" do
+ e = assert_raise ActionView::MissingTemplate do
+ @lookup_context.find("foo", %w(parent child), true)
+ end
+ assert_match %r{Missing partial parent/foo, child/foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message
+ end
+end
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index ab127521ad..156b7cb5ff 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -100,6 +100,8 @@ class NumberHelperTest < ActionView::TestCase
assert_equal("0", number_with_precision(0, :precision => 0))
assert_equal("0.00100", number_with_precision(0.001, :precision => 5))
assert_equal("0.001", number_with_precision(0.00111, :precision => 3))
+ assert_equal("10.00", number_with_precision(9.995, :precision => 2))
+ assert_equal("11.00", number_with_precision(10.995, :precision => 2))
end
def test_number_with_precision_with_custom_delimiter_and_separator
@@ -125,6 +127,9 @@ class NumberHelperTest < ActionView::TestCase
assert_equal "0.0001", number_with_precision(0.0001, :precision => 1, :significant => true )
assert_equal "0.000100", number_with_precision(0.0001, :precision => 3, :significant => true )
assert_equal "0.0001", number_with_precision(0.0001111, :precision => 1, :significant => true )
+ assert_equal "10.0", number_with_precision(9.995, :precision => 3, :significant => true)
+ assert_equal "9.99", number_with_precision(9.994, :precision => 3, :significant => true)
+ assert_equal "11.0", number_with_precision(10.995, :precision => 3, :significant => true)
end
def test_number_with_precision_with_strip_insignificant_zeros
diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb
new file mode 100644
index 0000000000..fc127c24e9
--- /dev/null
+++ b/actionpack/test/template/output_safety_helper_test.rb
@@ -0,0 +1,30 @@
+require 'abstract_unit'
+require 'testing_sandbox'
+
+class OutputSafetyHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::OutputSafetyHelper
+ include TestingSandbox
+
+ def setup
+ @string = "hello"
+ end
+
+ test "raw returns the safe string" do
+ result = raw(@string)
+ assert_equal @string, result
+ assert result.html_safe?
+ end
+
+ test "raw handles nil values correctly" do
+ assert_equal "", raw(nil)
+ end
+
+ test "safe_join should html_escape any items, including the separator, if they are not html_safe" do
+ joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
+ assert_equal "<p>foo</p>&lt;br /&gt;&lt;p&gt;bar&lt;/p&gt;", joined
+
+ joined = safe_join(["<p>foo</p>".html_safe, "<p>bar</p>".html_safe], "<br />".html_safe)
+ assert_equal "<p>foo</p><br /><p>bar</p>", joined
+ end
+
+end \ No newline at end of file
diff --git a/actionpack/test/template/raw_output_helper_test.rb b/actionpack/test/template/raw_output_helper_test.rb
deleted file mode 100644
index 598aa5b1d8..0000000000
--- a/actionpack/test/template/raw_output_helper_test.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'abstract_unit'
-require 'testing_sandbox'
-
-class RawOutputHelperTest < ActionView::TestCase
- tests ActionView::Helpers::RawOutputHelper
- include TestingSandbox
-
- def setup
- @string = "hello"
- end
-
- test "raw returns the safe string" do
- result = raw(@string)
- assert_equal @string, result
- assert result.html_safe?
- end
-
- test "raw handles nil values correctly" do
- assert_equal "", raw(nil)
- end
-end \ No newline at end of file
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 38bedd2e4e..034fb6c210 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -146,7 +146,12 @@ module RenderTestCases
assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
end
- def test_render_partial_collection_as
+ def test_render_partial_collection_as_by_string
+ assert_equal "david david davidmary mary mary",
+ @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => 'customer')
+ end
+
+ def test_render_partial_collection_as_by_symbol
assert_equal "david david davidmary mary mary",
@view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer)
end
@@ -204,6 +209,11 @@ module RenderTestCases
@view.formats = nil
end
+ def test_render_layout_with_block_and_other_partial_inside
+ render = @view.render(:layout => "test/layout_with_partial_and_yield.html.erb") { "Yield!" }
+ assert_equal "Before\npartial html\nYield!\nAfter\n", render
+ end
+
def test_render_inline
assert_equal "Hello, World!", @view.render(:inline => "Hello, World!")
end
diff --git a/actionpack/test/template/template_error_test.rb b/actionpack/test/template/template_error_test.rb
new file mode 100644
index 0000000000..3a874082d9
--- /dev/null
+++ b/actionpack/test/template/template_error_test.rb
@@ -0,0 +1,13 @@
+require "abstract_unit"
+
+class TemplateErrorTest < ActiveSupport::TestCase
+ def test_provides_original_message
+ error = ActionView::Template::Error.new("test", {}, Exception.new("original"))
+ assert_equal "original", error.message
+ end
+
+ def test_provides_useful_inspect
+ error = ActionView::Template::Error.new("test", {}, Exception.new("original"))
+ assert_equal "#<ActionView::Template::Error: original>", error.inspect
+ end
+end
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index 2ec640c84c..3432a02c3c 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -95,14 +95,14 @@ class TestERBTemplate < ActiveSupport::TestCase
def test_refresh_with_templates
@template = new_template("Hello", :virtual_path => "test/foo/bar")
@template.locals = [:key]
- @context.lookup_context.expects(:find_template).with("bar", "test/foo", false, [:key]).returns("template")
+ @context.lookup_context.expects(:find_template).with("bar", %w(test/foo), false, [:key]).returns("template")
assert_equal "template", @template.refresh(@context)
end
def test_refresh_with_partials
@template = new_template("Hello", :virtual_path => "test/_foo")
@template.locals = [:key]
- @context.lookup_context.expects(:find_template).with("foo", "test", true, [:key]).returns("partial")
+ @context.lookup_context.expects(:find_template).with("foo", %w(test), true, [:key]).returns("partial")
assert_equal "partial", @template.refresh(@context)
end
diff --git a/actionpack/test/template/test_case_test.rb b/actionpack/test/template/test_case_test.rb
index a745999622..11c355dc6d 100644
--- a/actionpack/test/template/test_case_test.rb
+++ b/actionpack/test/template/test_case_test.rb
@@ -116,6 +116,27 @@ module ActionView
end
end
+ class ControllerHelperMethod < ActionView::TestCase
+ module SomeHelper
+ def some_method
+ render :partial => 'test/from_helper'
+ end
+ end
+
+ helper SomeHelper
+
+ test "can call a helper method defined on the current controller from a helper" do
+ @controller.singleton_class.class_eval <<-EOF, __FILE__, __LINE__ + 1
+ def render_from_helper
+ 'controller_helper_method'
+ end
+ EOF
+ @controller.class.helper_method :render_from_helper
+
+ assert_equal 'controller_helper_method', some_method
+ end
+ end
+
class AssignsTest < ActionView::TestCase
setup do
ActiveSupport::Deprecation.stubs(:warn)
@@ -146,7 +167,7 @@ module ActionView
end
end
end
-
+
class HelperExposureTest < ActionView::TestCase
helper(Module.new do
def render_from_helper
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index 9e9ed9120d..d0d4286393 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -1,4 +1,4 @@
-# encoding: us-ascii
+# encoding: utf-8
require 'abstract_unit'
require 'testing_sandbox'
@@ -415,6 +415,12 @@ class TextHelperTest < ActionView::TestCase
link10_raw = 'http://www.mail-archive.com/ruby-talk@ruby-lang.org/'
link10_result = generate_result(link10_raw)
assert_equal %(<p>#{link10_result} Link</p>), auto_link("<p>#{link10_raw} Link</p>")
+
+ link11_raw = 'http://asakusa.rubyist.net/'
+ link11_result = generate_result(link11_raw)
+ with_kcode 'u' do
+ assert_equal %(浅草.rbの公式サイトはこちら#{link11_result}), auto_link("浅草.rbの公式サイトはこちら#{link11_raw}")
+ end
end
def test_auto_link_should_sanitize_input_when_sanitize_option_is_not_false
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index 4a8cea36d4..fc330f7a73 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -20,6 +20,7 @@ class UrlHelperTest < ActiveSupport::TestCase
include routes.url_helpers
include ActionView::Helpers::UrlHelper
+ include ActionView::Helpers::JavaScriptHelper
include ActionDispatch::Assertions::DomAssertions
include ActionView::Context
include RenderERBUtils
@@ -50,6 +51,14 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com")
end
+ def test_button_to_with_form_class
+ assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"custom-class\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :form_class => 'custom-class')
+ end
+
+ def test_button_to_with_form_class_escapes
+ assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"&lt;script&gt;evil_js&lt;/script&gt;\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :form_class => '<script>evil_js</script>')
+ end
+
def test_button_to_with_query
assert_dom_equal "<form method=\"post\" action=\"http://www.example.com/q1=v1&amp;q2=v2\" class=\"button_to\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com/q1=v1&q2=v2")
end
@@ -359,13 +368,13 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_mail_to_with_javascript
snippet = mail_to("me@domain.com", "My email", :encode => "javascript")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", snippet
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet
assert snippet.html_safe?
end
def test_mail_to_with_javascript_unicode
snippet = mail_to("unicode@example.com", "únicode", :encode => "javascript")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%22%3e%c3%ba%6e%69%63%6f%64%65%3c%2f%61%3e%27%29%3b'))</script>", snippet
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>", snippet
assert snippet.html_safe
end
@@ -391,8 +400,8 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_dom_equal "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)")
assert_dom_equal "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">My email</a>", mail_to("me@domain.com", "My email", :encode => "hex", :replace_at => "(at)")
assert_dom_equal "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d\">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#40;&#100;&#111;&#116;&#41;&#99;&#111;&#109;</a>", mail_to("me@domain.com", nil, :encode => "hex", :replace_at => "(at)", :replace_dot => "(dot)")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
- assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", "My email", :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
+ assert_dom_equal "<script type=\"text/javascript\">eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>", mail_to("me@domain.com", nil, :encode => "javascript", :replace_at => "(at)", :replace_dot => "(dot)")
end
# TODO: button_to looks at this ... why?
diff --git a/activemodel/CHANGELOG b/activemodel/CHANGELOG
index 4e963c77b0..3082c7186a 100644
--- a/activemodel/CHANGELOG
+++ b/activemodel/CHANGELOG
@@ -1,15 +1,20 @@
*Rails 3.1.0 (unreleased)*
-* No changes
+* 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]
+
*Rails 3.0.2 (unreleased)*
* 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]
diff --git a/activemodel/MIT-LICENSE b/activemodel/MIT-LICENSE
index a345a2419d..7ad1051066 100644
--- a/activemodel/MIT-LICENSE
+++ b/activemodel/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index 9b96bfaba7..d9a9bdae3e 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -41,7 +41,7 @@ modules:
define_model_callbacks :create
def create
- _run_create_callbacks do
+ run_callbacks :create do
# Your create action methods here
end
end
@@ -84,7 +84,7 @@ modules:
attr_reader :errors
def validate!
- errors.add(:name, "can not be nil") if name == nil
+ errors.add(:name, "can not be nil") if name.nil?
end
def ErrorsPerson.human_attribute_name(attr, options = {})
@@ -94,10 +94,10 @@ modules:
end
person.errors.full_messages
- # => ["Name Can not be nil"]
+ # => ["Name can not be nil"]
person.errors.full_messages
- # => ["Name Can not be nil"]
+ # => ["Name can not be nil"]
{Learn more}[link:classes/ActiveModel/Errors.html]
diff --git a/activemodel/Rakefile b/activemodel/Rakefile
index 0372c7a03e..0a10912695 100755
--- a/activemodel/Rakefile
+++ b/activemodel/Rakefile
@@ -14,7 +14,7 @@ namespace :test do
task :isolated do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
Dir.glob("#{dir}/test/**/*_test.rb").all? do |file|
- system(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file)
+ sh(ruby, '-w', "-I#{dir}/lib", "-I#{dir}/test", file)
end or raise "Failures"
end
end
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index 1f38e70c36..fec9c7ff8b 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -22,4 +22,5 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('builder', '~> 3.0.0')
s.add_dependency('i18n', '~> 0.5.0')
+ s.add_dependency('bcrypt-ruby', '~> 2.1.4')
end
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index be0f24ff92..d0e2a6f39c 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -42,6 +42,7 @@ module ActiveModel
autoload :Naming
autoload :Observer, 'active_model/observing'
autoload :Observing
+ autoload :SecurePassword
autoload :Serialization
autoload :TestCase
autoload :Translation
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index fc5f5c4c66..2a99450a3d 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -98,7 +98,7 @@ module ActiveModel
def define_attr_method(name, value=nil, &block)
sing = singleton_class
sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
- if method_defined?(:'original_#{name}')
+ if method_defined?('original_#{name}')
undef :'original_#{name}'
end
alias_method :'original_#{name}', :'#{name}'
@@ -109,7 +109,7 @@ module ActiveModel
# use eval instead of a block to work around a memory leak in dev
# mode in fcgi
sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
- def #{name}; #{value.to_s.inspect}; end
+ def #{name}; #{value.nil? ? 'nil' : value.to_s.inspect}; end
eorb
end
end
@@ -229,15 +229,13 @@ module ActiveModel
def alias_attribute(new_name, old_name)
attribute_method_matchers.each do |matcher|
- module_eval <<-STR, __FILE__, __LINE__ + 1
- def #{matcher.method_name(new_name)}(*args)
- send(:#{matcher.method_name(old_name)}, *args)
- end
- STR
+ define_method(matcher.method_name(new_name)) do |*args|
+ send(matcher.method_name(old_name), *args)
+ end
end
end
- # Declares a the attributes that should be prefixed and suffixed by
+ # Declares the attributes that should be prefixed and suffixed by
# ActiveModel::AttributeMethods.
#
# To use, pass in an array of attribute names (as strings or symbols),
@@ -262,30 +260,30 @@ module ActiveModel
# end
# end
def define_attribute_methods(attr_names)
- return if attribute_methods_generated?
- attr_names.each do |attr_name|
- attribute_method_matchers.each do |matcher|
- unless instance_method_already_implemented?(matcher.method_name(attr_name))
- generate_method = "define_method_#{matcher.prefix}attribute#{matcher.suffix}"
+ attr_names.each { |attr_name| define_attribute_method(attr_name) }
+ end
- if respond_to?(generate_method)
- send(generate_method, attr_name)
- else
- method_name = matcher.method_name(attr_name)
+ def define_attribute_method(attr_name)
+ attribute_method_matchers.each do |matcher|
+ unless instance_method_already_implemented?(matcher.method_name(attr_name))
+ generate_method = "define_method_#{matcher.prefix}attribute#{matcher.suffix}"
- generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
- if method_defined?(:'#{method_name}')
- undef :'#{method_name}'
- end
- def #{method_name}(*args)
- send(:#{matcher.method_missing_target}, '#{attr_name}', *args)
- end
- STR
- end
+ if respond_to?(generate_method)
+ send(generate_method, attr_name)
+ else
+ method_name = matcher.method_name(attr_name)
+
+ generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
+ if method_defined?('#{method_name}')
+ undef :'#{method_name}'
+ end
+ define_method('#{method_name}') do |*args|
+ send('#{matcher.method_missing_target}', '#{attr_name}', *args)
+ end
+ STR
end
end
end
- @attribute_methods_generated = true
end
# Removes all the previously dynamically defined methods from the class
@@ -293,7 +291,6 @@ module ActiveModel
generated_attribute_methods.module_eval do
instance_methods.each { |m| undef_method(m) }
end
- @attribute_methods_generated = nil
end
# Returns true if the attribute methods defined have been generated.
@@ -305,11 +302,6 @@ module ActiveModel
end
end
- # Returns true if the attribute methods defined have been generated.
- def attribute_methods_generated?
- @attribute_methods_generated ||= nil
- end
-
protected
def instance_method_already_implemented?(method_name)
method_defined?(method_name)
@@ -325,7 +317,7 @@ module ActiveModel
options.symbolize_keys!
@prefix, @suffix = options[:prefix] || '', options[:suffix] || ''
@regex = /^(#{Regexp.escape(@prefix)})(.+?)(#{Regexp.escape(@suffix)})$/
- @method_missing_target = :"#{@prefix}attribute#{@suffix}"
+ @method_missing_target = "#{@prefix}attribute#{@suffix}"
@method_name = "#{prefix}%s#{suffix}"
end
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
index aaa41f5ec6..2a1f51a9a7 100644
--- a/activemodel/lib/active_model/callbacks.rb
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -24,14 +24,11 @@ module ActiveModel
# you want callbacks on in a block so that the callbacks get a chance to fire:
#
# def create
- # _run_create_callbacks do
+ # run_callbacks :create do
# # Your create action methods here
# end
# end
#
- # The _run_<method_name>_callbacks methods are dynamically created when you extend
- # the <tt>ActiveModel::Callbacks</tt> module.
- #
# Then in your class, you can use the +before_create+, +after_create+ and +around_create+
# methods, just as you would in an Active Record module.
#
@@ -102,7 +99,7 @@ module ActiveModel
define_callbacks(callback, options)
types.each do |type|
- send(:"_define_#{type}_model_callback", self, callback)
+ send("_define_#{type}_model_callback", self, callback)
end
end
end
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index 1dfd0b6132..a479795d51 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -1,5 +1,4 @@
require 'active_model/attribute_methods'
-require 'active_support/concern'
require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/object/duplicable'
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index fdca852c7a..c2f0228785 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -60,9 +60,13 @@ module ActiveModel
# p.validate! # => ["can not be nil"]
# p.errors.full_messages # => ["name can not be nil"]
# # etc..
- class Errors < ActiveSupport::OrderedHash
+ class Errors
+ include Enumerable
+
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank]
+ attr_reader :messages
+
# Pass in the instance of the object that is using the errors object.
#
# class Person
@@ -71,12 +75,29 @@ module ActiveModel
# end
# end
def initialize(base)
- @base = base
- super()
+ @base = base
+ @messages = ActiveSupport::OrderedHash.new
+ end
+
+ # Clear the messages
+ def clear
+ messages.clear
+ end
+
+ # Do the error messages include an error with key +error+?
+ def include?(error)
+ messages.include? error
end
- alias_method :get, :[]
- alias_method :set, :[]=
+ # Get messages for +key+
+ def get(key)
+ messages[key]
+ end
+
+ # Set messages for +key+ to +value+
+ def set(key, value)
+ messages[key] = value
+ end
# When passed a symbol or a name of a method, returns an array of errors
# for the method.
@@ -110,7 +131,7 @@ module ActiveModel
# # then yield :name and "must be specified"
# end
def each
- each_key do |attribute|
+ messages.each_key do |attribute|
self[attribute].each { |error| yield attribute, error }
end
end
@@ -125,6 +146,16 @@ module ActiveModel
values.flatten.size
end
+ # Returns all message values
+ def values
+ messages.values
+ end
+
+ # Returns all message keys
+ def keys
+ messages.keys
+ end
+
# Returns an array of error messages, with the attribute name included
#
# p.errors.add(:name, "can't be blank")
@@ -147,7 +178,7 @@ module ActiveModel
def empty?
all? { |k, v| v && v.empty? }
end
-
+ alias_method :blank?, :empty?
# Returns an xml formatted representation of the Errors hash.
#
# p.errors.add(:name, "can't be blank")
@@ -169,9 +200,7 @@ module ActiveModel
end
def to_hash
- hash = ActiveSupport::OrderedHash.new
- each { |k, v| (hash[k] ||= []) << v }
- hash
+ messages.dup
end
# Adds +message+ to the error messages on +attribute+, which will be returned on a call to
@@ -221,26 +250,20 @@ module ActiveModel
# company.errors.full_messages # =>
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
def full_messages
- full_messages = []
-
- each do |attribute, messages|
- messages = Array.wrap(messages)
- next if messages.empty?
-
+ map { |attribute, message|
if attribute == :base
- messages.each {|m| full_messages << m }
+ message
else
attr_name = attribute.to_s.gsub('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
- options = { :default => "%{attribute} %{message}", :attribute => attr_name }
- messages.each do |m|
- full_messages << I18n.t(:"errors.format", options.merge(:message => m))
- end
+ I18n.t(:"errors.format", {
+ :default => "%{attribute} %{message}",
+ :attribute => attr_name,
+ :message => message
+ })
end
- end
-
- full_messages
+ }
end
# Translates an error message in its default scope
@@ -272,8 +295,8 @@ module ActiveModel
type = options.delete(:message) if options[:message].is_a?(Symbol)
defaults = @base.class.lookup_ancestors.map do |klass|
- [ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
- :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
+ [ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.underscore}.attributes.#{attribute}.#{type}",
+ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.underscore}.#{type}" ]
end
defaults << options.delete(:message)
diff --git a/activemodel/lib/active_model/mass_assignment_security.rb b/activemodel/lib/active_model/mass_assignment_security.rb
index 66cd9fdde6..97e31d4243 100644
--- a/activemodel/lib/active_model/mass_assignment_security.rb
+++ b/activemodel/lib/active_model/mass_assignment_security.rb
@@ -20,32 +20,32 @@ module ActiveModel
# For example, a logged in user may need to assign additional attributes depending
# on their role:
#
- # class AccountsController < ApplicationController
- # include ActiveModel::MassAssignmentSecurity
+ # class AccountsController < ApplicationController
+ # include ActiveModel::MassAssignmentSecurity
#
- # attr_accessible :first_name, :last_name
+ # attr_accessible :first_name, :last_name
#
- # def self.admin_accessible_attributes
- # accessible_attributes + [ :plan_id ]
- # end
+ # def self.admin_accessible_attributes
+ # accessible_attributes + [ :plan_id ]
+ # end
#
- # def update
- # ...
- # @account.update_attributes(account_params)
- # ...
- # end
+ # def update
+ # ...
+ # @account.update_attributes(account_params)
+ # ...
+ # end
#
- # protected
+ # protected
#
- # def account_params
- # sanitize_for_mass_assignment(params[:account])
- # end
+ # def account_params
+ # sanitize_for_mass_assignment(params[:account])
+ # end
#
- # def mass_assignment_authorizer
- # admin ? admin_accessible_attributes : super
- # end
+ # def mass_assignment_authorizer
+ # admin ? admin_accessible_attributes : super
+ # end
#
- # end
+ # end
#
module ClassMethods
# Attributes named in this macro are protected from mass-assignment
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index 44aedc8efd..eb9b847509 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -4,7 +4,7 @@ require 'active_support/core_ext/module/introspection'
module ActiveModel
class Name < String
- attr_reader :singular, :plural, :element, :collection, :partial_path, :route_key, :param_key, :i18n_key
+ attr_reader :singular, :plural, :element, :collection, :partial_path, :route_key, :param_key
alias_method :cache_key, :collection
def initialize(klass, namespace = nil)
@@ -20,7 +20,6 @@ module ActiveModel
@partial_path = "#{@collection}/#{@element}".freeze
@param_key = (namespace ? _singularize(@unnamespaced) : @singular).freeze
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural).freeze
- @i18n_key = _singularize(self, '.').to_sym
end
# Transform the model name into a more humane format, using I18n. By default,
@@ -34,7 +33,7 @@ module ActiveModel
@klass.respond_to?(:i18n_scope)
defaults = @klass.lookup_ancestors.map do |klass|
- klass.model_name.i18n_key
+ klass.model_name.underscore.to_sym
end
defaults << options[:default] if options[:default]
@@ -45,10 +44,9 @@ module ActiveModel
end
private
-
- def _singularize(string, replacement='_')
- ActiveSupport::Inflector.underscore(string).tr('/', replacement)
- end
+ def _singularize(str)
+ ActiveSupport::Inflector.underscore(str).tr('/', '_')
+ end
end
# == Active Model Naming
@@ -64,12 +62,9 @@ module ActiveModel
# BookCover.model_name # => "BookCover"
# BookCover.model_name.human # => "Book cover"
#
- # BookCover.model_name.i18n_key # => "book_cover"
- # BookModule::BookCover.model_name.i18n_key # => "book_module.book_cover"
- #
# Providing the functionality that ActiveModel::Naming provides in your object
# is required to pass the Active Model Lint test. So either extending the provided
- # method below, or rolling your own is required..
+ # method below, or rolling your own is required.
module Naming
# Returns an ActiveModel::Name object for module. It can be
# used to retrieve all kinds of naming-related information.
diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb
index 0d2dd36e59..af036b560e 100644
--- a/activemodel/lib/active_model/observing.rb
+++ b/activemodel/lib/active_model/observing.rb
@@ -13,14 +13,18 @@ module ActiveModel
#
# Activates the observers assigned. Examples:
#
+ # class ORM
+ # include ActiveModel::Observing
+ # end
+ #
# # Calls PersonObserver.instance
- # ActiveRecord::Base.observers = :person_observer
+ # ORM.observers = :person_observer
#
# # Calls Cacher.instance and GarbageCollector.instance
- # ActiveRecord::Base.observers = :cacher, :garbage_collector
+ # ORM.observers = :cacher, :garbage_collector
#
# # Same as above, just using explicit class references
- # ActiveRecord::Base.observers = Cacher, GarbageCollector
+ # ORM.observers = Cacher, GarbageCollector
#
# Note: Setting this does not instantiate the observers yet.
# +instantiate_observers+ is called during startup, and before
@@ -44,6 +48,7 @@ module ActiveModel
observers.each { |o| instantiate_observer(o) }
end
+ # Add a new observer to the pool.
def add_observer(observer)
unless observer.respond_to? :update
raise ArgumentError, "observer needs to respond to `update'"
@@ -51,12 +56,14 @@ module ActiveModel
observer_instances << observer
end
+ # Notify list of observers of a change.
def notify_observers(*arg)
for observer in observer_instances
observer.update(*arg)
end
end
+ # Total number of observers.
def count_observers
observer_instances.size
end
@@ -152,6 +159,10 @@ module ActiveModel
# The AuditObserver will now act on both updates to Account and Balance 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
+ # ActiveRecord::Observer.
+ #
class Observer
include Singleton
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
new file mode 100644
index 0000000000..957d0ddaaa
--- /dev/null
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -0,0 +1,66 @@
+require 'bcrypt'
+
+module ActiveModel
+ module SecurePassword
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ # 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, confirmation of password (using
+ # a "password_confirmation" attribute) are automatically added.
+ # You can add more validations by hand if need be.
+ #
+ # Example using Active Record (which automatically includes ActiveModel::SecurePassword):
+ #
+ # # Schema: User(name:string, password_digest: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
+ def has_secure_password
+ attr_reader :password
+ attr_accessor :password_confirmation
+
+ validates_confirmation_of :password
+ validates_presence_of :password_digest
+
+ include InstanceMethodsOnActivation
+
+ if respond_to?(:attributes_protected_by_default)
+ def self.attributes_protected_by_default
+ super + ['password_digest']
+ end
+ end
+ end
+ end
+
+ module InstanceMethodsOnActivation
+ # Returns self if the password is correct, otherwise false.
+ def authenticate(unencrypted_password)
+ if BCrypt::Password.new(password_digest) == unencrypted_password
+ self
+ else
+ false
+ end
+ end
+
+ # Encrypts the password into the password_digest attribute.
+ def password=(unencrypted_password)
+ @password = unencrypted_password
+ self.password_digest = BCrypt::Password.create(unencrypted_password)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index 37739b98a1..caf44a2ee0 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -15,7 +15,7 @@ module ActiveModel
# attr_accessor :name
#
# def attributes
- # @attributes ||= {'name' => 'nil'}
+ # {'name' => name}
# end
#
# end
@@ -45,7 +45,7 @@ module ActiveModel
# attr_accessor :name
#
# def attributes
- # @attributes ||= {'name' => 'nil'}
+ # {'name' => name}
# end
#
# end
diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb
index b897baa614..d4295e6afe 100644
--- a/activemodel/lib/active_model/serializers/xml.rb
+++ b/activemodel/lib/active_model/serializers/xml.rb
@@ -134,6 +134,29 @@ 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:
+ #
+ # konata = User.find(1)
+ # konata.to_xml
+ #
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <user>
+ # <id type="integer">1</id>
+ # <name>David</name>
+ # <age type="integer">16</age>
+ # <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.
+ #
+ # 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.
def to_xml(options = {}, &block)
Serializer.new(self, options).serialize(&block)
end
diff --git a/activemodel/lib/active_model/translation.rb b/activemodel/lib/active_model/translation.rb
index 920a133159..dbb76244e4 100644
--- a/activemodel/lib/active_model/translation.rb
+++ b/activemodel/lib/active_model/translation.rb
@@ -44,7 +44,7 @@ module ActiveModel
# Specify +options+ with additional translating options.
def human_attribute_name(attribute, options = {})
defaults = lookup_ancestors.map do |klass|
- :"#{self.i18n_scope}.attributes.#{klass.model_name.i18n_key}.#{attribute}"
+ :"#{self.i18n_scope}.attributes.#{klass.model_name.underscore}.#{attribute}"
end
defaults << :"attributes.#{attribute}"
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index b044caa8d3..98af88b5a0 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -71,8 +71,8 @@ module ActiveModel
# end
#
# Options:
- # * <tt>:on</tt> - Specifies when this validation is active (default is
- # <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies the context where this validation is active
+ # (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
@@ -104,7 +104,7 @@ module ActiveModel
# end
# end
#
- # Or with a block which is passed with the current record to be validated:
+ # With a block which is passed with the current record to be validated:
#
# class Comment
# include ActiveModel::Validations
@@ -118,6 +118,16 @@ module ActiveModel
# end
# end
#
+ # Or with a block where self points to the current record to be validated:
+ #
+ # class Comment
+ # include ActiveModel::Validations
+ #
+ # validate do
+ # errors.add(:base, "Must be friends to leave a comment") unless commenter.friend_of?(commentee)
+ # end
+ # end
+ #
def validate(*args, &block)
options = args.extract_options!
if options.key?(:on)
@@ -136,8 +146,10 @@ module ActiveModel
end
# List all validators that being used to validate a specific attribute.
- def validators_on(attribute)
- _validators[attribute.to_sym]
+ def validators_on(*attributes)
+ attributes.map do |attribute|
+ _validators[attribute.to_sym]
+ end.flatten
end
# Check if method is an attribute method or not.
@@ -197,7 +209,7 @@ module ActiveModel
protected
def run_validations!
- _run_validate_callbacks
+ run_callbacks :validate
errors.empty?
end
end
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index a7296d8e1d..4f390613aa 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -37,9 +37,9 @@ 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 (default is
- # <tt>:save</tt>, other options are <tt>:create</tt> and
- # <tt>:update</tt>).
+ # * <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).
# * <tt>:accept</tt> - Specifies value that is considered accepted.
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
index 621518de5b..adc2867ad0 100644
--- a/activemodel/lib/active_model/validations/callbacks.rb
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -50,7 +50,7 @@ module ActiveModel
# Overwrite run validations to include callbacks.
def run_validations!
- _run_validation_callbacks { super }
+ run_callbacks(:validation) { super }
end
end
end
diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb
index 00df10cef0..e6d10cfff8 100644
--- a/activemodel/lib/active_model/validations/confirmation.rb
+++ b/activemodel/lib/active_model/validations/confirmation.rb
@@ -45,8 +45,9 @@ module ActiveModel
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
# confirmation").
- # * <tt>:on</tt> - Specifies when this validation is active (default is
- # <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <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
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index 4138892786..e38e565d09 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -29,6 +29,9 @@ module ActiveModel
# * <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_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.
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index 104f403492..541f53a834 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -51,7 +51,9 @@ module ActiveModel
# * <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.
# * <tt>:without</tt> - Regular expression that if the attribute does not match will result in a successful validation.
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <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.
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 049b093618..92ac940f36 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/range.rb'
+
module ActiveModel
# == Active Model Inclusion Validator
@@ -9,9 +11,14 @@ module ActiveModel
end
def validate_each(record, attribute, value)
- unless options[:in].include?(value)
- record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value))
- end
+ record.errors.add(attribute, :inclusion, options.except(:in).merge!(:value => value)) unless options[:in].send(include?, value)
+ 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.
+ def include?
+ options[:in].is_a?(Range) ? :cover? : :include?
end
end
@@ -26,9 +33,14 @@ module ActiveModel
#
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items.
+ # If the enumerable is a range the test is performed with <tt>Range#cover?</tt>
+ # (backported in Active Support for 1.8), 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 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.
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index 5a46ecb4ac..7af6c83460 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -83,7 +83,9 @@ module ActiveModel
# * <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>: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 (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <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.
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 95fe20de75..ae576462e6 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -93,7 +93,9 @@ module ActiveModel
#
# 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 <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <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>: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.
diff --git a/activemodel/lib/active_model/validations/presence.rb b/activemodel/lib/active_model/validations/presence.rb
index 28c4640b17..cfb4c33dcc 100644
--- a/activemodel/lib/active_model/validations/presence.rb
+++ b/activemodel/lib/active_model/validations/presence.rb
@@ -26,8 +26,9 @@ module ActiveModel
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "can't be blank").
- # * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>,
- # <tt>:update</tt>).
+ # * <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.
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
index 77c5073c6e..7ff42de00b 100644
--- a/activemodel/lib/active_model/validations/validates.rb
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -55,6 +55,10 @@ module ActiveModel
# validates :name, :title => true
# end
#
+ # Additionally validator classes may be in another namespace and still used within any class.
+ #
+ # validates :name, :'file/title' => true
+ #
# The validators hash can also handle regular expressions, ranges,
# arrays and strings in shortcut form, e.g.
#
@@ -77,17 +81,18 @@ module ActiveModel
#
def validates(*attributes)
defaults = attributes.extract_options!
- validations = defaults.slice!(:if, :unless, :on, :allow_blank, :allow_nil)
+ validations = defaults.slice!(*_validates_default_keys)
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
- raise ArgumentError, "Attribute names must be symbols" if attributes.any?{ |attribute| !attribute.is_a?(Symbol) }
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
defaults.merge!(:attributes => attributes)
validations.each do |key, options|
+ key = "#{key.to_s.camelize}Validator"
+
begin
- validator = const_get("#{key.to_s.camelize}Validator")
+ validator = key.include?('::') ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end
@@ -98,6 +103,12 @@ module ActiveModel
protected
+ # 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
+ [ :if, :unless, :on, :allow_blank, :allow_nil ]
+ end
+
def _parse_validates_options(options) #:nodoc:
case options
when TrueClass
@@ -112,4 +123,4 @@ module ActiveModel
end
end
end
-end \ No newline at end of file
+end
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index 200efd4eb5..1663697727 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -8,6 +8,18 @@ module ActiveModel
end
end
+ class WithValidator < EachValidator
+ def validate_each(record, attr, val)
+ method_name = options[:with]
+
+ if record.method(method_name).arity == 0
+ record.send method_name
+ else
+ record.send method_name, attr
+ end
+ end
+ end
+
module ClassMethods
# Passes the record off to the class or classes specified and allows them
# to add errors based on more complex conditions.
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
index 54cf8380ab..b001adb35a 100644
--- a/activemodel/test/cases/attribute_methods_test.rb
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -21,25 +21,59 @@ class ModelWithAttributes2
attribute_method_suffix '_test'
end
+class ModelWithAttributesWithSpaces
+ include ActiveModel::AttributeMethods
+
+ attribute_method_suffix ''
+
+ def attributes
+ { :'foo bar' => 'value of foo bar'}
+ end
+
+private
+ def attribute(name)
+ attributes[name.to_sym]
+ end
+end
+
class AttributeMethodsTest < ActiveModel::TestCase
test 'unrelated classes should not share attribute method matchers' do
assert_not_equal ModelWithAttributes.send(:attribute_method_matchers),
ModelWithAttributes2.send(:attribute_method_matchers)
end
+ test '#define_attribute_method generates attribute method' do
+ ModelWithAttributes.define_attribute_method(:foo)
+
+ assert_respond_to ModelWithAttributes.new, :foo
+ assert_equal "value of foo", ModelWithAttributes.new.foo
+ end
+
test '#define_attribute_methods generates attribute methods' do
ModelWithAttributes.define_attribute_methods([:foo])
- assert ModelWithAttributes.attribute_methods_generated?
assert_respond_to ModelWithAttributes.new, :foo
assert_equal "value of foo", ModelWithAttributes.new.foo
end
+ test '#define_attribute_methods generates attribute methods with spaces in their names' do
+ ModelWithAttributesWithSpaces.define_attribute_methods([:'foo bar'])
+
+ assert_respond_to ModelWithAttributesWithSpaces.new, :'foo bar'
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.send(:'foo bar')
+ end
+
+ test '#alias_attribute works with attributes with spaces in their names' do
+ ModelWithAttributesWithSpaces.define_attribute_methods([:'foo bar'])
+ ModelWithAttributesWithSpaces.alias_attribute(:'foo_bar', :'foo bar')
+
+ assert_equal "value of foo bar", ModelWithAttributesWithSpaces.new.foo_bar
+ end
+
test '#undefine_attribute_methods removes attribute methods' do
ModelWithAttributes.define_attribute_methods([:foo])
ModelWithAttributes.undefine_attribute_methods
- assert !ModelWithAttributes.attribute_methods_generated?
assert !ModelWithAttributes.new.respond_to?(:foo)
assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
end
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
index 069d907fb2..086e7266ff 100644
--- a/activemodel/test/cases/callbacks_test.rb
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -37,7 +37,7 @@ class CallbacksTest < ActiveModel::TestCase
end
def create
- _run_create_callbacks do
+ run_callbacks :create do
@callbacks << :create
@valid
end
@@ -92,7 +92,7 @@ class CallbacksTest < ActiveModel::TestCase
def callback1; self.history << 'callback1'; end
def callback2; self.history << 'callback2'; end
def create
- _run_create_callbacks {}
+ run_callbacks(:create) {}
self
end
end
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index 27821c333b..a24cac40ad 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -25,7 +25,19 @@ class ErrorsTest < ActiveModel::TestCase
def self.lookup_ancestors
[self]
end
+ end
+
+ def test_include?
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ assert errors.include?(:foo), 'errors should include :foo'
+ end
+ test "should return true if no errors" do
+ person = Person.new
+ person.errors[:foo]
+ assert person.errors.empty?
+ assert person.errors.blank?
end
test "method validate! should work" do
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
new file mode 100644
index 0000000000..4a47a7a226
--- /dev/null
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -0,0 +1,45 @@
+require 'cases/helper'
+require 'models/user'
+require 'models/visitor'
+require 'models/administrator'
+
+class SecurePasswordTest < ActiveModel::TestCase
+
+ setup do
+ @user = User.new
+ end
+
+ test "password must be present" do
+ assert !@user.valid?
+ assert_equal 1, @user.errors.size
+ end
+
+ test "password must match confirmation" do
+ @user.password = "thiswillberight"
+ @user.password_confirmation = "wrong"
+
+ assert !@user.valid?
+
+ @user.password_confirmation = "thiswillberight"
+
+ assert @user.valid?
+ end
+
+ test "authenticate" do
+ @user.password = "secret"
+
+ assert !@user.authenticate("wrong")
+ assert @user.authenticate("secret")
+ end
+
+ test "visitor#password_digest should be protected against mass assignment" do
+ assert Visitor.active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::BlackList)
+ assert Visitor.active_authorizer.include?(:password_digest)
+ end
+
+ test "Administrator's mass_assignment_authorizer should be WhiteList" do
+ assert Administrator.active_authorizer.kind_of?(ActiveModel::MassAssignmentSecurity::WhiteList)
+ assert !Administrator.active_authorizer.include?(:password_digest)
+ assert Administrator.active_authorizer.include?(:name)
+ end
+end
diff --git a/activemodel/test/cases/serializeration/xml_serialization_test.rb b/activemodel/test/cases/serializeration/xml_serialization_test.rb
index cc19d322b3..b6a2f88667 100644
--- a/activemodel/test/cases/serializeration/xml_serialization_test.rb
+++ b/activemodel/test/cases/serializeration/xml_serialization_test.rb
@@ -114,7 +114,7 @@ class XmlSerializationTest < ActiveModel::TestCase
end
test "should serialize yaml" do
- assert_match %r{<preferences type=\"yaml\">--- !ruby/struct:Customer \nname: John\n</preferences>}, @contact.to_xml
+ assert_match %r{<preferences type=\"yaml\">--- !ruby/struct:Customer(\s*)\nname: John\n</preferences>}, @contact.to_xml
end
test "should call proc on object" do
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
index c299d6eb5e..1b1d972d5c 100644
--- a/activemodel/test/cases/translation_test.rb
+++ b/activemodel/test/cases/translation_test.rb
@@ -49,6 +49,13 @@ class ActiveModelI18nTests < ActiveModel::TestCase
assert_equal 'person name attribute', Child.human_attribute_name('name')
end
+ def test_translated_model_attributes_with_attribute_matching_namespaced_model_name
+ I18n.backend.store_translations 'en', :activemodel => {:attributes => {:person => {:gender => 'person gender'}, :"person/gender" => {:attribute => 'person gender attribute'}}}
+
+ assert_equal 'person gender', Person.human_attribute_name('gender')
+ assert_equal 'person gender attribute', Person::Gender.human_attribute_name('attribute')
+ end
+
def test_translated_model_names
I18n.backend.store_translations 'en', :activemodel => {:models => {:person => 'person model'} }
assert_equal 'person model', Person.model_name.human
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index 5cb7bff4e7..e9f0e430fe 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -55,14 +55,6 @@ class I18nValidationTest < ActiveModel::TestCase
assert_equal ["Person's name not found"], @person.errors.full_messages
end
- def test_errors_full_messages_translates_human_attribute_name_for_model_in_module_attributes
- I18n.backend.store_translations('en', :activemodel => {:attributes => {:person_module => {:person => {:name => "Person in Module's name"}}}})
- person = PersonModule::Person.new
- person.errors.add(:name, 'not found')
- PersonModule::Person.expects(:human_attribute_name).with(:name, :default => 'Name').returns("Person in Module's name")
- assert_equal ["Person in Module's name not found"], person.errors.full_messages
- end
-
def test_errors_full_messages_uses_format
I18n.backend.store_translations('en', :errors => {:format => "Field %{attribute} %{message}"})
@person.errors.add('name', 'empty')
@@ -371,15 +363,4 @@ class I18nValidationTest < ActiveModel::TestCase
assert_equal ["I am a custom error"], @person.errors[:title]
end
- def test_model_with_module_i18n_scope
- I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person_module => {:person => {:blank => 'generic blank'}}}}}
- PersonModule::Person.validates_presence_of :title
- person = PersonModule::Person.new
- person.valid?
- assert_equal ['generic blank'], person.errors[:title]
-
- I18n.backend.store_translations 'en', :activemodel => {:errors => {:models => {:person_module => {:person => {:attributes => {:title => {:blank => 'title cannot be blank'}}}}}}}
- person.valid?
- assert_equal ['title cannot be blank'], person.errors[:title]
- end
end
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 0716b4f087..62f2ec785d 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -10,6 +10,15 @@ class InclusionValidationTest < ActiveModel::TestCase
Topic.reset_callbacks(:validate)
end
+ def test_validates_inclusion_of_range
+ Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' )
+ assert Topic.new("title" => "bbc", "content" => "abc").invalid?
+ assert Topic.new("title" => "aa", "content" => "abc").invalid?
+ assert Topic.new("title" => "aaa", "content" => "abc").valid?
+ assert Topic.new("title" => "abc", "content" => "abc").valid?
+ assert Topic.new("title" => "bbb", "content" => "abc").valid?
+ end
+
def test_validates_inclusion_of
Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb
index 666c48c8a0..779f6c8448 100644
--- a/activemodel/test/cases/validations/validates_test.rb
+++ b/activemodel/test/cases/validations/validates_test.rb
@@ -1,8 +1,10 @@
# encoding: utf-8
require 'cases/helper'
require 'models/person'
+require 'models/topic'
require 'models/person_with_validator'
require 'validators/email_validator'
+require 'validators/namespace/email_validator'
class ValidatesTest < ActiveModel::TestCase
setup :reset_callbacks
@@ -10,6 +12,7 @@ class ValidatesTest < ActiveModel::TestCase
def reset_callbacks
Person.reset_callbacks(:validate)
+ Topic.reset_callbacks(:validate)
PersonWithValidator.reset_callbacks(:validate)
end
@@ -20,6 +23,17 @@ class ValidatesTest < ActiveModel::TestCase
assert_equal ['is not a number'], person.errors[:title]
end
+ def test_validates_with_attribute_specified_as_string
+ Person.validates "title", :numericality => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not a number'], person.errors[:title]
+
+ person = Person.new
+ person.title = 123
+ assert person.valid?
+ end
+
def test_validates_with_built_in_validation_and_options
Person.validates :salary, :numericality => { :message => 'my custom message' }
person = Person.new
@@ -34,6 +48,13 @@ class ValidatesTest < ActiveModel::TestCase
assert_equal ['is not an email'], person.errors[:karma]
end
+ def test_validates_with_namespaced_validator_class
+ Person.validates :karma, :'namespace/email' => true
+ person = Person.new
+ person.valid?
+ assert_equal ['is not an email'], person.errors[:karma]
+ end
+
def test_validates_with_if_as_local_conditions
Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true }
person = Person.new
@@ -120,4 +141,13 @@ class ValidatesTest < ActiveModel::TestCase
person.valid?
assert_equal ['does not appear to be like Mr.'], person.errors[:title]
end
+
+ def test_defining_extra_default_keys_for_validates
+ Topic.validates :title, :confirmation => true, :message => 'Y U NO CONFIRM'
+ topic = Topic.new
+ topic.title = "What's happening"
+ topic.title_confirmation = "Not this"
+ assert !topic.valid?
+ assert_equal ['Y U NO CONFIRM'], topic.errors[:title]
+ end
end
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 6d825cd316..07c1bd0533 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -171,4 +171,25 @@ class ValidatesWithTest < ActiveModel::TestCase
assert topic.errors[:title].empty?
assert topic.errors[:content].empty?
end
+
+ test "validates_with can validate with an instance method" do
+ Topic.validates :title, :with => :my_validation
+
+ topic = Topic.new :title => "foo"
+ assert topic.valid?
+ assert topic.errors[:title].empty?
+
+ topic = Topic.new
+ assert !topic.valid?
+ assert_equal ['is missing'], topic.errors[:title]
+ end
+
+ test "optionally pass in the attribute being validated when validating with an instance method" do
+ Topic.validates :title, :content, :with => :my_validation_with_arg
+
+ topic = Topic.new :title => "foo"
+ assert !topic.valid?
+ assert topic.errors[:title].empty?
+ assert_equal ['is missing'], topic.errors[:content]
+ end
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 55b477dd10..2f36195627 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -148,6 +148,14 @@ class ValidationsTest < ActiveModel::TestCase
end
def test_validate_block
+ Topic.validate { errors.add("title", "will never be valid") }
+ t = Topic.new("title" => "Title", "content" => "whatever")
+ assert t.invalid?
+ assert t.errors[:title].any?
+ assert_equal ["will never be valid"], t.errors["title"]
+ end
+
+ def test_validate_block_with_params
Topic.validate { |topic| topic.errors.add("title", "will never be valid") }
t = Topic.new("title" => "Title", "content" => "whatever")
assert t.invalid?
@@ -187,7 +195,7 @@ class ValidationsTest < ActiveModel::TestCase
assert t.invalid?
assert_equal "can't be blank", t.errors["title"].first
Topic.validates_presence_of :title, :author_name
- Topic.validate {|topic| topic.errors.add('author_email_address', 'will never be valid')}
+ Topic.validate {errors.add('author_email_address', 'will never be valid')}
Topic.validates_length_of :title, :content, :minimum => 2
t = Topic.new :title => ''
@@ -246,6 +254,24 @@ class ValidationsTest < ActiveModel::TestCase
assert_equal 10, Topic.validators_on(:title).first.options[:minimum]
end
+ def test_list_of_validators_on_multiple_attributes
+ Topic.validates :title, :length => { :minimum => 10 }
+ Topic.validates :author_name, :presence => true, :format => /a/
+
+ validators = Topic.validators_on(:title, :author_name)
+
+ assert_equal [
+ ActiveModel::Validations::FormatValidator,
+ ActiveModel::Validations::LengthValidator,
+ ActiveModel::Validations::PresenceValidator
+ ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ end
+
+ def test_list_of_validators_will_be_empty_when_empty
+ Topic.validates :title, :length => { :minimum => 10 }
+ assert_equal [], Topic.validators_on(:author_name)
+ end
+
def test_validations_on_the_instance_level
auto = Automobile.new
diff --git a/activemodel/test/models/administrator.rb b/activemodel/test/models/administrator.rb
new file mode 100644
index 0000000000..a48f8b064f
--- /dev/null
+++ b/activemodel/test/models/administrator.rb
@@ -0,0 +1,10 @@
+class Administrator
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+ include ActiveModel::MassAssignmentSecurity
+
+ attr_accessor :name, :password_digest
+ attr_accessible :name
+
+ has_secure_password
+end
diff --git a/activemodel/test/models/person.rb b/activemodel/test/models/person.rb
index eb84f7a27d..e896e90f98 100644
--- a/activemodel/test/models/person.rb
+++ b/activemodel/test/models/person.rb
@@ -9,10 +9,9 @@ class Person
end
end
-class Child < Person
+class Person::Gender
+ extend ActiveModel::Translation
end
-module PersonModule
- class Person < ::Person
- end
+class Child < Person
end
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
index ff34565bdb..c9af78f595 100644
--- a/activemodel/test/models/topic.rb
+++ b/activemodel/test/models/topic.rb
@@ -2,6 +2,10 @@ class Topic
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
+ def self._validates_default_keys
+ super | [ :message ]
+ end
+
attr_accessor :title, :author_name, :content, :approved
attr_accessor :after_validation_performed
@@ -25,4 +29,12 @@ class Topic
self.after_validation_performed = true
end
+ def my_validation
+ errors.add :title, "is missing" unless title
+ end
+
+ def my_validation_with_arg(attr)
+ errors.add attr, "is missing" unless send(attr)
+ end
+
end
diff --git a/activemodel/test/models/user.rb b/activemodel/test/models/user.rb
new file mode 100644
index 0000000000..e221bb8091
--- /dev/null
+++ b/activemodel/test/models/user.rb
@@ -0,0 +1,8 @@
+class User
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+
+ has_secure_password
+
+ attr_accessor :password_digest, :password_salt
+end
diff --git a/activemodel/test/models/visitor.rb b/activemodel/test/models/visitor.rb
new file mode 100644
index 0000000000..36c0a16688
--- /dev/null
+++ b/activemodel/test/models/visitor.rb
@@ -0,0 +1,9 @@
+class Visitor
+ include ActiveModel::Validations
+ include ActiveModel::SecurePassword
+ include ActiveModel::MassAssignmentSecurity
+
+ has_secure_password
+
+ attr_accessor :password_digest
+end
diff --git a/activemodel/test/validators/namespace/email_validator.rb b/activemodel/test/validators/namespace/email_validator.rb
new file mode 100644
index 0000000000..57e2793ce2
--- /dev/null
+++ b/activemodel/test/validators/namespace/email_validator.rb
@@ -0,0 +1,6 @@
+require 'validators/email_validator'
+
+module Namespace
+ class EmailValidator < ::EmailValidator
+ end
+end
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index 2d9f4da79e..3a63c08b2d 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,8 +1,172 @@
*Rails 3.1.0 (unreleased)*
* 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 #1812 [Jon Leighton]
+ through or source association, including other associations which have a
+ :through option and has_and_belongs_to_many associations
+
+ [Jon Leighton]
+
+* 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'
+
+ [lighthouse #6262]
+
+* 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.
+
+ This prevents namespace pollution, separates concerns, and will allow further refactorings.
+
+ 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.
+
+ [Jon Leighton]
+
+* 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:
+
+ class Post < ActiveRecord::Base
+ has_many :taggings
+ has_many :tags, :through => :taggings
+ end
+
+ 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
+
+ post = Post.first
+ tag = post.tags.build :name => "ruby"
+ tag.save # will save a Taggable linking to the post
+
+ [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.
+
+ [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.
+
+ 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.
+
+ If you wish to destroy the records themselves, you can do records.association.each(&:destroy)
+
+ [Jon Leighton]
+
+* 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:
+
+ change_table(:users, :bulk => true) do |t|
+ t.string :company_name
+ t.change :birthdate, :datetime
+ end
+
+ This will now result in:
+
+ ALTER TABLE `users` ADD COLUMN `company_name` varchar(255), CHANGE `updated_at` `updated_at` datetime DEFAULT NULL
+
+* 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]
+<<<<<<< Updated upstream
+>>>>>>> association_fixes
+=======
+>>>>>>> Stashed changes
* Setting the id of a belongs_to object will update the reference to the
object. [#2989 state:resolved]
@@ -63,7 +227,15 @@ IrreversibleMigration exception will be raised when going down.
[Aaron Patterson]
-*Rails 3.0.2 (unreleased)*
+
+*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]
diff --git a/activerecord/MIT-LICENSE b/activerecord/MIT-LICENSE
index 86bcb23b7c..c73d1af096 100644
--- a/activerecord/MIT-LICENSE
+++ b/activerecord/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
index 101a595ecd..91a23da8ad 100644
--- a/activerecord/README.rdoc
+++ b/activerecord/README.rdoc
@@ -84,7 +84,7 @@ A short rundown of some of the major features:
class CommentObserver < ActiveRecord::Observer
def after_create(comment) # is called just after Comment#save
- Notifications.deliver_new_comment("david@loudthinking.com", comment)
+ CommentMailer.new_comment_email("david@loudthinking.com", comment)
end
end
@@ -128,7 +128,7 @@ A short rundown of some of the major features:
# connect to MySQL with authentication
ActiveRecord::Base.establish_connection(
- :adapter => "mysql",
+ :adapter => "mysql2",
:host => "localhost",
:username => "me",
:password => "secret",
diff --git a/activerecord/RUNNING_UNIT_TESTS b/activerecord/RUNNING_UNIT_TESTS
index 18e3936d8a..b3d376772e 100644
--- a/activerecord/RUNNING_UNIT_TESTS
+++ b/activerecord/RUNNING_UNIT_TESTS
@@ -1,8 +1,8 @@
== Creating the test database
The default names for the test databases are "activerecord_unittest" and
-"activerecord_unittest2". If you want to use another database name then be sure
-to update the connection adapter setups you want to test with in
+"activerecord_unittest2". If you want to use another database name, then be sure
+to update the connection adapter setups you want to test within
test/connections/<your database>/connection.rb.
When you have the database online, you can import the fixture tables with
the test/schema/*.sql files.
@@ -32,7 +32,7 @@ being initialized - you can initialize the schema with:
rake test_mysql TEST=test/cases/aaa_create_tables_test.rb
rake mysql:build_databases
-
+
To setup the testing environment for PostgreSQL use this command:
rake postgresql:build_databases
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index f9b77c1799..e414c4fb1c 100755
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -41,7 +41,7 @@ namespace :test do
end
end
-%w( mysql mysql2 postgresql sqlite3 firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
+%w( mysql mysql2 postgresql sqlite3 sqlite3_mem firebird db2 oracle sybase openbase frontbase jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
Rake::TestTask.new("test_#{adapter}") { |t|
connection_path = "test/connections/#{adapter =~ /jdbc/ ? 'jdbc' : 'native'}_#{adapter}"
adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/]
@@ -62,7 +62,7 @@ end
(Dir["test/cases/**/*_test.rb"].reject {
|x| x =~ /\/adapters\//
} + Dir["test/cases/adapters/#{adapter_short}/**/*_test.rb"]).all? do |file|
- system(ruby, "-Ilib:test:#{connection_path}", file)
+ sh(ruby, "-Ilib:test:#{connection_path}", file)
end or raise "Failures"
end
@@ -72,6 +72,15 @@ end
end
end
+rule '.sqlite3' do |t|
+ sh %Q{sqlite3 "#{t.name}" "create table a (a integer); drop table a;"}
+end
+
+task :test_sqlite3 => [
+ 'test/fixtures/fixture_database.sqlite3',
+ 'test/fixtures/fixture_database_2.sqlite3'
+]
+
namespace :mysql do
desc 'Build the MySQL test databases'
task :build_databases do
diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb
index c4ce361b5d..63822731d5 100644
--- a/activerecord/examples/performance.rb
+++ b/activerecord/examples/performance.rb
@@ -1,31 +1,9 @@
-#!/usr/bin/env ruby -KU
-
TIMES = (ENV['N'] || 10000).to_i
-require 'rubygems'
-
-gem 'addressable', '~>2.0'
-gem 'faker', '~>0.3.1'
-gem 'rbench', '~>0.2.3'
-require 'addressable/uri'
-require 'faker'
-require 'rbench'
-
-require File.expand_path("../../../load_paths", __FILE__)
+require 'rubygems'
require "active_record"
-conn = { :adapter => 'mysql',
- :database => 'activerecord_unittest',
- :username => 'rails', :password => '',
- :encoding => 'utf8' }
-
-conn[:socket] = Pathname.glob(%w[
- /opt/local/var/run/mysql5/mysqld.sock
- /tmp/mysqld.sock
- /tmp/mysql.sock
- /var/mysql/mysql.sock
- /var/run/mysqld/mysqld.sock
-]).find { |path| path.socket? }.to_s
+conn = { :adapter => 'sqlite3', :database => ':memory:' }
ActiveRecord::Base.establish_connection(conn)
@@ -55,125 +33,126 @@ class Exhibit < ActiveRecord::Base
def self.feel(exhibits) exhibits.each { |e| e.feel } end
end
-sqlfile = File.expand_path("../performance.sql", __FILE__)
-
-if File.exists?(sqlfile)
- mysql_bin = %w[mysql mysql5].detect { |bin| `which #{bin}`.length > 0 }
- `#{mysql_bin} -u #{conn[:username]} #{"-p#{conn[:password]}" unless conn[:password].blank?} #{conn[:database]} < #{sqlfile}`
-else
- puts 'Generating data...'
-
- # pre-compute the insert statements and fake data compilation,
- # so the benchmarks below show the actual runtime for the execute
- # method, minus the setup steps
-
- # Using the same paragraph for all exhibits because it is very slow
- # to generate unique paragraphs for all exhibits.
- notes = Faker::Lorem.paragraphs.join($/)
- today = Date.today
-
- puts 'Inserting 10,000 users and exhibits...'
- 10_000.times do
- user = User.create(
- :created_at => today,
- :name => Faker::Name.name,
- :email => Faker::Internet.email
- )
-
- Exhibit.create(
- :created_at => today,
- :name => Faker::Company.name,
- :user => user,
- :notes => notes
- )
- end
-
- mysqldump_bin = %w[mysqldump mysqldump5].detect { |bin| `which #{bin}`.length > 0 }
- `#{mysqldump_bin} -u #{conn[:username]} #{"-p#{conn[:password]}" unless conn[:password].blank?} #{conn[:database]} exhibits users > #{sqlfile}`
+puts 'Generating data...'
+
+module ActiveRecord
+ class Faker
+ LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. Praesent varius tincidunt commodo".split
+ def self.name
+ LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join ' '
+ end
+
+ def self.email
+ LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join('@') + ".com"
+ end
+ end
+end
+
+# pre-compute the insert statements and fake data compilation,
+# so the benchmarks below show the actual runtime for the execute
+# method, minus the setup steps
+
+# Using the same paragraph for all exhibits because it is very slow
+# to generate unique paragraphs for all exhibits.
+notes = ActiveRecord::Faker::LOREM.join ' '
+today = Date.today
+
+puts 'Inserting 10,000 users and exhibits...'
+10_000.times do
+ user = User.create(
+ :created_at => today,
+ :name => ActiveRecord::Faker.name,
+ :email => ActiveRecord::Faker.email
+ )
+
+ Exhibit.create(
+ :created_at => today,
+ :name => ActiveRecord::Faker.name,
+ :user => user,
+ :notes => notes
+ )
end
-RBench.run(TIMES) do
- column :times
- column :ar
+require 'benchmark'
- report 'Model#id', (TIMES * 100).ceil do
- ar_obj = Exhibit.find(1)
+Benchmark.bm(46) do |x|
+ ar_obj = Exhibit.find(1)
+ attrs = { :name => 'sam' }
+ attrs_first = { :name => 'sam' }
+ attrs_second = { :name => 'tom' }
+ exhibit = {
+ :name => ActiveRecord::Faker.name,
+ :notes => notes,
+ :created_at => Date.today
+ }
- ar { ar_obj.id }
+ x.report("Model#id (x#{(TIMES * 100).ceil})") do
+ (TIMES * 100).ceil.times { ar_obj.id }
end
- report 'Model.new (instantiation)' do
- ar { Exhibit.new }
+ x.report 'Model.new (instantiation)' do
+ TIMES.times { Exhibit.new }
end
- report 'Model.new (setting attributes)' do
- attrs = { :name => 'sam' }
- ar { Exhibit.new(attrs) }
+ x.report 'Model.new (setting attributes)' do
+ TIMES.times { Exhibit.new(attrs) }
end
- report 'Model.first' do
- ar { Exhibit.first.look }
+ x.report 'Model.first' do
+ TIMES.times { Exhibit.first.look }
end
- report 'Model.all limit(100)', (TIMES / 10).ceil do
- ar { Exhibit.look Exhibit.limit(100) }
+ x.report("Model.all limit(100) (x#{(TIMES / 10).ceil})") do
+ (TIMES / 10).ceil.times { Exhibit.look Exhibit.limit(100) }
end
- report 'Model.all limit(100) with relationship', (TIMES / 10).ceil do
- ar { Exhibit.feel Exhibit.limit(100).includes(:user) }
+ x.report "Model.all limit(100) with relationship (x#{(TIMES / 10).ceil})" do
+ (TIMES / 10).ceil.times { Exhibit.feel Exhibit.limit(100).includes(:user) }
end
- report 'Model.all limit(10,000)', (TIMES / 1000).ceil do
- ar { Exhibit.look Exhibit.limit(10000) }
+ x.report "Model.all limit(10,000) x(#{(TIMES / 1000).ceil})" do
+ (TIMES / 1000).ceil.times { Exhibit.look Exhibit.limit(10000) }
end
- exhibit = {
- :name => Faker::Company.name,
- :notes => Faker::Lorem.paragraphs.join($/),
- :created_at => Date.today
- }
-
- report 'Model.create' do
- ar { Exhibit.create(exhibit) }
+ x.report 'Model.create' do
+ TIMES.times { Exhibit.create(exhibit) }
end
- report 'Resource#attributes=' do
- attrs_first = { :name => 'sam' }
- attrs_second = { :name => 'tom' }
- ar { exhibit = Exhibit.new(attrs_first); exhibit.attributes = attrs_second }
+ x.report 'Resource#attributes=' do
+ TIMES.times {
+ exhibit = Exhibit.new(attrs_first)
+ exhibit.attributes = attrs_second
+ }
end
- report 'Resource#update' do
- ar { Exhibit.first.update_attributes(:name => 'bob') }
+ x.report 'Resource#update' do
+ TIMES.times { Exhibit.first.update_attributes(:name => 'bob') }
end
- report 'Resource#destroy' do
- ar { Exhibit.first.destroy }
+ x.report 'Resource#destroy' do
+ TIMES.times { Exhibit.first.destroy }
end
- report 'Model.transaction' do
- ar { Exhibit.transaction { Exhibit.new } }
+ x.report 'Model.transaction' do
+ TIMES.times { Exhibit.transaction { Exhibit.new } }
end
- report 'Model.find(id)' do
+ x.report 'Model.find(id)' do
id = Exhibit.first.id
- ar { Exhibit.find(id) }
+ TIMES.times { Exhibit.find(id) }
end
- report 'Model.find_by_sql' do
- ar { Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first }
+ x.report 'Model.find_by_sql' do
+ TIMES.times {
+ Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first
+ }
end
- report 'Model.log', (TIMES * 10) do
- ar { Exhibit.connection.send(:log, "hello", "world") {} }
+ x.report "Model.log x(#{TIMES * 10})" do
+ (TIMES * 10).times { Exhibit.connection.send(:log, "hello", "world") {} }
end
- report 'AR.execute(query)', (TIMES / 2) do
- ar { ActiveRecord::Base.connection.execute("Select * from exhibits where id = #{(rand * 1000 + 1).to_i}") }
+ 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}") }
end
-
- summary 'Total'
end
-
-ActiveRecord::Migration.drop_table "exhibits"
-ActiveRecord::Migration.drop_table "users"
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index c80bce2849..59cf42a377 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2010 David Heinemeier Hansson
+# Copyright (c) 2004-2011 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -43,7 +43,6 @@ module ActiveRecord
autoload :ConnectionNotEstablished, 'active_record/errors'
autoload :Aggregations
- autoload :AssociationPreload
autoload :Associations
autoload :AttributeMethods
autoload :AutosaveAssociation
@@ -79,6 +78,11 @@ module ActiveRecord
autoload :Timestamp
autoload :Transactions
autoload :Validations
+ autoload :IdentityMap
+ end
+
+ module Coders
+ autoload :YAMLColumn, 'active_record/coders/yaml_column'
end
module AttributeMethods
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index 8cd7389005..90d3b58c78 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -4,9 +4,7 @@ module ActiveRecord
extend ActiveSupport::Concern
def clear_aggregation_cache #:nodoc:
- self.class.reflect_on_all_aggregations.to_a.each do |assoc|
- instance_variable_set "@#{assoc.name}", nil
- end if self.persisted?
+ @aggregation_cache.clear if persisted?
end
# Active Record implements aggregation through a macro-like class method called +composed_of+
@@ -222,53 +220,32 @@ module ActiveRecord
private
def reader_method(name, class_name, mapping, allow_nil, constructor)
- module_eval do
- define_method(name) do |*args|
- force_reload = args.first || false
-
- unless instance_variable_defined?("@#{name}")
- instance_variable_set("@#{name}", nil)
- end
-
- if (instance_variable_get("@#{name}").nil? || force_reload) && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
- attrs = mapping.collect {|pair| read_attribute(pair.first)}
- object = case constructor
- when Symbol
- class_name.constantize.send(constructor, *attrs)
- when Proc, Method
- constructor.call(*attrs)
- else
- raise ArgumentError, 'Constructor must be a symbol denoting the constructor method to call or a Proc to be invoked.'
- end
- instance_variable_set("@#{name}", object)
- end
- instance_variable_get("@#{name}")
+ 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)
- module_eval do
- define_method("#{name}=") do |part|
- if part.nil? && allow_nil
- mapping.each { |pair| self[pair.first] = nil }
- instance_variable_set("@#{name}", nil)
- else
- unless part.is_a?(class_name.constantize) || converter.nil?
- part = case converter
- when Symbol
- class_name.constantize.send(converter, part)
- when Proc, Method
- converter.call(part)
- else
- raise ArgumentError, 'Converter must be a symbol denoting the converter method to call or a Proc to be invoked.'
- end
- end
-
- mapping.each { |pair| self[pair.first] = part.send(pair.last) }
- instance_variable_set("@#{name}", part.freeze)
+ define_method("#{name}=") do |part|
+ if part.nil? && allow_nil
+ mapping.each { |pair| self[pair.first] = nil }
+ @aggregation_cache[name] = nil
+ else
+ unless part.is_a?(class_name.constantize) || converter.nil?
+ part = converter.respond_to?(:call) ?
+ converter.call(part) :
+ class_name.constantize.send(converter, part)
end
+
+ mapping.each { |pair| self[pair.first] = part.send(pair.last) }
+ @aggregation_cache[name] = part.freeze
end
end
end
diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb
deleted file mode 100644
index 8ca83a7e75..0000000000
--- a/activerecord/lib/active_record/association_preload.rb
+++ /dev/null
@@ -1,421 +0,0 @@
-require 'active_support/core_ext/array/wrap'
-require 'active_support/core_ext/enumerable'
-
-module ActiveRecord
- # See ActiveRecord::AssociationPreload::ClassMethods for documentation.
- module AssociationPreload #:nodoc:
- extend ActiveSupport::Concern
-
- # Implements the details of eager loading of Active Record associations.
- # Application developers should not use this module directly.
- #
- # <tt>ActiveRecord::Base</tt> is extended with this module. The source code in
- # <tt>ActiveRecord::Base</tt> references methods defined in this module.
- #
- # Note that 'eager loading' and 'preloading' are actually the same thing.
- # However, there are two different eager loading strategies.
- #
- # The first one is by using table joins. This was only strategy available
- # prior to Rails 2.1. Suppose that you have an Author model with columns
- # 'name' and 'age', and a Book model with columns 'name' and 'sales'. Using
- # this strategy, Active Record would try to retrieve all data for an author
- # and all of its books via a single query:
- #
- # SELECT * FROM authors
- # LEFT OUTER JOIN books ON authors.id = books.id
- # WHERE authors.name = 'Ken Akamatsu'
- #
- # However, this could result in many rows that contain redundant data. After
- # having received the first row, we already have enough data to instantiate
- # the Author object. In all subsequent rows, only the data for the joined
- # 'books' table is useful; the joined 'authors' data is just redundant, and
- # processing this redundant data takes memory and CPU time. The problem
- # quickly becomes worse and worse as the level of eager loading increases
- # (i.e. if Active Record is to eager load the associations' associations as
- # well).
- #
- # The second strategy is to use multiple database queries, one for each
- # level of association. Since Rails 2.1, this is the default strategy. In
- # situations where a table join is necessary (e.g. when the +:conditions+
- # option references an association's column), it will fallback to the table
- # join strategy.
- #
- # See also ActiveRecord::Associations::ClassMethods, which explains eager
- # loading in a more high-level (application developer-friendly) manner.
- module ClassMethods
- protected
-
- # Eager loads the named associations for the given Active Record record(s).
- #
- # In this description, 'association name' shall refer to the name passed
- # to an association creation method. For example, a model that specifies
- # <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
- # names +:author+ and +:buyers+.
- #
- # == Parameters
- # +records+ is an array of ActiveRecord::Base. This array needs not be flat,
- # i.e. +records+ itself may also contain arrays of records. In any case,
- # +preload_associations+ will preload the all associations records by
- # flattening +records+.
- #
- # +associations+ specifies one or more associations that you want to
- # preload. It may be:
- # - a Symbol or a String which specifies a single association name. For
- # example, specifying +:books+ allows this method to preload all books
- # for an Author.
- # - an Array which specifies multiple association names. This array
- # is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
- # allows this method to preload an author's avatar as well as all of his
- # books.
- # - a Hash which specifies multiple association names, as well as
- # association names for the to-be-preloaded association objects. For
- # example, specifying <tt>{ :author => :avatar }</tt> will preload a
- # book's author, as well as that author's avatar.
- #
- # +:associations+ has the same format as the +:include+ option for
- # <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
- #
- # :books
- # [ :books, :author ]
- # { :author => :avatar }
- # [ :books, { :author => :avatar } ]
- #
- # +preload_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 preload_associations(records, associations, preload_options={})
- records = Array.wrap(records).compact.uniq
- return if records.empty?
- case associations
- when Array then associations.each {|association| preload_associations(records, association, preload_options)}
- when Symbol, String then preload_one_association(records, associations.to_sym, preload_options)
- when Hash then
- associations.each do |parent, child|
- raise "parent must be an association name" unless parent.is_a?(String) || parent.is_a?(Symbol)
- preload_associations(records, parent, preload_options)
- reflection = reflections[parent]
- parents = records.sum { |record| Array.wrap(record.send(reflection.name)) }
- unless parents.empty?
- parents.first.class.preload_associations(parents, child)
- end
- end
- end
- end
-
- private
-
- # Preloads a specific named association for the given records. This is
- # called by +preload_associations+ as its base case.
- def preload_one_association(records, association, preload_options={})
- class_to_reflection = {}
- # Not all records have the same class, so group then preload
- # group on the reflection itself so that if various subclass share the same association then
- # we do not split them unnecessarily
- records.group_by { |record| class_to_reflection[record.class] ||= record.class.reflections[association]}.each do |reflection, _records|
- raise ConfigurationError, "Association named '#{ association }' was not found; perhaps you misspelled it?" unless reflection
-
- # 'reflection.macro' can return 'belongs_to', 'has_many', etc. Thus,
- # the following could call 'preload_belongs_to_association',
- # 'preload_has_many_association', etc.
- send("preload_#{reflection.macro}_association", _records, reflection, preload_options)
- end
- end
-
- def add_preloaded_records_to_collection(parent_records, reflection_name, associated_record)
- parent_records.each do |parent_record|
- association_proxy = parent_record.send(reflection_name)
- association_proxy.loaded
- association_proxy.target.push(*Array.wrap(associated_record))
-
- association_proxy.__send__(:set_inverse_instance, associated_record, parent_record)
- end
- end
-
- def add_preloaded_record_to_collection(parent_records, reflection_name, associated_record)
- parent_records.each do |parent_record|
- parent_record.send("set_#{reflection_name}_target", associated_record)
- end
- end
-
- def set_association_collection_records(id_to_record_map, reflection_name, associated_records, key)
- associated_records.each do |associated_record|
- mapped_records = id_to_record_map[associated_record[key].to_s]
- add_preloaded_records_to_collection(mapped_records, reflection_name, associated_record)
- end
- end
-
- def set_association_single_records(id_to_record_map, reflection_name, associated_records, key)
- seen_keys = {}
- associated_records.each do |associated_record|
- #this is a has_one or belongs_to: there should only be one record.
- #Unfortunately we can't (in portable way) ask the database for
- #'all records where foo_id in (x,y,z), but please
- # only one row per distinct foo_id' so this where we enforce that
- next if seen_keys[associated_record[key].to_s]
- seen_keys[associated_record[key].to_s] = true
- mapped_records = id_to_record_map[associated_record[key].to_s]
- mapped_records.each do |mapped_record|
- association_proxy = mapped_record.send("set_#{reflection_name}_target", associated_record)
- association_proxy.__send__(:set_inverse_instance, associated_record, mapped_record)
- end
- end
-
- id_to_record_map.each do |id, records|
- next if seen_keys.include?(id.to_s)
- records.each {|record| record.send("set_#{reflection_name}_target", nil) }
- end
- end
-
- # Given a collection of Active Record objects, constructs a Hash which maps
- # the objects' IDs to the relevant objects. Returns a 2-tuple
- # <tt>(id_to_record_map, ids)</tt> where +id_to_record_map+ is the Hash,
- # and +ids+ is an Array of record IDs.
- def construct_id_map(records, primary_key=nil)
- id_to_record_map = {}
- ids = []
- records.each do |record|
- primary_key ||= record.class.primary_key
- ids << record[primary_key]
- mapped_records = (id_to_record_map[ids.last.to_s] ||= [])
- mapped_records << record
- end
- ids.uniq!
- return id_to_record_map, ids
- end
-
- def preload_has_and_belongs_to_many_association(records, reflection, preload_options={})
- table_name = reflection.klass.quoted_table_name
- id_to_record_map, ids = construct_id_map(records)
- records.each {|record| record.send(reflection.name).loaded}
- options = reflection.options
-
- conditions = "t0.#{reflection.primary_key_name} #{in_or_equals_for_ids(ids)}"
- conditions << append_conditions(reflection, preload_options)
-
- associated_records_proxy = reflection.klass.unscoped.
- includes(options[:include]).
- joins("INNER JOIN #{connection.quote_table_name options[:join_table]} t0 ON #{reflection.klass.quoted_table_name}.#{reflection.klass.primary_key} = t0.#{reflection.association_foreign_key}").
- select("#{options[:select] || table_name+'.*'}, t0.#{reflection.primary_key_name} as the_parent_record_id").
- order(options[:order])
-
- all_associated_records = associated_records(ids) do |some_ids|
- associated_records_proxy.where([conditions, ids]).to_a
- end
-
- set_association_collection_records(id_to_record_map, reflection.name, all_associated_records, 'the_parent_record_id')
- end
-
- def preload_has_one_or_has_many_association(records, reflection, preload_options={})
- if reflection.macro == :has_many
- return if records.first.send(reflection.name).loaded?
- records.each { |record| record.send(reflection.name).loaded }
- else
- return if records.first.send("loaded_#{reflection.name}?")
- records.each {|record| record.send("set_#{reflection.name}_target", nil)}
- end
-
- options = reflection.options
-
- if options[:through]
- records_with_through_records = preload_through_records(records, reflection, options[:through])
- all_through_records = records_with_through_records.map(&:last).flatten
-
- unless all_through_records.empty?
- source = reflection.source_reflection.name
- all_through_records.first.class.preload_associations(all_through_records, source, options)
-
- records_with_through_records.each do |record, through_records|
- source_records = through_records.map(&source).flatten.compact
-
- case reflection.macro
- when :has_many, :has_and_belongs_to_many
- add_preloaded_records_to_collection([record], reflection.name, source_records)
- when :has_one, :belongs_to
- add_preloaded_record_to_collection([record], reflection.name, source_records.first)
- end
- end
- end
- else
- id_to_record_map, ids = construct_id_map(records, reflection.options[:primary_key])
- associated_records = find_associated_records(ids, reflection, preload_options)
-
- if reflection.macro == :has_many
- set_association_collection_records(
- id_to_record_map, reflection.name,
- associated_records, reflection.primary_key_name
- )
- else
- set_association_single_records(
- id_to_record_map, reflection.name,
- associated_records, reflection.primary_key_name
- )
- end
- end
- end
-
- alias_method :preload_has_one_association, :preload_has_one_or_has_many_association
- alias_method :preload_has_many_association, :preload_has_one_or_has_many_association
-
- def preload_through_records(records, reflection, through_association)
- # If the same through record is loaded twice, we want to return exactly the same
- # object in the result, rather than two separate instances representing the same
- # record. This is so that we can preload the source association for each record,
- # and always be able to access the preloaded association regardless of where we
- # refer to the record.
- #
- # Suffices to say, if AR had an identity map built in then this would be unnecessary.
- identity_map = {}
-
- options = {}
-
- if reflection.options[:source_type]
- interface = reflection.source_reflection.options[:foreign_type]
- options[:conditions] = ["#{connection.quote_column_name interface} = ?", reflection.options[:source_type]]
- records.compact!
- else
- if reflection.options[:conditions]
- options[:include] = reflection.options[:include] ||
- reflection.options[:source]
- options[:conditions] = reflection.options[:conditions]
- end
-
- options[:order] = reflection.options[:order]
- end
-
- records.first.class.preload_associations(records, through_association, options)
-
- records.map do |record|
- if reflection.options[:source_type]
- # Dont cache the association - we would only be caching a subset
- proxy = record.send(through_association)
-
- if proxy.respond_to?(:target)
- through_records = proxy.target
- proxy.reset
- else # this is a has_one :through reflection
- through_records = proxy
- end
- else
- through_records = record.send(through_association)
- end
-
- through_records = Array.wrap(through_records).map do |through_record|
- identity_map[through_record] ||= through_record
- end
-
- [record, through_records]
- end
- end
-
- def preload_belongs_to_association(records, reflection, preload_options={})
- return if records.first.send("loaded_#{reflection.name}?")
- options = reflection.options
- primary_key_name = reflection.primary_key_name
-
- klasses_and_ids = {}
-
- if options[:polymorphic]
- polymorph_type = options[:foreign_type]
-
- # Construct a mapping from klass to a list of ids to load and a mapping of those ids back
- # to their parent_records
- records.each do |record|
- if klass = record.send(polymorph_type)
- klass_id = record.send(primary_key_name)
- if klass_id
- id_map = klasses_and_ids[klass] ||= {}
- (id_map[klass_id.to_s] ||= []) << record
- end
- end
- end
- else
- id_map = {}
- records.each do |record|
- key = record.send(primary_key_name)
- (id_map[key.to_s] ||= []) << record if key
- end
- klasses_and_ids[reflection.klass.name] = id_map unless id_map.empty?
- end
-
- klasses_and_ids.each do |klass_name, _id_map|
- klass = klass_name.constantize
-
- table_name = klass.quoted_table_name
- primary_key = (reflection.options[:primary_key] || klass.primary_key).to_s
- column_type = klass.columns.detect{|c| c.name == primary_key}.type
-
- ids = _id_map.keys.map do |id|
- if column_type == :integer
- id.to_i
- elsif column_type == :float
- id.to_f
- else
- id
- end
- end
-
- conditions = "#{table_name}.#{connection.quote_column_name(primary_key)} #{in_or_equals_for_ids(ids)}"
- conditions << append_conditions(reflection, preload_options)
-
- associated_records = klass.unscoped.where([conditions, ids]).apply_finder_options(options.slice(:include, :select, :joins, :order)).to_a
-
- set_association_single_records(_id_map, reflection.name, associated_records, primary_key)
- end
- end
-
- def find_associated_records(ids, reflection, preload_options)
- options = reflection.options
- table_name = reflection.klass.quoted_table_name
-
- if interface = reflection.options[:as]
- conditions = "#{reflection.klass.quoted_table_name}.#{connection.quote_column_name "#{interface}_id"} #{in_or_equals_for_ids(ids)} and #{reflection.klass.quoted_table_name}.#{connection.quote_column_name "#{interface}_type"} = '#{self.base_class.sti_name}'"
- else
- foreign_key = reflection.primary_key_name
- conditions = "#{reflection.klass.quoted_table_name}.#{foreign_key} #{in_or_equals_for_ids(ids)}"
- end
-
- conditions << append_conditions(reflection, preload_options)
-
- find_options = {
- :select => preload_options[:select] || options[:select] || Arel::SqlLiteral.new("#{table_name}.*"),
- :include => preload_options[:include] || options[:include],
- :joins => options[:joins],
- :group => preload_options[:group] || options[:group],
- :order => preload_options[:order] || options[:order]
- }
-
- associated_records(ids) do |some_ids|
- reflection.klass.scoped.apply_finder_options(find_options.merge(:conditions => [conditions, some_ids])).to_a
- end
- end
-
-
- def interpolate_sql_for_preload(sql)
- instance_eval("%@#{sql.gsub('@', '\@')}@", __FILE__, __LINE__)
- end
-
- def append_conditions(reflection, preload_options)
- sql = ""
- sql << " AND (#{interpolate_sql_for_preload(reflection.sanitized_conditions)})" if reflection.sanitized_conditions
- sql << " AND (#{sanitize_sql preload_options[:conditions]})" if preload_options[:conditions]
- sql
- end
-
- def in_or_equals_for_ids(ids)
- ids.size > 1 ? "IN (?)" : "= ?"
- end
-
- # Some databases impose a limit on the number of ids in a list (in Oracle its 1000)
- # Make several smaller queries if necessary or make one query if the adapter supports it
- def associated_records(ids)
- in_clause_length = connection.in_clause_length || ids.size
- records = []
- ids.each_slice(in_clause_length) do |some_ids|
- records += yield(some_ids)
- end
- records
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 9544fdcb39..ec5b41a3e7 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -5,7 +5,6 @@ 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'
-require 'active_record/associations/class_methods/join_dependency'
module ActiveRecord
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
@@ -20,18 +19,30 @@ module ActiveRecord
end
end
- class HasManyThroughAssociationPolymorphicError < ActiveRecordError #:nodoc:
+ class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection, source_reflection)
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}'.")
end
end
+ class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection)
+ super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
+ end
+ end
+
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
def initialize(owner_class_name, reflection, source_reflection)
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
end
end
+ class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
+ def initialize(owner_class_name, reflection, through_reflection)
+ super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
+ end
+ end
+
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
def initialize(reflection)
through_reflection = reflection.through_reflection
@@ -93,8 +104,8 @@ module ActiveRecord
# (has_many, has_one) when there is at least 1 child associated instance.
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
class DeleteRestrictionError < ActiveRecordError #:nodoc:
- def initialize(reflection)
- super("Cannot delete record because of dependent #{reflection.name}")
+ def initialize(name)
+ super("Cannot delete record because of dependent #{name}")
end
end
@@ -104,37 +115,65 @@ module ActiveRecord
# These classes will be loaded when associations are created.
# So there is no need to eager load them.
- autoload :AssociationCollection, 'active_record/associations/association_collection'
- autoload :AssociationProxy, 'active_record/associations/association_proxy'
- autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
+ autoload :Association, 'active_record/associations/association'
+ autoload :SingularAssociation, 'active_record/associations/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/collection_association'
+ autoload :CollectionProxy, 'active_record/associations/collection_proxy'
+
+ autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
- autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
- autoload :HasManyAssociation, 'active_record/associations/has_many_association'
- autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
- autoload :HasOneAssociation, 'active_record/associations/has_one_association'
- autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
- autoload :AliasTracker, 'active_record/associations/alias_tracker'
+ autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
+ autoload :HasManyAssociation, 'active_record/associations/has_many_association'
+ autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
+ autoload :HasOneAssociation, 'active_record/associations/has_one_association'
+ autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
+ autoload :ThroughAssociation, 'active_record/associations/through_association'
+
+ module Builder #:nodoc:
+ autoload :Association, 'active_record/associations/builder/association'
+ autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
+
+ autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
+ autoload :HasOne, 'active_record/associations/builder/has_one'
+ autoload :HasMany, 'active_record/associations/builder/has_many'
+ 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 :AliasTracker, 'active_record/associations/alias_tracker'
# Clears out the association cache.
def clear_association_cache #:nodoc:
- self.class.reflect_on_all_associations.to_a.each do |assoc|
- instance_variable_set "@#{assoc.name}", nil
- end if self.persisted?
+ @association_cache.clear if persisted?
+ end
+
+ # :nodoc:
+ attr_reader :association_cache
+
+ # Returns the association instance for the given name, instantiating it if it doesn't already exist
+ def association(name) #:nodoc:
+ association = association_instance_get(name)
+
+ if association.nil?
+ reflection = self.class.reflect_on_association(name)
+ association = reflection.association_class.new(self, reflection)
+ association_instance_set(name, association)
+ end
+
+ association
end
private
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
def association_instance_get(name)
- ivar = "@#{name}"
- if instance_variable_defined?(ivar)
- association = instance_variable_get(ivar)
- association if association.respond_to?(:loaded?)
- end
+ @association_cache[name.to_sym]
end
# Set the specified association instance.
def association_instance_set(name, association)
- instance_variable_set("@#{name}", association)
+ @association_cache[name] = association
end
# Associations are a set of macro-like class methods for tying objects together through
@@ -178,7 +217,7 @@ module ActiveRecord
# other=(other) | X | X | X
# build_other(attributes={}) | X | | X
# create_other(attributes={}) | X | | X
- # other.create!(attributes={}) | | | X
+ # create_other!(attributes={}) | X | | X
#
# ===Collection associations (one-to-many / many-to-many)
# | | | has_many
@@ -201,10 +240,9 @@ module ActiveRecord
# others.empty? | X | X | X
# others.clear | X | X | X
# others.delete(other,other,...) | X | X | X
- # others.delete_all | X | X |
+ # others.delete_all | X | X | X
# others.destroy_all | X | X | X
# others.find(*args) | X | X | X
- # others.find_first | X | |
# others.exists? | X | X | X
# others.uniq | X | X | X
# others.reset | X | X | X
@@ -318,26 +356,31 @@ module ActiveRecord
# === 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 (<tt>new_record? == true</tt>).
- # * If either of these saves fail (due to one of the objects being invalid) the assignment
- # statement returns +false+ and the assignment is cancelled.
+ # the object being replaced (if there is one), in order to update their foreign
+ # keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
+ # * If either of these saves fail (due to one of the objects being invalid), an
+ # <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
+ # cancelled.
# * If you wish to assign an object to a +has_one+ association without saving it,
- # use the <tt>association.build</tt> method (documented below).
+ # use the <tt>build_association</tt> method (documented below). The object being
+ # replaced will still be saved to update its foreign key.
# * 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.
+ # 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.
+ # 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 <tt>push</tt> or similar)
- # fails, then <tt>push</tt> returns +false+.
+ # fails, then <tt>push</tt> returns +false+.
+ # * If saving fails while replacing the collection (via <tt>association=</tt>), an
+ # <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
+ # cancelled.
# * You can add an object to a collection without automatically saving it by using the
- # <tt>collection.build</tt> method (documented below).
+ # <tt>collection.build</tt> method (documented below).
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
- # saved when the parent is saved.
+ # saved when the parent is saved.
#
# === Association callbacks
#
@@ -488,6 +531,22 @@ module ActiveRecord
# @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
# @group.avatars.delete(@group.avatars.last) # so would this
#
+ # If you are using a +belongs_to+ on the join model, it is a good idea to set the
+ # <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
+ # works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
+ #
+ # @post = Post.first
+ # @tag = @post.tags.build :name => "ruby"
+ # @tag.save
+ #
+ # The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
+ # <tt>:inverse_of</tt> is set:
+ #
+ # class Taggable < ActiveRecord::Base
+ # belongs_to :post
+ # belongs_to :tag, :inverse_of => :taggings
+ # end
+ #
# === Nested Associations
#
# You can actually specify *any* association with the <tt>:through</tt> option, including an
@@ -800,7 +859,7 @@ module ActiveRecord
# belongs_to :dungeon
# end
#
- # The +traps+ association on +Dungeon+ and the the +dungeon+ association on +Trap+ are
+ # The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
# the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
# is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
# Active Record doesn't know anything about these inverse relationships and so no object
@@ -840,6 +899,73 @@ module ActiveRecord
# * does not work with <tt>:polymorphic</tt> associations.
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
#
+ # == Deleting from associations
+ #
+ # === Dependent associations
+ #
+ # +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
+ # This allows you to specify that associated records should be deleted when the owner is
+ # deleted.
+ #
+ # For example:
+ #
+ # class Author
+ # has_many :posts, :dependent => :destroy
+ # end
+ # Author.find(1).destroy # => Will destroy all of the author's posts, too
+ #
+ # 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.
+ #
+ # === Delete or destroy?
+ #
+ # +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
+ # <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
+ #
+ # For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
+ # cause the records in the join table to be removed.
+ #
+ # For +has_many+, <tt>destroy</tt> will always call the <tt>destroy</tt> method of the
+ # record(s) being removed so that callbacks are run. However <tt>delete</tt> will either
+ # do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
+ # if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
+ # The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
+ # +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
+ # the join records, without running their callbacks).
+ #
+ # There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
+ # it returns the association rather than the records which have been deleted.
+ #
+ # === What gets deleted?
+ #
+ # There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
+ # associations have records in join tables, as well as the associated records. So when we
+ # call one of these deletion methods, what exactly should be deleted?
+ #
+ # The answer is that it is assumed that deletion on an association is about removing the
+ # <i>link</i> between the owner and the associated object(s), rather than necessarily the
+ # associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
+ # <tt>:through</tt>, the join records will be deleted, but the associated records won't.
+ #
+ # This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by_name('food'))</tt>
+ # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
+ # to be removed from the database.
+ #
+ # However, there are examples where this strategy doesn't make sense. For example, suppose
+ # a person has many projects, and each project has many tasks. If we deleted one of a person's
+ # tasks, we would probably not want the project to be deleted. In this scenario, the delete method
+ # won't actually work: it can only be used if the association on the join model is a
+ # +belongs_to+. In other situations you are expected to perform operations directly on
+ # either the associated records or the <tt>:through</tt> association.
+ #
+ # With a regular +has_many+ there is no distinction between the "associated records"
+ # and the "link", so there is only one choice for what gets deleted.
+ #
+ # With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
+ # associated records themselves, you can always do something along the lines of
+ # <tt>person.tasks.each(&:destroy)</tt>.
+ #
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
#
# If you attempt to assign an object to an association that doesn't match the inferred
@@ -864,6 +990,10 @@ module ActiveRecord
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
# Objects will be in addition destroyed if they're associated with <tt>:dependent => :destroy</tt>,
# and deleted if they're associated with <tt>:dependent => :delete_all</tt>.
+ #
+ # If the <tt>:through</tt> option is used, then the join records are deleted (rather than
+ # nullified) by default, but you can specify <tt>:dependent => :destroy</tt> or
+ # <tt>:dependent => :nullify</tt> to override this.
# [collection=objects]
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
@@ -919,7 +1049,7 @@ module ActiveRecord
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
- # === Supported options
+ # === Options
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_many :products</tt> will by default be linked
@@ -947,7 +1077,9 @@ module ActiveRecord
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. If set to
# <tt>:restrict</tt> this object cannot be deleted if it has any associated object.
#
- # *Warning:* This option is ignored when used with <tt>:through</tt> option.
+ # 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
@@ -978,14 +1110,21 @@ module ActiveRecord
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
- # Specifies a join model through which to perform the query. Options for <tt>:class_name</tt>,
+ # Specifies an association through which to perform the query. This can be any other type
+ # of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
# <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
- # source reflection. You can use a <tt>:through</tt> association through any other,
- # association, but if other <tt>:through</tt> associations are involved then the resulting
- # association will be read-only. Otherwise, the collection of join models
- # can be managed via the collection API. For example, new join models are created for
- # newly associated objects, and if some are gone their rows are deleted (directly,
- # no destroy callbacks are triggered).
+ # source reflection.
+ #
+ # If the association on the join model is a +belongs_to+, the collection can be modified
+ # and the records on the <tt>:through</tt> model will be automatically created and removed
+ # as appropriate. Otherwise, the collection is read-only, so you should manipulate the
+ # <tt>:through</tt> association directly.
+ #
+ # If you are going to modify the association (rather than just read from it), then it is
+ # a good idea to set the <tt>:inverse_of</tt> option on the source association on the
+ # join model. This allows associated records to be built which will automatically create
+ # the appropriate join model records when they are saved. (See the 'Association Join Models'
+ # section above.)
# [:source]
# Specifies the source association name used by <tt>has_many :through</tt> queries.
# Only use it if the name cannot be inferred from the association.
@@ -1024,16 +1163,8 @@ module ActiveRecord
# '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(association_id, options = {}, &extension)
- reflection = create_has_many_reflection(association_id, options, &extension)
- configure_dependency_for_has_many(reflection)
- add_association_callbacks(reflection.name, reflection.options)
-
- if options[:through]
- collection_accessor_methods(reflection, HasManyThroughAssociation)
- else
- collection_accessor_methods(reflection, HasManyAssociation)
- end
+ def has_many(name, options = {}, &extension)
+ Builder::HasMany.build(self, name, options, &extension)
end
# Specifies a one-to-one association with another class. This method should only be used
@@ -1051,12 +1182,14 @@ module ActiveRecord
# [build_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not
- # yet been saved. <b>Note:</b> This ONLY works if an association already exists.
- # It will NOT work if the association is +nil+.
+ # yet been saved.
# [create_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
+ # [create_association!(attributes = {})]
+ # Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
@@ -1068,6 +1201,7 @@ module ActiveRecord
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
+ # * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
#
# === Options
#
@@ -1142,17 +1276,8 @@ module ActiveRecord
# 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(association_id, options = {})
- if options[:through]
- reflection = create_has_one_through_reflection(association_id, options)
- association_accessor_methods(reflection, ActiveRecord::Associations::HasOneThroughAssociation)
- else
- reflection = create_has_one_reflection(association_id, options)
- association_accessor_methods(reflection, HasOneAssociation)
- association_constructor_method(:build, reflection, HasOneAssociation)
- association_constructor_method(:create, reflection, HasOneAssociation)
- configure_dependency_for_has_one(reflection)
- end
+ def has_one(name, options = {})
+ Builder::HasOne.build(self, name, options)
end
# Specifies a one-to-one association with another class. This method should only be used
@@ -1174,6 +1299,9 @@ module ActiveRecord
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
+ # [create_association!(attributes = {})]
+ # Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
+ # if the record is invalid.
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
@@ -1185,6 +1313,7 @@ module ActiveRecord
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
+ # * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
# === Options
@@ -1206,6 +1335,11 @@ module ActiveRecord
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
# <tt>belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key
# of "favorite_person_id".
+ # [:foreign_type]
+ # Specify the column used to store the associated object's type, if this is a polymorphic
+ # association. By default this is guessed to be the name of the association with a "_type"
+ # suffix. So a class that defines a <tt>belongs_to :taggable, :polymorphic => true</tt>
+ # association will use "taggable_type" as the default <tt>:foreign_type</tt>.
# [:primary_key]
# Specify the method that returns the primary key of associated object used for the association.
# By default this is id.
@@ -1261,23 +1395,8 @@ module ActiveRecord
# belongs_to :post, :counter_cache => true
# belongs_to :company, :touch => true
# belongs_to :company, :touch => :employees_last_updated_at
- def belongs_to(association_id, options = {})
- reflection = create_belongs_to_reflection(association_id, options)
-
- if reflection.options[:polymorphic]
- association_accessor_methods(reflection, BelongsToPolymorphicAssociation)
- association_foreign_type_setter_method(reflection)
- else
- association_accessor_methods(reflection, BelongsToAssociation)
- association_constructor_method(:build, reflection, BelongsToAssociation)
- association_constructor_method(:create, reflection, BelongsToAssociation)
- end
-
- association_foreign_key_setter_method(reflection)
- add_counter_cache_callbacks(reflection) if options[:counter_cache]
- add_touch_callbacks(reflection, options[:touch]) if options[:touch]
-
- configure_dependency_for_belongs_to(reflection)
+ def belongs_to(name, options = {})
+ Builder::BelongsTo.build(self, name, options)
end
# Specifies a many-to-many relationship with another class. This associates two classes via an
@@ -1308,12 +1427,6 @@ module ActiveRecord
# end
# end
#
- # Deprecated: Any additional fields added to the join table will be placed as attributes when
- # pulling records out through +has_and_belongs_to_many+ associations. Records returned from join
- # tables with additional attributes will be marked as readonly (because we can't save changes
- # to the additional attributes). It's strongly recommended that you upgrade any
- # associations with attributes to a real join model (see introduction).
- #
# Adds the following methods for retrieval and query:
#
# [collection(force_reload = false)]
@@ -1454,469 +1567,9 @@ module ActiveRecord
# has_and_belongs_to_many :categories, :readonly => true
# has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
# 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
- def has_and_belongs_to_many(association_id, options = {}, &extension)
- reflection = create_has_and_belongs_to_many_reflection(association_id, options, &extension)
- collection_accessor_methods(reflection, HasAndBelongsToManyAssociation)
-
- # Don't use a before_destroy callback since users' before_destroy
- # callbacks will be executed after the association is wiped out.
- include Module.new {
- class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def destroy # def destroy
- #{reflection.name}.clear # posts.clear
- super # super
- end # end
- RUBY
- }
-
- add_association_callbacks(reflection.name, options)
+ def has_and_belongs_to_many(name, options = {}, &extension)
+ Builder::HasAndBelongsToMany.build(self, name, options, &extension)
end
-
- private
- # Generates a join table name from two provided table names.
- # The names in the join table names end up in lexicographic order.
- #
- # join_table_name("members", "clubs") # => "clubs_members"
- # join_table_name("members", "special_clubs") # => "members_special_clubs"
- def join_table_name(first_table_name, second_table_name)
- if first_table_name < second_table_name
- join_table = "#{first_table_name}_#{second_table_name}"
- else
- join_table = "#{second_table_name}_#{first_table_name}"
- end
-
- table_name_prefix + join_table + table_name_suffix
- end
-
- def association_accessor_methods(reflection, association_proxy_class)
- redefine_method(reflection.name) do |*params|
- force_reload = params.first unless params.empty?
- association = association_instance_get(reflection.name)
-
- if association.nil? || force_reload
- association = association_proxy_class.new(self, reflection)
- retval = force_reload ? reflection.klass.uncached { association.reload } : association.reload
- if retval.nil? and association_proxy_class == BelongsToAssociation
- association_instance_set(reflection.name, nil)
- return nil
- end
- association_instance_set(reflection.name, association)
- end
-
- association.target.nil? ? nil : association
- end
-
- redefine_method("loaded_#{reflection.name}?") do
- association = association_instance_get(reflection.name)
- association && association.loaded?
- end
-
- redefine_method("#{reflection.name}=") do |new_value|
- association = association_instance_get(reflection.name)
-
- if association.nil? || association.target != new_value
- association = association_proxy_class.new(self, reflection)
- end
-
- association.replace(new_value)
- association_instance_set(reflection.name, new_value.nil? ? nil : association)
- end
-
- redefine_method("set_#{reflection.name}_target") do |target|
- return if target.nil? and association_proxy_class == BelongsToAssociation
- association = association_proxy_class.new(self, reflection)
- association.target = target
- association_instance_set(reflection.name, association)
- end
- end
-
- def collection_reader_method(reflection, association_proxy_class)
- redefine_method(reflection.name) do |*params|
- force_reload = params.first unless params.empty?
- association = association_instance_get(reflection.name)
-
- unless association
- association = association_proxy_class.new(self, reflection)
- association_instance_set(reflection.name, association)
- end
-
- reflection.klass.uncached { association.reload } if force_reload
-
- association
- end
-
- redefine_method("#{reflection.name.to_s.singularize}_ids") do
- if send(reflection.name).loaded? || reflection.options[:finder_sql]
- send(reflection.name).map { |r| r.id }
- else
- if reflection.through_reflection && reflection.source_reflection.belongs_to?
- through = reflection.through_reflection
- primary_key = reflection.source_reflection.primary_key_name
- send(through.name).select("DISTINCT #{through.quoted_table_name}.#{primary_key}").map! { |r| r.send(primary_key) }
- else
- send(reflection.name).select("#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").except(:includes).map! { |r| r.id }
- end
- end
- end
-
- end
-
- def collection_accessor_methods(reflection, association_proxy_class, writer = true)
- collection_reader_method(reflection, association_proxy_class)
-
- if writer
- redefine_method("#{reflection.name}=") do |new_value|
- # Loads proxy class instance (defined in collection_reader_method) if not already loaded
- association = send(reflection.name)
- association.replace(new_value)
- association
- end
-
- redefine_method("#{reflection.name.to_s.singularize}_ids=") do |new_value|
- pk_column = reflection.primary_key_column
- ids = (new_value || []).reject { |nid| nid.blank? }
- ids.map!{ |i| pk_column.type_cast(i) }
- send("#{reflection.name}=", reflection.klass.find(ids).index_by{ |r| r.id }.values_at(*ids))
- end
- end
- end
-
- def association_constructor_method(constructor, reflection, association_proxy_class)
- redefine_method("#{constructor}_#{reflection.name}") do |*params|
- attributees = params.first unless params.empty?
- replace_existing = params[1].nil? ? true : params[1]
- association = association_instance_get(reflection.name)
-
- unless association
- association = association_proxy_class.new(self, reflection)
- association_instance_set(reflection.name, association)
- end
-
- if association_proxy_class == HasOneAssociation
- association.send(constructor, attributees, replace_existing)
- else
- association.send(constructor, attributees)
- end
- end
- end
-
- def association_foreign_key_setter_method(reflection)
- setters = reflect_on_all_associations(:belongs_to).map do |belongs_to_reflection|
- if belongs_to_reflection.primary_key_name == reflection.primary_key_name
- "association_instance_set(:#{belongs_to_reflection.name}, nil);"
- end
- end.compact.join
-
- if method_defined?(:"#{reflection.primary_key_name}=")
- undef_method :"#{reflection.primary_key_name}="
- end
-
- class_eval <<-FILE, __FILE__, __LINE__ + 1
- def #{reflection.primary_key_name}=(new_id)
- write_attribute :#{reflection.primary_key_name}, new_id
- if #{reflection.primary_key_name}_changed?
- #{ setters }
- end
- end
- FILE
- end
-
- def association_foreign_type_setter_method(reflection)
- setters = reflect_on_all_associations(:belongs_to).map do |belongs_to_reflection|
- if belongs_to_reflection.options[:foreign_type] == reflection.options[:foreign_type]
- "association_instance_set(:#{belongs_to_reflection.name}, nil);"
- end
- end.compact.join
-
- field = reflection.options[:foreign_type]
- class_eval <<-FILE, __FILE__, __LINE__ + 1
- def #{field}=(new_id)
- write_attribute :#{field}, new_id
- if #{field}_changed?
- #{ setters }
- end
- end
- FILE
- end
-
- def add_counter_cache_callbacks(reflection)
- cache_column = reflection.counter_cache_column
-
- method_name = "belongs_to_counter_cache_after_create_for_#{reflection.name}".to_sym
- define_method(method_name) do
- association = send(reflection.name)
- association.class.increment_counter(cache_column, association.id) unless association.nil?
- end
- after_create(method_name)
-
- method_name = "belongs_to_counter_cache_before_destroy_for_#{reflection.name}".to_sym
- define_method(method_name) do
- association = send(reflection.name)
- association.class.decrement_counter(cache_column, association.id) unless association.nil?
- end
- before_destroy(method_name)
-
- 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
-
- def add_touch_callbacks(reflection, touch_attribute)
- method_name = :"belongs_to_touch_after_save_or_destroy_for_#{reflection.name}"
- redefine_method(method_name) do
- association = send(reflection.name)
-
- if touch_attribute == true
- association.touch unless association.nil?
- else
- association.touch(touch_attribute) unless association.nil?
- end
- end
- after_save(method_name)
- after_touch(method_name)
- after_destroy(method_name)
- end
-
- # Creates before_destroy callback methods that nullify, delete or destroy
- # has_many associated objects, according to the defined :dependent rule.
- #
- # See HasManyAssociation#delete_records for more information. In general
- # - delete children if the option is set to :destroy or :delete_all
- # - set the foreign key to NULL if the option is set to :nullify
- # - do not delete the parent record if there is any child record if the
- # option is set to :restrict
- #
- # The +extra_conditions+ parameter, which is not used within the main
- # Active Record codebase, is meant to allow plugins to define extra
- # finder conditions.
- def configure_dependency_for_has_many(reflection, extra_conditions = nil)
- if reflection.options.include?(:dependent)
- case reflection.options[:dependent]
- when :destroy
- method_name = "has_many_dependent_destroy_for_#{reflection.name}".to_sym
- define_method(method_name) do
- send(reflection.name).each do |o|
- # No point in executing the counter update since we're going to destroy the parent anyway
- counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
- if(o.respond_to? counter_method) then
- class << o
- self
- end.send(:define_method, counter_method, Proc.new {})
- end
- o.destroy
- end
- end
- before_destroy method_name
- when :delete_all
- before_destroy do |record|
- self.class.send(:delete_all_has_many_dependencies,
- record,
- reflection.name,
- reflection.klass,
- reflection.dependent_conditions(record, self.class, extra_conditions))
- end
- when :nullify
- before_destroy do |record|
- self.class.send(:nullify_has_many_dependencies,
- record,
- reflection.name,
- reflection.klass,
- reflection.primary_key_name,
- reflection.dependent_conditions(record, self.class, extra_conditions))
- end
- when :restrict
- method_name = "has_many_dependent_restrict_for_#{reflection.name}".to_sym
- define_method(method_name) do
- unless send(reflection.name).empty?
- raise DeleteRestrictionError.new(reflection)
- end
- end
- before_destroy method_name
- else
- raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, :nullify or :restrict (#{reflection.options[:dependent].inspect})"
- end
- end
- end
-
- # Creates before_destroy callback methods that nullify, delete or destroy
- # has_one associated objects, according to the defined :dependent rule.
- # If the association is marked as :dependent => :restrict, create a callback
- # that prevents deleting entirely.
- def configure_dependency_for_has_one(reflection)
- if reflection.options.include?(:dependent)
- name = reflection.options[:dependent]
- method_name = :"has_one_dependent_#{name}_for_#{reflection.name}"
-
- case name
- when :destroy, :delete
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
- def #{method_name}
- association = #{reflection.name}
- association.#{name} if association
- end
- eoruby
- when :nullify
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
- def #{method_name}
- association = #{reflection.name}
- association.update_attribute(#{reflection.primary_key_name.inspect}, nil) if association
- end
- eoruby
- when :restrict
- method_name = "has_one_dependent_restrict_for_#{reflection.name}".to_sym
- define_method(method_name) do
- unless send(reflection.name).nil?
- raise DeleteRestrictionError.new(reflection)
- end
- end
- before_destroy method_name
- else
- raise ArgumentError, "The :dependent option expects either :destroy, :delete, :nullify or :restrict (#{reflection.options[:dependent].inspect})"
- end
-
- before_destroy method_name
- end
- end
-
- def configure_dependency_for_belongs_to(reflection)
- if reflection.options.include?(:dependent)
- name = reflection.options[:dependent]
-
- unless [:destroy, :delete].include?(name)
- raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{reflection.options[:dependent].inspect})"
- end
-
- method_name = :"belongs_to_dependent_#{name}_for_#{reflection.name}"
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
- def #{method_name}
- association = #{reflection.name}
- association.#{name} if association
- end
- eoruby
- after_destroy method_name
- end
- end
-
- def delete_all_has_many_dependencies(record, reflection_name, association_class, dependent_conditions)
- association_class.delete_all(dependent_conditions)
- end
-
- def nullify_has_many_dependencies(record, reflection_name, association_class, primary_key_name, dependent_conditions)
- association_class.update_all("#{primary_key_name} = NULL", dependent_conditions)
- end
-
- 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)
- options[:extend] = create_extension_modules(association_id, extension, options[:extend])
-
- create_reflection(:has_many, association_id, options, self)
- end
-
- mattr_accessor :valid_keys_for_has_one_association
- @@valid_keys_for_has_one_association = [
- :class_name, :foreign_key, :remote, :select, :conditions, :order,
- :include, :dependent, :counter_cache, :extend, :as, :readonly,
- :validate, :primary_key, :inverse_of
- ]
-
- def create_has_one_reflection(association_id, options)
- options.assert_valid_keys(valid_keys_for_has_one_association)
- create_reflection(:has_one, association_id, options, self)
- end
-
- def create_has_one_through_reflection(association_id, options)
- options.assert_valid_keys(
- :class_name, :foreign_key, :remote, :select, :conditions, :order, :include, :dependent, :counter_cache, :extend, :as, :through, :source, :source_type, :validate
- )
- create_reflection(:has_one, association_id, options, self)
- end
-
- mattr_accessor :valid_keys_for_belongs_to_association
- @@valid_keys_for_belongs_to_association = [
- :class_name, :primary_key, :foreign_key, :foreign_type, :remote, :select, :conditions,
- :include, :dependent, :counter_cache, :extend, :polymorphic, :readonly,
- :validate, :touch, :inverse_of
- ]
-
- def create_belongs_to_reflection(association_id, options)
- options.assert_valid_keys(valid_keys_for_belongs_to_association)
- reflection = create_reflection(:belongs_to, association_id, options, self)
-
- if options[:polymorphic]
- reflection.options[:foreign_type] ||= reflection.class_name.underscore + "_type"
- end
-
- reflection
- end
-
- mattr_accessor :valid_keys_for_has_and_belongs_to_many_association
- @@valid_keys_for_has_and_belongs_to_many_association = [
- :class_name, :table_name, :join_table, :foreign_key, :association_foreign_key,
- :select, :conditions, :include, :order, :group, :having, :limit, :offset,
- :uniq,
- :finder_sql, :counter_sql, :delete_sql, :insert_sql,
- :before_add, :after_add, :before_remove, :after_remove,
- :extend, :readonly,
- :validate
- ]
-
- def create_has_and_belongs_to_many_reflection(association_id, options, &extension)
- options.assert_valid_keys(valid_keys_for_has_and_belongs_to_many_association)
- options[:extend] = create_extension_modules(association_id, extension, options[:extend])
-
- reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)
-
- if reflection.association_foreign_key == reflection.primary_key_name
- raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
- end
-
- reflection.options[:join_table] ||= join_table_name(undecorated_table_name(self.to_s), undecorated_table_name(reflection.class_name))
- if connection.supports_primary_key? && (connection.primary_key(reflection.options[:join_table]) rescue false)
- raise HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection)
- end
-
- reflection
- end
-
- def add_association_callbacks(association_name, options)
- callbacks = %w(before_add after_add before_remove after_remove)
- callbacks.each do |callback_name|
- full_callback_name = "#{callback_name}_for_#{association_name}"
- defined_callbacks = options[callback_name.to_sym]
-
- full_callback_value = options.has_key?(callback_name.to_sym) ? [defined_callbacks].flatten : []
-
- # TODO : why do i need method_defined? I think its because of the inheritance chain
- class_attribute full_callback_name.to_sym unless method_defined?(full_callback_name)
- self.send("#{full_callback_name}=", full_callback_value)
- end
- end
-
- def create_extension_modules(association_id, block_extension, extensions)
- if block_extension
- extension_module_name = "#{self.to_s.demodulize}#{association_id.to_s.camelize}AssociationExtension"
-
- silence_warnings do
- self.parent.const_set(extension_module_name, Module.new(&block_extension))
- end
- Array.wrap(extensions).push("#{self.parent}::#{extension_module_name}".constantize)
- else
- Array.wrap(extensions)
- end
- end
end
end
end
diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb
index 6428fcec0a..6fc2bfdb31 100644
--- a/activerecord/lib/active_record/associations/alias_tracker.rb
+++ b/activerecord/lib/active_record/associations/alias_tracker.rb
@@ -5,32 +5,44 @@ module ActiveRecord
# Keeps track of table aliases for ActiveRecord::Associations::ClassMethods::JoinDependency and
# ActiveRecord::Associations::ThroughAssociationScope
class AliasTracker # :nodoc:
+ attr_reader :aliases, :table_joins
+
# table_joins is an array of arel joins which might conflict with the aliases we assign here
- def initialize(table_joins = nil)
+ def initialize(table_joins = [])
@aliases = Hash.new
@table_joins = table_joins
end
+ def aliased_table_for(table_name, aliased_name = nil)
+ table_alias = aliased_name_for(table_name, aliased_name)
+
+ if table_alias == table_name # TODO: Is this conditional necessary?
+ Arel::Table.new(table_name)
+ else
+ Arel::Table.new(table_name).alias(table_alias)
+ end
+ end
+
def aliased_name_for(table_name, aliased_name = nil)
aliased_name ||= table_name
- initialize_count_for(table_name) if @aliases[table_name].nil?
+ initialize_count_for(table_name) if aliases[table_name].nil?
- if @aliases[table_name].zero?
+ if aliases[table_name].zero?
# If it's zero, we can have our table_name
- @aliases[table_name] = 1
+ aliases[table_name] = 1
table_name
else
# Otherwise, we need to use an alias
aliased_name = connection.table_alias_for(aliased_name)
- initialize_count_for(aliased_name) if @aliases[aliased_name].nil?
+ initialize_count_for(aliased_name) if aliases[aliased_name].nil?
# Update the count
- @aliases[aliased_name] += 1
+ aliases[aliased_name] += 1
- if @aliases[aliased_name] > 1
- "#{truncate(aliased_name)}_#{@aliases[aliased_name]}"
+ if aliases[aliased_name] > 1
+ "#{truncate(aliased_name)}_#{aliases[aliased_name]}"
else
aliased_name
end
@@ -44,29 +56,21 @@ module ActiveRecord
private
def initialize_count_for(name)
- @aliases[name] = 0
+ aliases[name] = 0
- unless @table_joins.nil? || Arel::Table === @table_joins
+ unless Arel::Table === table_joins
# quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
quoted_name = connection.quote_table_name(name).downcase
- @aliases[name] += @table_joins.grep(Arel::Nodes::Join).map { |join|
- right = join.right
- case right
- when Arel::Table
- right.name.downcase == name ? 1 : 0
- when String
- # Table names + table aliases
- right.downcase.scan(
- /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
- ).size
- else
- 0
- end
+ aliases[name] += table_joins.map { |join|
+ # Table names + table aliases
+ join.left.downcase.scan(
+ /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
+ ).size
}.sum
end
- @aliases[name]
+ aliases[name]
end
def truncate(name)
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
new file mode 100644
index 0000000000..86904ea2bc
--- /dev/null
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -0,0 +1,262 @@
+require 'active_support/core_ext/array/wrap'
+
+module ActiveRecord
+ module Associations
+ # = Active Record Associations
+ #
+ # This is the root class of all associations ('+ Foo' signifies an included module Foo):
+ #
+ # Association
+ # SingularAssociaton
+ # HasOneAssociation
+ # HasOneThroughAssociation + ThroughAssociation
+ # BelongsToAssociation
+ # BelongsToPolymorphicAssociation
+ # CollectionAssociation
+ # HasAndBelongsToManyAssociation
+ # HasManyAssociation
+ # HasManyThroughAssociation + ThroughAssociation
+ class Association #:nodoc:
+ attr_reader :owner, :target, :reflection
+
+ delegate :options, :to => :reflection
+
+ def initialize(owner, reflection)
+ reflection.check_validity!
+
+ @target = nil
+ @owner, @reflection = owner, reflection
+ @updated = false
+
+ reset
+ construct_scope
+ end
+
+ # Returns the name of the table of the related class:
+ #
+ # post.comments.aliased_table_name # => "comments"
+ #
+ def aliased_table_name
+ reflection.klass.table_name
+ end
+
+ # Resets the \loaded flag to +false+ and sets the \target to +nil+.
+ def reset
+ @loaded = false
+ IdentityMap.remove(target) if IdentityMap.enabled? && target
+ @target = nil
+ end
+
+ # Reloads the \target and returns +self+ on success.
+ def reload
+ reset
+ construct_scope
+ load_target
+ self unless target.nil?
+ end
+
+ # Has the \target been already \loaded?
+ def loaded?
+ @loaded
+ end
+
+ # Asserts the \target has been loaded setting the \loaded flag to +true+.
+ def loaded!
+ @loaded = true
+ @stale_state = stale_state
+ end
+
+ # The target is stale if the target no longer points to the record(s) that the
+ # relevant foreign_key(s) refers to. If stale, the association accessor method
+ # on the owner will reload the target. It's up to subclasses to implement the
+ # state_state method if relevant.
+ #
+ # Note that if the target has not been loaded, it is not considered stale.
+ def stale_target?
+ loaded? && @stale_state != stale_state
+ end
+
+ # Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
+ def target=(target)
+ @target = target
+ loaded!
+ end
+
+ def scoped
+ target_scope.merge(@association_scope)
+ end
+
+ # Construct the scope for this association.
+ #
+ # Note that the association_scope is merged into the targed_scope only when the
+ # scoped method is called. This is because at that point the call may be surrounded
+ # by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which
+ # actually gets built.
+ def construct_scope
+ @association_scope = association_scope if klass
+ end
+
+ def association_scope
+ scope = klass.unscoped
+ scope = scope.create_with(creation_attributes)
+ scope = scope.apply_finder_options(options.slice(:readonly, :include))
+ scope = scope.where(interpolate(options[:conditions]))
+ if select = select_value
+ scope = scope.select(select)
+ end
+ scope = scope.extending(*Array.wrap(options[:extend]))
+ scope.where(construct_owner_conditions)
+ end
+
+ def aliased_table
+ klass.arel_table
+ end
+
+ # Set the inverse association, if possible
+ def set_inverse_instance(record)
+ if record && invertible_for?(record)
+ inverse = record.association(inverse_reflection_for(record).name)
+ inverse.target = owner
+ end
+ end
+
+ # This class of the target. belongs_to polymorphic overrides this to look at the
+ # polymorphic_type field on the owner.
+ def klass
+ reflection.klass
+ end
+
+ # Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
+ # through association's scope)
+ def target_scope
+ klass.scoped
+ end
+
+ # Loads the \target if needed and returns it.
+ #
+ # This method is abstract in the sense that it relies on +find_target+,
+ # which is expected to be provided by descendants.
+ #
+ # If the \target is already \loaded it is just returned. Thus, you can call
+ # +load_target+ unconditionally to get the \target.
+ #
+ # ActiveRecord::RecordNotFound is rescued within the method, and it is
+ # not reraised. The proxy is \reset and +nil+ is the return value.
+ def load_target
+ if find_target?
+ begin
+ if IdentityMap.enabled? && association_class && association_class.respond_to?(:base_class)
+ @target = IdentityMap.get(association_class, owner[reflection.foreign_key])
+ end
+ rescue NameError
+ nil
+ ensure
+ @target ||= find_target
+ end
+ end
+ loaded!
+ target
+ rescue ActiveRecord::RecordNotFound
+ reset
+ end
+
+ private
+
+ def find_target?
+ !loaded? && (!owner.new_record? || foreign_key_present?) && klass
+ end
+
+ def interpolate(sql, record = nil)
+ if sql.respond_to?(:to_proc)
+ owner.send(:instance_exec, record, &sql)
+ else
+ sql
+ end
+ end
+
+ def select_value
+ options[:select]
+ end
+
+ # Implemented by (some) subclasses
+ def creation_attributes
+ { }
+ end
+
+ # Returns a hash linking the owner to the association represented by the reflection
+ def construct_owner_attributes(reflection = reflection)
+ attributes = {}
+ if reflection.macro == :belongs_to
+ attributes[reflection.association_primary_key] = owner[reflection.foreign_key]
+ else
+ attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key]
+
+ if options[:as]
+ attributes["#{options[:as]}_type"] = owner.class.base_class.name
+ end
+ end
+ attributes
+ end
+
+ # Builds an array of arel nodes from the owner attributes hash
+ def construct_owner_conditions(table = aliased_table, reflection = reflection)
+ conditions = construct_owner_attributes(reflection).map do |attr, value|
+ table[attr].eq(value)
+ end
+ table.create_and(conditions)
+ end
+
+ # Sets the owner attributes on the given record
+ def set_owner_attributes(record)
+ if owner.persisted?
+ construct_owner_attributes.each { |key, value| record[key] = value }
+ end
+ end
+
+ # Should be true if there is a foreign key present on the owner which
+ # references the target. This is used to determine whether we can load
+ # the target if the owner is currently a new record (and therefore
+ # without a key).
+ #
+ # Currently implemented by belongs_to (vanilla and polymorphic) and
+ # has_one/has_many :through associations which go through a belongs_to
+ def foreign_key_present?
+ false
+ end
+
+ # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
+ # the kind of the class of the associated objects. Meant to be used as
+ # a sanity check when you are about to assign an associated record.
+ def raise_on_type_mismatch(record)
+ unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
+ message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
+ raise ActiveRecord::AssociationTypeMismatch, message
+ end
+ end
+
+ # Can be redefined by subclasses, notably polymorphic belongs_to
+ # The record parameter is necessary to support polymorphic inverses as we must check for
+ # the association in the specific class of the record.
+ def inverse_reflection_for(record)
+ reflection.inverse_of
+ end
+
+ # Is this association invertible? Can be redefined by subclasses.
+ def invertible_for?(record)
+ inverse_reflection_for(record)
+ end
+
+ # This should be implemented to return the values of the relevant key(s) on the owner,
+ # so that when state_state is different from the value stored on the last find_target,
+ # the target is stale.
+ #
+ # This is only relevant to certain associations, which is why it returns nil by default.
+ def stale_state
+ end
+
+ def association_class
+ @reflection.klass
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/association_collection.rb b/activerecord/lib/active_record/associations/association_collection.rb
deleted file mode 100644
index abb17a11c6..0000000000
--- a/activerecord/lib/active_record/associations/association_collection.rb
+++ /dev/null
@@ -1,558 +0,0 @@
-require 'set'
-require 'active_support/core_ext/array/wrap'
-
-module ActiveRecord
- module Associations
- # = Active Record Association Collection
- #
- # AssociationCollection is an abstract class that provides common stuff to
- # ease the implementation of association proxies that represent
- # collections. See the class hierarchy in AssociationProxy.
- #
- # You need to be careful with assumptions regarding the target: The proxy
- # does not fetch records from the database until it needs them, but new
- # ones created with +build+ are added to the target. So, the target may be
- # non-empty and still lack children waiting to be read from the database.
- # If you look directly to the database you cannot assume that's the entire
- # collection because new records may have been added to the target, etc.
- #
- # If you need to work on all current children, new and existing records,
- # +load_target+ and the +loaded+ flag are your friends.
- class AssociationCollection < AssociationProxy #:nodoc:
- delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :to => :scoped
-
- def select(select = nil)
- if block_given?
- load_target
- @target.select.each { |e| yield e }
- else
- scoped.select(select)
- end
- end
-
- def scoped
- with_scope(@scope) { @reflection.klass.scoped }
- end
-
- def find(*args)
- options = args.extract_options!
-
- # If using a custom finder_sql, scan the entire collection.
- if @reflection.options[:finder_sql]
- expects_array = args.first.kind_of?(Array)
- ids = args.flatten.compact.uniq.map { |arg| arg.to_i }
-
- if ids.size == 1
- id = ids.first
- record = load_target.detect { |r| id == r.id }
- expects_array ? [ record ] : record
- else
- load_target.select { |r| ids.include?(r.id) }
- end
- else
- merge_options_from_reflection!(options)
- construct_find_options!(options)
-
- with_scope(:find => @scope[:find].slice(:conditions, :order)) do
- relation = @reflection.klass.send(:construct_finder_arel, options, @reflection.klass.send(:current_scoped_methods))
-
- case args.first
- when :first, :last
- relation.send(args.first)
- when :all
- records = relation.all
- @reflection.options[:uniq] ? uniq(records) : records
- else
- relation.find(*args)
- end
- end
- end
- end
-
- # Fetches the first one using SQL if possible.
- def first(*args)
- if fetch_first_or_last_using_find?(args)
- find(:first, *args)
- else
- load_target unless loaded?
- args = args[1..-1] if args.first.kind_of?(Hash) && args.first.empty?
- @target.first(*args)
- end
- end
-
- # Fetches the last one using SQL if possible.
- def last(*args)
- if fetch_first_or_last_using_find?(args)
- find(:last, *args)
- else
- load_target unless loaded?
- @target.last(*args)
- end
- end
-
- def to_ary
- load_target
- if @target.is_a?(Array)
- @target.to_ary
- else
- Array.wrap(@target)
- end
- end
- alias_method :to_a, :to_ary
-
- def reset
- reset_target!
- reset_named_scopes_cache!
- @loaded = false
- end
-
- def build(attributes = {}, &block)
- if attributes.is_a?(Array)
- attributes.collect { |attr| build(attr, &block) }
- else
- build_record(attributes) do |record|
- block.call(record) if block_given?
- set_belongs_to_association_for(record)
- end
- end
- end
-
- # Add +records+ to this association. Returns +self+ so method calls may be chained.
- # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
- def <<(*records)
- result = true
- load_target if @owner.new_record?
-
- transaction do
- flatten_deeper(records).each do |record|
- raise_on_type_mismatch(record)
- add_record_to_target_with_callbacks(record) do |r|
- result &&= insert_record(record) unless @owner.new_record?
- end
- end
- end
-
- result && self
- end
-
- alias_method :push, :<<
- alias_method :concat, :<<
-
- # Starts a transaction in the association class's database connection.
- #
- # class Author < ActiveRecord::Base
- # has_many :books
- # end
- #
- # Author.first.books.transaction do
- # # same effect as calling Book.transaction
- # end
- def transaction(*args)
- @reflection.klass.transaction(*args) do
- yield
- end
- end
-
- # Remove all records from this association
- #
- # See delete for more info.
- def delete_all
- load_target
- delete(@target)
- reset_target!
- reset_named_scopes_cache!
- end
-
- # Calculate sum using SQL, not Enumerable
- def sum(*args)
- if block_given?
- calculate(:sum, *args) { |*block_args| yield(*block_args) }
- else
- calculate(:sum, *args)
- end
- end
-
- # Count all records using SQL. If the +:counter_sql+ or +:finder_sql+ option is set for the
- # association, it will be used for the query. Otherwise, construct options and pass them with
- # scope to the target class's +count+.
- def count(column_name = nil, options = {})
- column_name, options = nil, column_name if column_name.is_a?(Hash)
-
- if @reflection.options[:counter_sql] || @reflection.options[:finder_sql]
- unless options.blank?
- raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
- end
-
- @reflection.klass.count_by_sql(custom_counter_sql)
- else
-
- if @reflection.options[:uniq]
- # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
- column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" unless column_name
- options.merge!(:distinct => true)
- end
-
- value = @reflection.klass.send(:with_scope, @scope) { @reflection.klass.count(column_name, options) }
-
- limit = @reflection.options[:limit]
- offset = @reflection.options[:offset]
-
- if limit || offset
- [ [value - offset.to_i, 0].max, limit.to_i ].min
- else
- value
- end
- end
- end
-
- # Removes +records+ from this association calling +before_remove+ and
- # +after_remove+ callbacks.
- #
- # This method is abstract in the sense that +delete_records+ has to be
- # provided by descendants. Note this method does not imply the records
- # are actually removed from the database, that depends precisely on
- # +delete_records+. They are in any case removed from the collection.
- def delete(*records)
- remove_records(records) do |_records, old_records|
- delete_records(old_records) if old_records.any?
- _records.each { |record| @target.delete(record) }
- end
- end
-
- # Destroy +records+ and remove them from this association calling
- # +before_remove+ and +after_remove+ callbacks.
- #
- # Note that this method will _always_ remove records from the database
- # ignoring the +:dependent+ option.
- def destroy(*records)
- records = find(records) if records.any? {|record| record.kind_of?(Fixnum) || record.kind_of?(String)}
- remove_records(records) do |_records, old_records|
- old_records.each { |record| record.destroy }
- end
-
- load_target
- end
-
- # Removes all records from this association. Returns +self+ so method calls may be chained.
- def clear
- unless length.zero? # forces load_target if it hasn't happened already
- if @reflection.options[:dependent] == :destroy
- destroy_all
- else
- delete_all
- end
- end
-
- self
- end
-
- # Destroy all the records from this association.
- #
- # See destroy for more info.
- def destroy_all
- load_target
- destroy(@target).tap do
- reset_target!
- reset_named_scopes_cache!
- end
- end
-
- def create(attrs = {})
- if attrs.is_a?(Array)
- attrs.collect { |attr| create(attr) }
- else
- create_record(attrs) do |record|
- yield(record) if block_given?
- record.save
- end
- end
- end
-
- def create!(attrs = {})
- create_record(attrs) do |record|
- yield(record) if block_given?
- record.save!
- end
- end
-
- # Returns the size of the collection by executing a SELECT COUNT(*)
- # query if the collection hasn't been loaded, and calling
- # <tt>collection.size</tt> if it has.
- #
- # If the collection has been already loaded +size+ and +length+ are
- # equivalent. If not and you are going to need the records anyway
- # +length+ will take one less query. Otherwise +size+ is more efficient.
- #
- # This method is abstract in the sense that it relies on
- # +count_records+, which is a method descendants have to provide.
- def size
- if @owner.new_record? || (loaded? && !@reflection.options[:uniq])
- @target.size
- elsif !loaded? && @reflection.options[:group]
- load_target.size
- elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array)
- unsaved_records = @target.select { |r| r.new_record? }
- unsaved_records.size + count_records
- else
- count_records
- end
- end
-
- # Returns the size of the collection calling +size+ on the target.
- #
- # If the collection has been already loaded +length+ and +size+ are
- # equivalent. If not and you are going to need the records anyway this
- # method will take one less query. Otherwise +size+ is more efficient.
- def length
- load_target.size
- end
-
- # Equivalent to <tt>collection.size.zero?</tt>. If the collection has
- # not been already loaded and you are going to fetch the records anyway
- # it is better to check <tt>collection.length.zero?</tt>.
- def empty?
- size.zero?
- end
-
- def any?
- if block_given?
- method_missing(:any?) { |*block_args| yield(*block_args) }
- else
- !empty?
- end
- end
-
- # Returns true if the collection has more than 1 record. Equivalent to collection.size > 1.
- def many?
- if block_given?
- method_missing(:many?) { |*block_args| yield(*block_args) }
- else
- size > 1
- end
- end
-
- def uniq(collection = self)
- seen = {}
- collection.find_all do |record|
- seen[record.id] = true unless seen.key?(record.id)
- end
- end
-
- # Replace this collection with +other_array+
- # This will perform a diff and delete/add only records that have changed.
- def replace(other_array)
- other_array.each { |val| raise_on_type_mismatch(val) }
-
- load_target
- other = other_array.size < 100 ? other_array : other_array.to_set
- current = @target.size < 100 ? @target : @target.to_set
-
- transaction do
- delete(@target.select { |v| !other.include?(v) })
- concat(other_array.select { |v| !current.include?(v) })
- end
- end
-
- def include?(record)
- return false unless record.is_a?(@reflection.klass)
- return include_in_memory?(record) if record.new_record?
- load_target if @reflection.options[:finder_sql] && !loaded?
- loaded? ? @target.include?(record) : exists?(record)
- end
-
- def proxy_respond_to?(method, include_private = false)
- super || @reflection.klass.respond_to?(method, include_private)
- end
-
- protected
- def construct_find_options!(options)
- end
-
- def load_target
- if !@owner.new_record? || foreign_key_present
- begin
- unless loaded?
- if @target.is_a?(Array) && @target.any?
- @target = find_target.map do |f|
- i = @target.index(f)
- if i
- @target.delete_at(i).tap do |t|
- keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
- f.attributes.except(*keys).each do |k,v|
- t.send("#{k}=", v)
- end
- end
- else
- f
- end
- end + @target
- else
- @target = find_target
- end
- end
- rescue ActiveRecord::RecordNotFound
- reset
- end
- end
-
- loaded if target
- target
- end
-
- def method_missing(method, *args)
- match = DynamicFinderMatch.match(method)
- if match && match.creator?
- attributes = match.attribute_names
- return send(:"find_by_#{attributes.join('_and_')}", *args) || create(Hash[attributes.zip(args)])
- end
-
- if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
- super
- elsif @reflection.klass.scopes[method]
- @_named_scopes_cache ||= {}
- @_named_scopes_cache[method] ||= {}
- @_named_scopes_cache[method][args] ||= with_scope(@scope) { @reflection.klass.send(method, *args) }
- else
- with_scope(@scope) do
- if block_given?
- @reflection.klass.send(method, *args) { |*block_args| yield(*block_args) }
- else
- @reflection.klass.send(method, *args)
- end
- end
- end
- end
-
- def custom_counter_sql
- if @reflection.options[:counter_sql]
- counter_sql = @reflection.options[:counter_sql]
- else
- # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
- counter_sql = @reflection.options[:finder_sql].sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
- end
-
- interpolate_sql(counter_sql)
- end
-
- def custom_finder_sql
- interpolate_sql(@reflection.options[:finder_sql])
- end
-
- def reset_target!
- @target = Array.new
- end
-
- def reset_named_scopes_cache!
- @_named_scopes_cache = {}
- end
-
- def find_target
- records =
- if @reflection.options[:finder_sql]
- @reflection.klass.find_by_sql(custom_finder_sql)
- else
- find(:all)
- end
-
- records = @reflection.options[:uniq] ? uniq(records) : records
- records.each do |record|
- set_inverse_instance(record, @owner)
- end
- records
- end
-
- def add_record_to_target_with_callbacks(record)
- callback(:before_add, record)
- yield(record) if block_given?
- @target ||= [] unless loaded?
- if index = @target.index(record)
- @target[index] = record
- else
- @target << record
- end
- callback(:after_add, record)
- set_inverse_instance(record, @owner)
- record
- end
-
- private
- def create_record(attrs)
- attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
- ensure_owner_is_persisted!
-
- scoped_where = scoped.where_values_hash
- create_scope = scoped_where ? @scope[:create].merge(scoped_where) : @scope[:create]
- record = @reflection.klass.send(:with_scope, :create => create_scope) do
- @reflection.build_association(attrs)
- end
- if block_given?
- add_record_to_target_with_callbacks(record) { |*block_args| yield(*block_args) }
- else
- add_record_to_target_with_callbacks(record)
- end
- end
-
- def build_record(attrs)
- attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
- record = @reflection.build_association(attrs)
- if block_given?
- add_record_to_target_with_callbacks(record) { |*block_args| yield(*block_args) }
- else
- add_record_to_target_with_callbacks(record)
- end
- end
-
- def remove_records(*records)
- records = flatten_deeper(records)
- records.each { |record| raise_on_type_mismatch(record) }
-
- transaction do
- records.each { |record| callback(:before_remove, record) }
- old_records = records.reject { |r| r.new_record? }
- yield(records, old_records)
- records.each { |record| callback(:after_remove, record) }
- end
- end
-
- def callback(method, record)
- callbacks_for(method).each do |callback|
- case callback
- when Symbol
- @owner.send(callback, record)
- when Proc
- callback.call(@owner, record)
- else
- callback.send(method, @owner, record)
- end
- end
- end
-
- def callbacks_for(callback_name)
- full_callback_name = "#{callback_name}_for_#{@reflection.name}"
- @owner.class.send(full_callback_name.to_sym) || []
- end
-
- def ensure_owner_is_persisted!
- unless @owner.persisted?
- raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
- end
- end
-
- def fetch_first_or_last_using_find?(args)
- (args.first.kind_of?(Hash) && !args.first.empty?) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] ||
- @target.any? { |record| record.new_record? } || args.first.kind_of?(Integer))
- end
-
- def include_in_memory?(record)
- if @reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
- @owner.send(proxy_reflection.through_reflection.name.to_sym).any? do |source|
- target = source.send(proxy_reflection.source_reflection.name)
- target.respond_to?(:include?) ? target.include?(record) : target == record
- end
- else
- @target.include?(record)
- end
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/association_proxy.rb b/activerecord/lib/active_record/associations/association_proxy.rb
deleted file mode 100644
index 252ff7e7ea..0000000000
--- a/activerecord/lib/active_record/associations/association_proxy.rb
+++ /dev/null
@@ -1,314 +0,0 @@
-require 'active_support/core_ext/array/wrap'
-
-module ActiveRecord
- module Associations
- # = Active Record Associations
- #
- # This is the root class of all association proxies:
- #
- # AssociationProxy
- # BelongsToAssociation
- # HasOneAssociation
- # BelongsToPolymorphicAssociation
- # AssociationCollection
- # HasAndBelongsToManyAssociation
- # HasManyAssociation
- # HasManyThroughAssociation
- # HasOneThroughAssociation
- #
- # Association proxies in Active Record are middlemen between the object that
- # holds the association, known as the <tt>@owner</tt>, and the actual associated
- # object, known as the <tt>@target</tt>. The kind of association any proxy is
- # about is available in <tt>@reflection</tt>. That's an instance of the class
- # ActiveRecord::Reflection::AssociationReflection.
- #
- # For example, given
- #
- # class Blog < ActiveRecord::Base
- # has_many :posts
- # end
- #
- # blog = Blog.find(:first)
- #
- # the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
- # <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
- # the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
- #
- # This class has most of the basic instance methods removed, and delegates
- # unknown methods to <tt>@target</tt> via <tt>method_missing</tt>. As a
- # corner case, it even removes the +class+ method and that's why you get
- #
- # blog.posts.class # => Array
- #
- # though the object behind <tt>blog.posts</tt> is not an Array, but an
- # ActiveRecord::Associations::HasManyAssociation.
- #
- # The <tt>@target</tt> object is not \loaded until needed. For example,
- #
- # blog.posts.count
- #
- # is computed directly through SQL and does not trigger by itself the
- # instantiation of the actual post records.
- class AssociationProxy #:nodoc:
- alias_method :proxy_respond_to?, :respond_to?
- alias_method :proxy_extend, :extend
- delegate :to_param, :to => :proxy_target
- instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to_missing|proxy_/ }
-
- def initialize(owner, reflection)
- @owner, @reflection = owner, reflection
- @updated = false
- reflection.check_validity!
- Array.wrap(reflection.options[:extend]).each { |ext| proxy_extend(ext) }
- reset
- construct_scope
- end
-
- # Returns the owner of the proxy.
- def proxy_owner
- @owner
- end
-
- # Returns the reflection object that represents the association handled
- # by the proxy.
- def proxy_reflection
- @reflection
- end
-
- # Returns the \target of the proxy, same as +target+.
- def proxy_target
- @target
- end
-
- # Does the proxy or its \target respond to +symbol+?
- def respond_to?(*args)
- proxy_respond_to?(*args) || (load_target && @target.respond_to?(*args))
- end
-
- # Forwards <tt>===</tt> explicitly to the \target because the instance method
- # removal above doesn't catch it. Loads the \target if needed.
- def ===(other)
- load_target
- other === @target
- end
-
- # Returns the name of the table of the related class:
- #
- # post.comments.aliased_table_name # => "comments"
- #
- def aliased_table_name
- @reflection.klass.table_name
- end
-
- # Returns the SQL string that corresponds to the <tt>:conditions</tt>
- # option of the macro, if given, or +nil+ otherwise.
- def conditions
- @conditions ||= interpolate_sql(@reflection.sanitized_conditions) if @reflection.sanitized_conditions
- end
- alias :sql_conditions :conditions
-
- # Resets the \loaded flag to +false+ and sets the \target to +nil+.
- def reset
- @loaded = false
- @target = nil
- end
-
- # Reloads the \target and returns +self+ on success.
- def reload
- reset
- load_target
- self unless @target.nil?
- end
-
- # Has the \target been already \loaded?
- def loaded?
- @loaded
- end
-
- # Asserts the \target has been loaded setting the \loaded flag to +true+.
- def loaded
- @loaded = true
- end
-
- # Returns the target of this proxy, same as +proxy_target+.
- def target
- @target
- end
-
- # Sets the target of this proxy to <tt>\target</tt>, and the \loaded flag to +true+.
- def target=(target)
- @target = target
- loaded
- end
-
- # Forwards the call to the target. Loads the \target if needed.
- def inspect
- load_target
- @target.inspect
- end
-
- def send(method, *args)
- if proxy_respond_to?(method)
- super
- else
- load_target
- @target.send(method, *args)
- end
- end
-
- protected
- # Does the association have a <tt>:dependent</tt> option?
- def dependent?
- @reflection.options[:dependent]
- end
-
- def interpolate_sql(sql, record = nil)
- @owner.send(:interpolate_sql, sql, record)
- end
-
- # Forwards the call to the reflection class.
- def sanitize_sql(sql, table_name = @reflection.klass.table_name)
- @reflection.klass.send(:sanitize_sql, sql, table_name)
- end
-
- # Assigns the ID of the owner to the corresponding foreign key in +record+.
- # If the association is polymorphic the type of the owner is also set.
- def set_belongs_to_association_for(record)
- if @reflection.options[:as]
- record["#{@reflection.options[:as]}_id"] = @owner.id if @owner.persisted?
- record["#{@reflection.options[:as]}_type"] = @owner.class.base_class.name.to_s
- else
- if @owner.persisted?
- primary_key = @reflection.options[:primary_key] || :id
- record[@reflection.primary_key_name] = @owner.send(primary_key)
- end
- end
- end
-
- # Merges into +options+ the ones coming from the reflection.
- def merge_options_from_reflection!(options)
- options.reverse_merge!(
- :group => @reflection.options[:group],
- :having => @reflection.options[:having],
- :limit => @reflection.options[:limit],
- :offset => @reflection.options[:offset],
- :joins => @reflection.options[:joins],
- :include => @reflection.options[:include],
- :select => @reflection.options[:select],
- :readonly => @reflection.options[:readonly]
- )
- end
-
- # Forwards +with_scope+ to the reflection.
- def with_scope(*args, &block)
- @reflection.klass.send :with_scope, *args, &block
- end
-
- # Construct the scope used for find/create queries on the target
- def construct_scope
- @scope = {
- :find => construct_find_scope,
- :create => construct_create_scope
- }
- end
-
- # Implemented by subclasses
- def construct_find_scope
- raise NotImplementedError
- end
-
- # Implemented by (some) subclasses
- def construct_create_scope
- {}
- end
-
- private
- # Forwards any missing method call to the \target.
- def method_missing(method, *args)
- if load_target
- unless @target.respond_to?(method)
- message = "undefined method `#{method.to_s}' for \"#{@target}\":#{@target.class.to_s}"
- raise NoMethodError, message
- end
-
- if block_given?
- @target.send(method, *args) { |*block_args| yield(*block_args) }
- else
- @target.send(method, *args)
- end
- end
- end
-
- # Loads the \target if needed and returns it.
- #
- # This method is abstract in the sense that it relies on +find_target+,
- # which is expected to be provided by descendants.
- #
- # If the \target is already \loaded it is just returned. Thus, you can call
- # +load_target+ unconditionally to get the \target.
- #
- # ActiveRecord::RecordNotFound is rescued within the method, and it is
- # not reraised. The proxy is \reset and +nil+ is the return value.
- def load_target
- return nil unless defined?(@loaded)
-
- if !loaded? && (!@owner.new_record? || foreign_key_present)
- @target = find_target
- end
-
- @loaded = true
- @target
- rescue ActiveRecord::RecordNotFound
- reset
- end
-
- # Can be overwritten by associations that might have the foreign key
- # available for an association without having the object itself (and
- # still being a new record). Currently, only +belongs_to+ presents
- # this scenario (both vanilla and polymorphic).
- def foreign_key_present
- false
- end
-
- # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of
- # the kind of the class of the associated objects. Meant to be used as
- # a sanity check when you are about to assign an associated record.
- def raise_on_type_mismatch(record)
- unless record.is_a?(@reflection.klass) || record.is_a?(@reflection.class_name.constantize)
- message = "#{@reflection.class_name}(##{@reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
- raise ActiveRecord::AssociationTypeMismatch, message
- end
- end
-
- if RUBY_VERSION < '1.9.2'
- # Array#flatten has problems with recursive arrays before Ruby 1.9.2.
- # Going one level deeper solves the majority of the problems.
- def flatten_deeper(array)
- array.collect { |element| (element.respond_to?(:flatten) && !element.is_a?(Hash)) ? element.flatten : element }.flatten
- end
- else
- def flatten_deeper(array)
- array.flatten
- end
- end
-
- # Returns the ID of the owner, quoted if needed.
- def owner_quoted_id
- @owner.quoted_id
- end
-
- def set_inverse_instance(record, instance)
- return if record.nil? || !we_can_set_the_inverse_on_this?(record)
- inverse_relationship = @reflection.inverse_of
- unless inverse_relationship.nil?
- record.send(:"set_#{inverse_relationship.name}_target", instance)
- end
- end
-
- # Override in subclasses
- def we_can_set_the_inverse_on_this?(record)
- false
- end
- 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 b438620c8f..c263edd2c6 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -1,41 +1,17 @@
module ActiveRecord
# = Active Record Belongs To Associations
module Associations
- class BelongsToAssociation < AssociationProxy #:nodoc:
- def create(attributes = {})
- replace(@reflection.create_association(attributes))
- end
-
- def build(attributes = {})
- replace(@reflection.build_association(attributes))
- end
-
+ class BelongsToAssociation < SingularAssociation #:nodoc:
def replace(record)
- counter_cache_name = @reflection.counter_cache_column
-
- if record.nil?
- if counter_cache_name && @owner.persisted?
- @reflection.klass.decrement_counter(counter_cache_name, previous_record_id) if @owner[@reflection.primary_key_name]
- end
-
- @target = @owner[@reflection.primary_key_name] = nil
- else
- raise_on_type_mismatch(record)
+ raise_on_type_mismatch(record) if record
- if counter_cache_name && @owner.persisted? && record.id != @owner[@reflection.primary_key_name]
- @reflection.klass.increment_counter(counter_cache_name, record.id)
- @reflection.klass.decrement_counter(counter_cache_name, @owner[@reflection.primary_key_name]) if @owner[@reflection.primary_key_name]
- end
-
- @target = (AssociationProxy === record ? record.target : record)
- @owner[@reflection.primary_key_name] = record_id(record) if record.persisted?
- @updated = true
- end
+ update_counters(record)
+ replace_keys(record)
+ set_inverse_instance(record)
- set_inverse_instance(record, @owner)
+ @updated = true if record
- loaded
- record
+ self.target = record
end
def updated?
@@ -43,50 +19,52 @@ module ActiveRecord
end
private
- def find_target
- find_method = if @reflection.options[:primary_key]
- "find_by_#{@reflection.options[:primary_key]}"
- else
- "find"
- end
- options = @reflection.options.dup.slice(:select, :include, :readonly)
+ def update_counters(record)
+ counter_cache_name = reflection.counter_cache_column
+
+ if counter_cache_name && owner.persisted? && different_target?(record)
+ if record
+ record.class.increment_counter(counter_cache_name, record.id)
+ end
- the_target = with_scope(:find => @scope[:find]) do
- @reflection.klass.send(find_method,
- @owner[@reflection.primary_key_name],
- options
- ) if @owner[@reflection.primary_key_name]
+ if foreign_key_present?
+ klass.decrement_counter(counter_cache_name, target_id)
+ end
end
- set_inverse_instance(the_target, @owner)
- the_target
end
- def construct_find_scope
- { :conditions => conditions }
+ # Checks whether record is different to the current target, without loading it
+ def different_target?(record)
+ record.nil? && owner[reflection.foreign_key] ||
+ record.id != owner[reflection.foreign_key]
end
- def foreign_key_present
- !@owner[@reflection.primary_key_name].nil?
+ def replace_keys(record)
+ owner[reflection.foreign_key] = record && record[reflection.association_primary_key]
+ end
+
+ def foreign_key_present?
+ owner[reflection.foreign_key]
end
# NOTE - for now, we're only supporting inverse setting from belongs_to back onto
# has_one associations.
- def we_can_set_the_inverse_on_this?(record)
- @reflection.has_inverse? && @reflection.inverse_of.macro == :has_one
+ def invertible_for?(record)
+ inverse = inverse_reflection_for(record)
+ inverse && inverse.macro == :has_one
end
- def record_id(record)
- record.send(@reflection.options[:primary_key] || :id)
+ def target_id
+ if options[:primary_key]
+ owner.send(reflection.name).try(:id)
+ else
+ owner[reflection.foreign_key]
+ end
end
- def previous_record_id
- @previous_record_id ||= if @reflection.options[:primary_key]
- previous_record = @owner.send(@reflection.name)
- previous_record.nil? ? nil : previous_record.id
- else
- @owner[@reflection.primary_key_name]
- end
+ def stale_state
+ owner[reflection.foreign_key].to_s
end
end
end
diff --git a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
index a0df860623..1ca448236e 100644
--- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
@@ -1,77 +1,33 @@
module ActiveRecord
# = Active Record Belongs To Polymorphic Association
module Associations
- class BelongsToPolymorphicAssociation < AssociationProxy #:nodoc:
- def replace(record)
- if record.nil?
- @target = @owner[@reflection.primary_key_name] = @owner[@reflection.options[:foreign_type]] = nil
- else
- @target = (AssociationProxy === record ? record.target : record)
-
- @owner[@reflection.primary_key_name] = record_id(record)
- @owner[@reflection.options[:foreign_type]] = record.class.base_class.name.to_s
-
- @updated = true
- end
-
- set_inverse_instance(record, @owner)
- loaded
- record
- end
-
- def updated?
- @updated
- end
-
+ class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc:
private
- # NOTE - for now, we're only supporting inverse setting from belongs_to back onto
- # has_one associations.
- def we_can_set_the_inverse_on_this?(record)
- if @reflection.has_inverse?
- inverse_association = @reflection.polymorphic_inverse_of(record.class)
- inverse_association && inverse_association.macro == :has_one
- else
- false
- end
- end
-
- def set_inverse_instance(record, instance)
- return if record.nil? || !we_can_set_the_inverse_on_this?(record)
- inverse_relationship = @reflection.polymorphic_inverse_of(record.class)
- if inverse_relationship
- record.send(:"set_#{inverse_relationship.name}_target", instance)
- end
+ def replace_keys(record)
+ super
+ owner[reflection.foreign_type] = record && record.class.base_class.name
end
- def construct_find_scope
- { :conditions => conditions }
+ def different_target?(record)
+ super || record.class != klass
end
- def find_target
- return nil if association_class.nil?
-
- target = association_class.send(:with_scope, :find => @scope[:find]) do
- association_class.find(
- @owner[@reflection.primary_key_name],
- :select => @reflection.options[:select],
- :include => @reflection.options[:include]
- )
- end
- set_inverse_instance(target, @owner)
- target
+ def inverse_reflection_for(record)
+ reflection.polymorphic_inverse_of(record.class)
end
- def foreign_key_present
- !@owner[@reflection.primary_key_name].nil?
+ def klass
+ type = owner[reflection.foreign_type]
+ type && type.constantize
end
- def record_id(record)
- record.send(@reflection.options[:primary_key] || :id)
+ def raise_on_type_mismatch(record)
+ # A polymorphic association cannot have a type mismatch, by definition
end
- def association_class
- @owner[@reflection.options[:foreign_type]] ? @owner[@reflection.options[:foreign_type]].constantize : nil
+ def stale_state
+ [super, owner[reflection.foreign_type].to_s]
end
end
end
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
new file mode 100644
index 0000000000..96fca97440
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -0,0 +1,53 @@
+module ActiveRecord::Associations::Builder
+ class Association #:nodoc:
+ class_attribute :valid_options
+ self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate]
+
+ # Set by subclasses
+ class_attribute :macro
+
+ attr_reader :model, :name, :options, :reflection
+
+ def self.build(model, name, options)
+ new(model, name, options).build
+ end
+
+ def initialize(model, name, options)
+ @model, @name, @options = model, name, options
+ end
+
+ def build
+ validate_options
+ reflection = model.create_reflection(self.class.macro, name, options, model)
+ define_accessors
+ reflection
+ end
+
+ private
+
+ def validate_options
+ options.assert_valid_keys(self.class.valid_options)
+ end
+
+ def define_accessors
+ define_readers
+ define_writers
+ end
+
+ def define_readers
+ name = self.name
+
+ model.redefine_method(name) do |*params|
+ association(name).reader(*params)
+ end
+ end
+
+ def define_writers
+ name = self.name
+
+ model.redefine_method("#{name}=") do |value|
+ association(name).writer(value)
+ end
+ 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
new file mode 100644
index 0000000000..964e7fddc8
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -0,0 +1,83 @@
+module ActiveRecord::Associations::Builder
+ class BelongsTo < SingularAssociation #:nodoc:
+ self.macro = :belongs_to
+
+ self.valid_options += [:foreign_type, :polymorphic, :touch]
+
+ def constructable?
+ !options[:polymorphic]
+ end
+
+ def build
+ 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
+ name = self.name
+
+ method_name = "belongs_to_counter_cache_after_create_for_#{name}"
+ model.redefine_method(method_name) do
+ record = send(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}"
+ model.redefine_method(method_name) do
+ record = send(name)
+ record.class.decrement_counter(cache_column, record.id) unless record.nil?
+ end
+ model.before_destroy(method_name)
+
+ 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
+
+ def add_touch_callbacks(reflection)
+ name = self.name
+ method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}"
+ touch = options[:touch]
+
+ model.redefine_method(method_name) do
+ record = send(name)
+
+ unless record.nil?
+ if touch == true
+ record.touch
+ else
+ record.touch(touch)
+ end
+ end
+ end
+
+ model.after_save(method_name)
+ model.after_touch(method_name)
+ model.after_destroy(method_name)
+ end
+
+ def configure_dependency
+ if options[:dependent]
+ unless [:destroy, :delete].include?(options[:dependent])
+ raise ArgumentError, "The :dependent option expects either :destroy or :delete (#{options[:dependent].inspect})"
+ 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
+ end
+end
diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb
new file mode 100644
index 0000000000..f62209a226
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/collection_association.rb
@@ -0,0 +1,75 @@
+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
+ end
+
+ def initialize(model, name, options, &extension)
+ super(model, name, options)
+ @block_extension = extension
+ end
+
+ def build
+ wrap_block_extension
+ reflection = super
+ CALLBACKS.each { |callback_name| define_callback(callback_name) }
+ reflection
+ end
+
+ def writable?
+ true
+ end
+
+ private
+
+ def wrap_block_extension
+ options[:extend] = Array.wrap(options[:extend])
+
+ 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)
+ end
+ end
+
+ def extension_module_name
+ @extension_module_name ||= "#{model.to_s.demodulize}#{name.to_s.camelize}AssociationExtension"
+ end
+
+ 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.wrap(options[callback_name.to_sym]))
+ end
+
+ def define_readers
+ super
+
+ name = self.name
+ model.redefine_method("#{name.to_s.singularize}_ids") do
+ association(name).ids_reader
+ end
+ end
+
+ def define_writers
+ super
+
+ name = self.name
+ model.redefine_method("#{name.to_s.singularize}_ids=") do |ids|
+ association(name).ids_writer(ids)
+ end
+ 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
new file mode 100644
index 0000000000..e40b32826a
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
@@ -0,0 +1,63 @@
+module ActiveRecord::Associations::Builder
+ class HasAndBelongsToMany < CollectionAssociation #:nodoc:
+ self.macro = :has_and_belongs_to_many
+
+ self.valid_options += [:join_table, :association_foreign_key, :delete_sql, :insert_sql]
+
+ def build
+ reflection = super
+ check_validity(reflection)
+ redefine_destroy
+ reflection
+ end
+
+ private
+
+ def redefine_destroy
+ # Don't use a before_destroy callback since users' before_destroy
+ # callbacks will be executed after the association is wiped out.
+ name = self.name
+ model.send(:include, Module.new {
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def destroy # def destroy
+ super # super
+ #{name}.clear # posts.clear
+ end # end
+ RUBY
+ })
+ end
+
+ # TODO: These checks should probably be moved into the Reflection, and we should not be
+ # redefining the options[:join_table] value - instead we should define a
+ # reflection.join_table method.
+ def check_validity(reflection)
+ if reflection.association_foreign_key == reflection.foreign_key
+ raise ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded.new(reflection)
+ end
+
+ reflection.options[:join_table] ||= join_table_name(
+ model.send(:undecorated_table_name, model.to_s),
+ model.send(:undecorated_table_name, reflection.class_name)
+ )
+
+ if model.connection.supports_primary_key? && (model.connection.primary_key(reflection.options[:join_table]) rescue false)
+ raise ActiveRecord::HasAndBelongsToManyAssociationWithPrimaryKeyError.new(reflection)
+ end
+ end
+
+ # Generates a join table name from two provided table names.
+ # The names in the join table names end up in lexicographic order.
+ #
+ # join_table_name("members", "clubs") # => "clubs_members"
+ # join_table_name("members", "special_clubs") # => "members_special_clubs"
+ def join_table_name(first_table_name, second_table_name)
+ if first_table_name < second_table_name
+ join_table = "#{first_table_name}_#{second_table_name}"
+ else
+ join_table = "#{second_table_name}_#{first_table_name}"
+ end
+
+ model.table_name_prefix + join_table + model.table_name_suffix
+ 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
new file mode 100644
index 0000000000..77bb66228d
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_many.rb
@@ -0,0 +1,63 @@
+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
+ end
+
+ private
+
+ def configure_dependency
+ if options[:dependent]
+ unless [:destroy, :delete_all, :nullify, :restrict].include?(options[:dependent])
+ raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
+ ":nullify or :restrict (#{options[:dependent].inspect})"
+ end
+
+ send("define_#{options[:dependent]}_dependency_method")
+ model.before_destroy dependency_method_name
+ end
+ end
+
+ def define_destroy_dependency_method
+ name = self.name
+ model.send(:define_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
+ counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
+ if o.respond_to?(counter_method)
+ class << o
+ self
+ end.send(:define_method, counter_method, Proc.new {})
+ end
+ end
+
+ send(name).delete_all
+ end
+ end
+
+ def define_delete_all_dependency_method
+ name = self.name
+ model.send(:define_method, dependency_method_name) do
+ send(name).delete_all
+ end
+ end
+ alias :define_nullify_dependency_method :define_delete_all_dependency_method
+
+ def define_restrict_dependency_method
+ name = self.name
+ model.send(:define_method, dependency_method_name) do
+ raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty?
+ end
+ end
+
+ def dependency_method_name
+ "has_many_dependent_for_#{name}"
+ 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
new file mode 100644
index 0000000000..07ba5d088e
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/has_one.rb
@@ -0,0 +1,61 @@
+module ActiveRecord::Associations::Builder
+ class HasOne < SingularAssociation #:nodoc:
+ self.macro = :has_one
+
+ self.valid_options += [:order, :as]
+
+ class_attribute :through_options
+ self.through_options = [:through, :source, :source_type]
+
+ def constructable?
+ !options[:through]
+ end
+
+ def build
+ reflection = super
+ configure_dependency unless options[:through]
+ reflection
+ 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 [:destroy, :delete, :nullify, :restrict].include?(options[:dependent])
+ raise ArgumentError, "The :dependent option expects either :destroy, :delete, " \
+ ":nullify or :restrict (#{options[:dependent].inspect})"
+ end
+
+ send("define_#{options[:dependent]}_dependency_method")
+ model.before_destroy dependency_method_name
+ end
+ end
+
+ def dependency_method_name
+ "has_one_dependent_#{options[:dependent]}_for_#{name}"
+ end
+
+ def define_destroy_dependency_method
+ model.send(:class_eval, <<-eoruby, __FILE__, __LINE__ + 1)
+ def #{dependency_method_name}
+ association(#{name.to_sym.inspect}).delete
+ end
+ eoruby
+ end
+ alias :define_delete_dependency_method :define_destroy_dependency_method
+ alias :define_nullify_dependency_method :define_destroy_dependency_method
+
+ def define_restrict_dependency_method
+ name = self.name
+ model.redefine_method(dependency_method_name) do
+ raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).nil?
+ end
+ 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
new file mode 100644
index 0000000000..06a414b874
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/singular_association.rb
@@ -0,0 +1,32 @@
+module ActiveRecord::Associations::Builder
+ class SingularAssociation < Association #:nodoc:
+ self.valid_options += [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]
+
+ def constructable?
+ true
+ end
+
+ def define_accessors
+ super
+ define_constructors if constructable?
+ end
+
+ private
+
+ def define_constructors
+ name = self.name
+
+ model.redefine_method("build_#{name}") do |*params|
+ association(name).build(*params)
+ end
+
+ model.redefine_method("create_#{name}") do |*params|
+ association(name).create(*params)
+ end
+
+ model.redefine_method("create_#{name}!") do |*params|
+ association(name).create!(*params)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/class_methods/join_dependency.rb b/activerecord/lib/active_record/associations/class_methods/join_dependency.rb
deleted file mode 100644
index 78b634a26c..0000000000
--- a/activerecord/lib/active_record/associations/class_methods/join_dependency.rb
+++ /dev/null
@@ -1,216 +0,0 @@
-require 'active_record/associations/class_methods/join_dependency/join_part'
-require 'active_record/associations/class_methods/join_dependency/join_base'
-require 'active_record/associations/class_methods/join_dependency/join_association'
-
-module ActiveRecord
- module Associations
- module ClassMethods
- class JoinDependency # :nodoc:
- attr_reader :join_parts, :reflections, :alias_tracker, :active_record
-
- def initialize(base, associations, joins)
- @active_record = base
- @table_joins = joins
- @join_parts = [JoinBase.new(base)]
- @associations = {}
- @reflections = []
- @alias_tracker = AliasTracker.new(joins)
- @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
- build(associations)
- end
-
- def graft(*associations)
- associations.each do |association|
- join_associations.detect {|a| association == a} ||
- build(association.reflection.name, association.find_parent_in(self) || join_base, association.join_type)
- end
- self
- end
-
- def join_associations
- join_parts.last(join_parts.length - 1)
- end
-
- def join_base
- join_parts.first
- end
-
- def columns
- join_parts.collect { |join_part|
- table = join_part.aliased_table
- join_part.column_names_with_alias.collect{ |column_name, aliased_name|
- table[column_name].as Arel.sql(aliased_name)
- }
- }.flatten
- end
-
- def instantiate(rows)
- primary_key = join_base.aliased_primary_key
- parents = {}
-
- records = rows.map { |model|
- primary_id = model[primary_key]
- parent = parents[primary_id] ||= join_base.instantiate(model)
- construct(parent, @associations, join_associations, model)
- parent
- }.uniq
-
- remove_duplicate_results!(active_record, records, @associations)
- records
- end
-
- def remove_duplicate_results!(base, records, associations)
- case associations
- when Symbol, String
- reflection = base.reflections[associations]
- remove_uniq_by_reflection(reflection, records)
- when Array
- associations.each do |association|
- remove_duplicate_results!(base, records, association)
- end
- when Hash
- associations.keys.each do |name|
- reflection = base.reflections[name]
- remove_uniq_by_reflection(reflection, records)
-
- parent_records = []
- records.each do |record|
- if descendant = record.send(reflection.name)
- if reflection.collection?
- parent_records.concat descendant.target.uniq
- else
- parent_records << descendant
- end
- end
- end
-
- remove_duplicate_results!(reflection.klass, parent_records, associations[name]) unless parent_records.empty?
- end
- end
- end
-
- protected
-
- def cache_joined_association(association)
- associations = []
- parent = association.parent
- while parent != join_base
- associations.unshift(parent.reflection.name)
- parent = parent.parent
- end
- ref = @associations
- associations.each do |key|
- ref = ref[key]
- end
- ref[association.reflection.name] ||= {}
- end
-
- def build(associations, parent = nil, join_type = Arel::InnerJoin)
- parent ||= join_parts.last
- case associations
- when Symbol, String
- reflection = parent.reflections[associations.to_s.intern] or
- raise ConfigurationError, "Association named '#{ associations }' was not found; perhaps you misspelled it?"
- unless join_association = find_join_association(reflection, parent)
- @reflections << reflection
- join_association = build_join_association(reflection, parent)
- join_association.join_type = join_type
- @join_parts << join_association
- cache_joined_association(join_association)
- end
- join_association
- when Array
- associations.each do |association|
- build(association, parent, join_type)
- end
- when Hash
- associations.keys.sort_by { |a| a.to_s }.each do |name|
- join_association = build(name, parent, join_type)
- build(associations[name], join_association, join_type)
- end
- else
- raise ConfigurationError, associations.inspect
- end
- end
-
- def find_join_association(name_or_reflection, parent)
- if String === name_or_reflection
- name_or_reflection = name_or_reflection.to_sym
- end
-
- join_associations.detect { |j|
- j.reflection == name_or_reflection && j.parent == parent
- }
- end
-
- def remove_uniq_by_reflection(reflection, records)
- if reflection && reflection.collection?
- records.each { |record| record.send(reflection.name).target.uniq! }
- end
- end
-
- def build_join_association(reflection, parent)
- JoinAssociation.new(reflection, self, parent)
- end
-
- def construct(parent, associations, join_parts, row)
- case associations
- when Symbol, String
- name = associations.to_s
-
- join_part = join_parts.detect { |j|
- j.reflection.name.to_s == name &&
- j.parent_table_name == parent.class.table_name }
-
- raise(ConfigurationError, "No such association") unless join_part
-
- join_parts.delete(join_part)
- construct_association(parent, join_part, row)
- when Array
- associations.each do |association|
- construct(parent, association, join_parts, row)
- end
- when Hash
- associations.sort_by { |k,_| k.to_s }.each do |name, assoc|
- association = construct(parent, name, join_parts, row)
- construct(association, assoc, join_parts, row) if association
- end
- else
- raise ConfigurationError, associations.inspect
- end
- end
-
- def construct_association(record, join_part, row)
- return if record.id.to_s != join_part.parent.record_id(row).to_s
-
- macro = join_part.reflection.macro
- if macro == :has_one
- return if record.instance_variable_defined?("@#{join_part.reflection.name}")
- association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil?
- set_target_and_inverse(join_part, association, record)
- else
- return if row[join_part.aliased_primary_key].nil?
- association = join_part.instantiate(row)
- case macro
- when :has_many, :has_and_belongs_to_many
- collection = record.send(join_part.reflection.name)
- collection.loaded
- collection.target.push(association)
- collection.__send__(:set_inverse_instance, association, record)
- when :belongs_to
- set_target_and_inverse(join_part, association, record)
- else
- raise ConfigurationError, "unknown macro: #{join_part.reflection.macro}"
- end
- end
- association
- end
-
- def set_target_and_inverse(join_part, association, record)
- association_proxy = record.send("set_#{join_part.reflection.name}_target", association)
- association_proxy.__send__(:set_inverse_instance, association, record)
- end
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb
deleted file mode 100644
index 5cc96a7aef..0000000000
--- a/activerecord/lib/active_record/associations/class_methods/join_dependency/join_association.rb
+++ /dev/null
@@ -1,258 +0,0 @@
-module ActiveRecord
- module Associations
- module ClassMethods
- class JoinDependency # :nodoc:
- class JoinAssociation < JoinPart # :nodoc:
- # The reflection of the association represented
- attr_reader :reflection
-
- # The JoinDependency object which this JoinAssociation exists within. This is mainly
- # relevant for generating aliases which do not conflict with other joins which are
- # part of the query.
- attr_reader :join_dependency
-
- # A JoinBase instance representing the active record we are joining onto.
- # (So in Author.has_many :posts, the Author would be that base record.)
- attr_reader :parent
-
- # What type of join will be generated, either Arel::InnerJoin (default) or Arel::OuterJoin
- attr_accessor :join_type
-
- attr_reader :aliased_prefix
-
- delegate :options, :through_reflection, :source_reflection, :through_reflection_chain, :to => :reflection
- delegate :table, :table_name, :to => :parent, :prefix => :parent
- delegate :alias_tracker, :to => :join_dependency
-
- def initialize(reflection, join_dependency, parent = nil)
- reflection.check_validity!
-
- if reflection.options[:polymorphic]
- raise EagerLoadPolymorphicError.new(reflection)
- end
-
- super(reflection.klass)
-
- @reflection = reflection
- @join_dependency = join_dependency
- @parent = parent
- @join_type = Arel::InnerJoin
- @aliased_prefix = "t#{ join_dependency.join_parts.size }"
-
- setup_tables
- end
-
- def ==(other)
- other.class == self.class &&
- other.reflection == reflection &&
- other.parent == parent
- end
-
- def find_parent_in(other_join_dependency)
- other_join_dependency.join_parts.detect do |join_part|
- parent == join_part
- end
- end
-
- def join_to(relation)
- # The chain starts with the target table, but we want to end with it here (makes
- # more sense in this context)
- chain = through_reflection_chain.reverse
-
- foreign_table = parent_table
- index = 0
-
- chain.each do |reflection|
- table = @tables[index]
- conditions = []
-
- if reflection.source_reflection.nil?
- case reflection.macro
- when :belongs_to
- key = reflection.association_primary_key
- foreign_key = reflection.primary_key_name
- when :has_many, :has_one
- key = reflection.primary_key_name
- foreign_key = reflection.active_record_primary_key
-
- conditions << polymorphic_conditions(reflection, table)
- when :has_and_belongs_to_many
- # For habtm, we need to deal with the join table at the same time as the
- # target table (because unlike a :through association, there is no reflection
- # to represent the join table)
- table, join_table = table
-
- join_key = reflection.primary_key_name
- join_foreign_key = reflection.active_record.primary_key
-
- relation = relation.join(join_table, join_type).on(
- join_table[join_key].
- eq(foreign_table[join_foreign_key])
- )
-
- # We've done the first join now, so update the foreign_table for the second
- foreign_table = join_table
-
- key = reflection.klass.primary_key
- foreign_key = reflection.association_foreign_key
- end
- else
- case reflection.source_reflection.macro
- when :belongs_to
- key = reflection.association_primary_key
- foreign_key = reflection.primary_key_name
-
- conditions << source_type_conditions(reflection, foreign_table)
- when :has_many, :has_one
- key = reflection.primary_key_name
- foreign_key = reflection.source_reflection.active_record_primary_key
- when :has_and_belongs_to_many
- table, join_table = table
-
- join_key = reflection.primary_key_name
- join_foreign_key = reflection.klass.primary_key
-
- relation = relation.join(join_table, join_type).on(
- join_table[join_key].
- eq(foreign_table[join_foreign_key])
- )
-
- foreign_table = join_table
-
- key = reflection.klass.primary_key
- foreign_key = reflection.association_foreign_key
- end
- end
-
- conditions << table[key].eq(foreign_table[foreign_key])
-
- conditions << reflection_conditions(index, table)
- conditions << sti_conditions(reflection, table)
-
- ands = relation.create_and(conditions.flatten.compact)
-
- join = relation.create_join(
- relation.froms.first,
- table,
- relation.create_on(ands),
- join_type)
-
- relation = relation.from(join)
-
- # The current table in this iteration becomes the foreign table in the next
- foreign_table = table
- index += 1
- end
-
- relation
- end
-
- def join_relation(joining_relation)
- self.join_type = Arel::OuterJoin
- joining_relation.joins(self)
- end
-
- def table
- if @tables.last.is_a?(Array)
- @tables.last.first
- else
- @tables.last
- end
- end
-
- def aliased_table_name
- table.table_alias || table.name
- end
-
- protected
-
- def table_alias_for(reflection, join = false)
- name = alias_tracker.pluralize(reflection.name)
- name << "_#{parent_table_name}"
- name << "_join" if join
- name
- end
-
- private
-
- # Generate aliases and Arel::Table instances for each of the tables which we will
- # later generate joins for. We must do this in advance in order to correctly allocate
- # the proper alias.
- def setup_tables
- @tables = through_reflection_chain.map do |reflection|
- aliased_table_name = alias_tracker.aliased_name_for(
- reflection.table_name,
- table_alias_for(reflection, reflection != self.reflection)
- )
-
- table = Arel::Table.new(reflection.table_name, :as => aliased_table_name)
-
- # For habtm, we have two Arel::Table instances related to a single reflection, so
- # we just store them as a pair in the array.
- if reflection.macro == :has_and_belongs_to_many ||
- (reflection.source_reflection &&
- reflection.source_reflection.macro == :has_and_belongs_to_many)
-
- join_table_name = (reflection.source_reflection || reflection).options[:join_table]
-
- aliased_join_table_name = alias_tracker.aliased_name_for(
- join_table_name,
- table_alias_for(reflection, true)
- )
-
- join_table = Arel::Table.new(join_table_name, :as => aliased_join_table_name)
-
- [table, join_table]
- else
- table
- end
- end
-
- # The joins are generated from the through_reflection_chain in reverse order, so
- # reverse the tables too (but it's important to generate the aliases in the 'forward'
- # order, which is why we only do the reversal now.
- @tables.reverse!
-
- @tables
- end
-
- def reflection_conditions(index, table)
- @reflection.through_conditions.reverse[index].map do |condition|
- Arel.sql(sanitize_sql(condition, table.table_alias || table.name))
- end
- end
-
- def sanitize_sql(condition, table_name)
- active_record.send(:sanitize_sql, condition, table_name)
- end
-
- def sti_conditions(reflection, table)
- unless reflection.klass.descends_from_active_record?
- sti_column = table[reflection.klass.inheritance_column]
- sti_condition = sti_column.eq(reflection.klass.sti_name)
- subclasses = reflection.klass.descendants
-
- subclasses.inject(sti_condition) { |attr,subclass|
- attr.or(sti_column.eq(subclass.sti_name))
- }
- end
- end
-
- def source_type_conditions(reflection, foreign_table)
- if reflection.options[:source_type]
- foreign_table[reflection.source_reflection.options[:foreign_type]].
- eq(reflection.options[:source_type])
- end
- end
-
- def polymorphic_conditions(reflection, table)
- if reflection.options[:as]
- table["#{reflection.options[:as]}_type"].
- eq(reflection.active_record.base_class.name)
- end
- end
- end
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/class_methods/join_dependency/join_base.rb b/activerecord/lib/active_record/associations/class_methods/join_dependency/join_base.rb
deleted file mode 100644
index 67567f06df..0000000000
--- a/activerecord/lib/active_record/associations/class_methods/join_dependency/join_base.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-module ActiveRecord
- module Associations
- module ClassMethods
- class JoinDependency # :nodoc:
- class JoinBase < JoinPart # :nodoc:
- def ==(other)
- other.class == self.class &&
- other.active_record == active_record
- end
-
- def aliased_prefix
- "t0"
- end
-
- def table
- Arel::Table.new(table_name, arel_engine)
- end
-
- def aliased_table_name
- active_record.table_name
- end
- end
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/class_methods/join_dependency/join_part.rb b/activerecord/lib/active_record/associations/class_methods/join_dependency/join_part.rb
deleted file mode 100644
index cd16ae5a8b..0000000000
--- a/activerecord/lib/active_record/associations/class_methods/join_dependency/join_part.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-module ActiveRecord
- module Associations
- module ClassMethods
- class JoinDependency # :nodoc:
- # A JoinPart represents a part of a JoinDependency. It is an abstract class, inherited
- # by JoinBase and JoinAssociation. A JoinBase represents the Active Record which
- # everything else is being joined onto. A JoinAssociation represents an association which
- # is joining to the base. A JoinAssociation may result in more than one actual join
- # operations (for example a has_and_belongs_to_many JoinAssociation would result in
- # two; one for the join table and one for the target table).
- class JoinPart # :nodoc:
- # The Active Record class which this join part is associated 'about'; for a JoinBase
- # this is the actual base model, for a JoinAssociation this is the target model of the
- # association.
- attr_reader :active_record
-
- delegate :table_name, :column_names, :primary_key, :reflections, :arel_engine, :to => :active_record
-
- def initialize(active_record)
- @active_record = active_record
- @cached_record = {}
- @column_names_with_alias = nil
- end
-
- def aliased_table
- Arel::Nodes::TableAlias.new aliased_table_name, table
- end
-
- def ==(other)
- raise NotImplementedError
- end
-
- # An Arel::Table for the active_record
- def table
- raise NotImplementedError
- end
-
- # The prefix to be used when aliasing columns in the active_record's table
- def aliased_prefix
- raise NotImplementedError
- end
-
- # The alias for the active_record's table
- def aliased_table_name
- raise NotImplementedError
- end
-
- # The alias for the primary key of the active_record's table
- def aliased_primary_key
- "#{aliased_prefix}_r0"
- end
-
- # An array of [column_name, alias] pairs for the table
- def column_names_with_alias
- unless @column_names_with_alias
- @column_names_with_alias = []
-
- ([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i|
- @column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"]
- end
- end
- @column_names_with_alias
- end
-
- def extract_record(row)
- Hash[column_names_with_alias.map{|cn, an| [cn, row[an]]}]
- end
-
- def record_id(row)
- row[aliased_primary_key]
- end
-
- def instantiate(row)
- @cached_record[record_id(row)] ||= active_record.send(:instantiate, extract_record(row))
- end
- end
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
new file mode 100644
index 0000000000..f3761bd2c7
--- /dev/null
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -0,0 +1,549 @@
+require 'active_support/core_ext/array/wrap'
+
+module ActiveRecord
+ module Associations
+ # = Active Record Association Collection
+ #
+ # AssociationCollection is an abstract class that provides common stuff to
+ # ease the implementation of association proxies that represent
+ # collections. See the class hierarchy in AssociationProxy.
+ #
+ # You need to be careful with assumptions regarding the target: The proxy
+ # does not fetch records from the database until it needs them, but new
+ # ones created with +build+ are added to the target. So, the target may be
+ # non-empty and still lack children waiting to be read from the database.
+ # If you look directly to the database you cannot assume that's the entire
+ # collection because new records may have been added to the target, etc.
+ #
+ # If you need to work on all current children, new and existing records,
+ # +load_target+ and the +loaded+ flag are your friends.
+ class CollectionAssociation < Association #:nodoc:
+ attr_reader :proxy
+
+ def initialize(owner, reflection)
+ # When scopes are created via method_missing on the proxy, they are stored so that
+ # any records fetched from the database are kept around for future use.
+ @scopes_cache = Hash.new do |hash, method|
+ hash[method] = { }
+ end
+
+ super
+
+ @proxy = CollectionProxy.new(self)
+ end
+
+ # Implements the reader method, e.g. foo.items for Foo.has_many :items
+ def reader(force_reload = false)
+ if force_reload
+ klass.uncached { reload }
+ elsif stale_target?
+ reload
+ end
+
+ proxy
+ end
+
+ # Implements the writer method, e.g. foo.items= for Foo.has_many :items
+ def writer(records)
+ replace(records)
+ end
+
+ # Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items
+ def ids_reader
+ if loaded? || options[:finder_sql]
+ load_target.map do |record|
+ record.send(reflection.association_primary_key)
+ end
+ else
+ column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
+
+ scoped.select(column).except(:includes).map! do |record|
+ record.send(reflection.association_primary_key)
+ end
+ end
+ end
+
+ # Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
+ def ids_writer(ids)
+ pk_column = reflection.primary_key_column
+ ids = Array.wrap(ids).reject { |id| id.blank? }
+ ids.map! { |i| pk_column.type_cast(i) }
+ replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
+ end
+
+ def reset
+ @loaded = false
+ @target = []
+ @scopes_cache.clear
+ end
+
+ def select(select = nil)
+ if block_given?
+ load_target.select.each { |e| yield e }
+ else
+ scoped.select(select)
+ end
+ end
+
+ def find(*args)
+ if options[:finder_sql]
+ find_by_scan(*args)
+ else
+ scoped.find(*args)
+ end
+ end
+
+ def first(*args)
+ first_or_last(:first, *args)
+ end
+
+ def last(*args)
+ first_or_last(:last, *args)
+ end
+
+ def build(attributes = {}, &block)
+ build_or_create(attributes, :build, &block)
+ end
+
+ def create(attributes = {}, &block)
+ unless owner.persisted?
+ raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
+ end
+
+ build_or_create(attributes, :create, &block)
+ end
+
+ def create!(attrs = {}, &block)
+ record = create(attrs, &block)
+ Array.wrap(record).each(&:save!)
+ record
+ end
+
+ # Add +records+ to this association. Returns +self+ so method calls may be chained.
+ # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
+ def concat(*records)
+ result = true
+ load_target if owner.new_record?
+
+ transaction do
+ records.flatten.each do |record|
+ raise_on_type_mismatch(record)
+ add_to_target(record) do |r|
+ result &&= insert_record(record) unless owner.new_record?
+ end
+ end
+ end
+
+ result && records
+ end
+
+ # Starts a transaction in the association class's database connection.
+ #
+ # class Author < ActiveRecord::Base
+ # has_many :books
+ # end
+ #
+ # Author.first.books.transaction do
+ # # same effect as calling Book.transaction
+ # end
+ def transaction(*args)
+ reflection.klass.transaction(*args) do
+ yield
+ end
+ end
+
+ # Remove all records from this association
+ #
+ # See delete for more info.
+ def delete_all
+ delete(load_target).tap do
+ reset
+ loaded!
+ end
+ end
+
+ # Destroy all the records from this association.
+ #
+ # See destroy for more info.
+ def destroy_all
+ destroy(load_target).tap do
+ reset
+ loaded!
+ end
+ end
+
+ # Calculate sum using SQL, not Enumerable
+ def sum(*args)
+ if block_given?
+ scoped.sum(*args) { |*block_args| yield(*block_args) }
+ else
+ scoped.sum(*args)
+ end
+ end
+
+ # Count all records using SQL. If the +:counter_sql+ or +:finder_sql+ option is set for the
+ # association, it will be used for the query. Otherwise, construct options and pass them with
+ # scope to the target class's +count+.
+ def count(column_name = nil, count_options = {})
+ column_name, count_options = nil, column_name if column_name.is_a?(Hash)
+
+ if options[:counter_sql] || options[:finder_sql]
+ unless count_options.blank?
+ raise ArgumentError, "If finder_sql/counter_sql is used then options cannot be passed"
+ end
+
+ reflection.klass.count_by_sql(custom_counter_sql)
+ else
+ if options[:uniq]
+ # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
+ column_name ||= reflection.klass.primary_key
+ count_options.merge!(:distinct => true)
+ end
+
+ value = scoped.count(column_name, count_options)
+
+ limit = options[:limit]
+ offset = options[:offset]
+
+ if limit || offset
+ [ [value - offset.to_i, 0].max, limit.to_i ].min
+ else
+ value
+ end
+ end
+ end
+
+ # Removes +records+ from this association calling +before_remove+ and
+ # +after_remove+ callbacks.
+ #
+ # This method is abstract in the sense that +delete_records+ has to be
+ # provided by descendants. Note this method does not imply the records
+ # are actually removed from the database, that depends precisely on
+ # +delete_records+. They are in any case removed from the collection.
+ def delete(*records)
+ delete_or_destroy(records, options[:dependent])
+ end
+
+ # Destroy +records+ and remove them from this association calling
+ # +before_remove+ and +after_remove+ callbacks.
+ #
+ # Note that this method will _always_ remove records from the database
+ # ignoring the +:dependent+ option.
+ def destroy(*records)
+ records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
+ delete_or_destroy(records, :destroy)
+ end
+
+ # Returns the size of the collection by executing a SELECT COUNT(*)
+ # query if the collection hasn't been loaded, and calling
+ # <tt>collection.size</tt> if it has.
+ #
+ # If the collection has been already loaded +size+ and +length+ are
+ # equivalent. If not and you are going to need the records anyway
+ # +length+ will take one less query. Otherwise +size+ is more efficient.
+ #
+ # This method is abstract in the sense that it relies on
+ # +count_records+, which is a method descendants have to provide.
+ def size
+ if owner.new_record? || (loaded? && !options[:uniq])
+ target.size
+ elsif !loaded? && options[:group]
+ load_target.size
+ elsif !loaded? && !options[:uniq] && target.is_a?(Array)
+ unsaved_records = target.select { |r| r.new_record? }
+ unsaved_records.size + count_records
+ else
+ count_records
+ end
+ end
+
+ # Returns the size of the collection calling +size+ on the target.
+ #
+ # If the collection has been already loaded +length+ and +size+ are
+ # equivalent. If not and you are going to need the records anyway this
+ # method will take one less query. Otherwise +size+ is more efficient.
+ def length
+ load_target.size
+ end
+
+ # Equivalent to <tt>collection.size.zero?</tt>. If the collection has
+ # not been already loaded and you are going to fetch the records anyway
+ # it is better to check <tt>collection.length.zero?</tt>.
+ def empty?
+ size.zero?
+ end
+
+ def any?
+ if block_given?
+ load_target.any? { |*block_args| yield(*block_args) }
+ else
+ !empty?
+ end
+ end
+
+ # Returns true if the collection has more than 1 record. Equivalent to collection.size > 1.
+ def many?
+ if block_given?
+ load_target.many? { |*block_args| yield(*block_args) }
+ else
+ size > 1
+ end
+ end
+
+ def uniq(collection = load_target)
+ seen = {}
+ collection.find_all do |record|
+ seen[record.id] = true unless seen.key?(record.id)
+ end
+ end
+
+ # Replace this collection with +other_array+
+ # This will perform a diff and delete/add only records that have changed.
+ def replace(other_array)
+ other_array.each { |val| raise_on_type_mismatch(val) }
+ original_target = load_target.dup
+
+ transaction do
+ delete(target - other_array)
+
+ unless concat(other_array - target)
+ @target = original_target
+ raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
+ "new records could not be saved."
+ end
+ end
+ end
+
+ def include?(record)
+ if record.is_a?(reflection.klass)
+ if record.new_record?
+ include_in_memory?(record)
+ else
+ load_target if options[:finder_sql]
+ loaded? ? target.include?(record) : scoped.exists?(record)
+ end
+ else
+ false
+ end
+ end
+
+ def cached_scope(method, args)
+ @scopes_cache[method][args] ||= scoped.readonly(nil).send(method, *args)
+ end
+
+ def association_scope
+ options = reflection.options.slice(:order, :limit, :joins, :group, :having, :offset)
+ super.apply_finder_options(options)
+ end
+
+ def load_target
+ if find_target?
+ targets = []
+
+ begin
+ targets = find_target
+ rescue ActiveRecord::RecordNotFound
+ reset
+ end
+
+ @target = merge_target_lists(targets, target)
+ end
+
+ loaded!
+ target
+ end
+
+ def add_to_target(record)
+ transaction do
+ callback(:before_add, record)
+ yield(record) if block_given?
+
+ if options[:uniq] && index = @target.index(record)
+ @target[index] = record
+ else
+ @target << record
+ end
+
+ callback(:after_add, record)
+ set_inverse_instance(record)
+ end
+
+ record
+ end
+
+ private
+
+ def select_value
+ super || uniq_select_value
+ end
+
+ def uniq_select_value
+ options[:uniq] && "DISTINCT #{reflection.quoted_table_name}.*"
+ end
+
+ def custom_counter_sql
+ if options[:counter_sql]
+ interpolate(options[:counter_sql])
+ else
+ # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
+ interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
+ end
+ end
+
+ def custom_finder_sql
+ interpolate(options[:finder_sql])
+ end
+
+ def find_target
+ records =
+ if options[:finder_sql]
+ reflection.klass.find_by_sql(custom_finder_sql)
+ else
+ find(:all)
+ end
+
+ records = options[:uniq] ? uniq(records) : records
+ records.each { |record| set_inverse_instance(record) }
+ records
+ end
+
+ def merge_target_lists(loaded, existing)
+ return loaded if existing.empty?
+ return existing if loaded.empty?
+
+ loaded.map do |f|
+ i = existing.index(f)
+ if i
+ existing.delete_at(i).tap do |t|
+ keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
+ # FIXME: this call to attributes causes many NoMethodErrors
+ attributes = f.attributes
+ (attributes.keys - keys).each do |k|
+ t.send("#{k}=", attributes[k])
+ end
+ end
+ else
+ f
+ end
+ end + existing
+ end
+
+ def build_or_create(attributes, method)
+ records = Array.wrap(attributes).map do |attrs|
+ record = build_record(attrs)
+
+ add_to_target(record) do
+ yield(record) if block_given?
+ insert_record(record) if method == :create
+ end
+ end
+
+ attributes.is_a?(Array) ? records : records.first
+ end
+
+ # Do the relevant stuff to insert the given record into the association collection.
+ def insert_record(record, validate = true)
+ raise NotImplementedError
+ end
+
+ def build_record(attributes)
+ reflection.build_association(scoped.scope_for_create.merge(attributes))
+ end
+
+ def delete_or_destroy(records, method)
+ records = records.flatten
+ records.each { |record| raise_on_type_mismatch(record) }
+ existing_records = records.reject { |r| r.new_record? }
+
+ transaction do
+ records.each { |record| callback(:before_remove, record) }
+
+ delete_records(existing_records, method) if existing_records.any?
+ records.each { |record| target.delete(record) }
+
+ records.each { |record| callback(:after_remove, record) }
+ end
+ end
+
+ # Delete the given records from the association, using one of the methods :destroy,
+ # :delete_all or :nullify (or nil, in which case a default is used).
+ def delete_records(records, method)
+ raise NotImplementedError
+ end
+
+ def callback(method, record)
+ callbacks_for(method).each do |callback|
+ case callback
+ when Symbol
+ owner.send(callback, record)
+ when Proc
+ callback.call(owner, record)
+ else
+ callback.send(method, owner, record)
+ end
+ end
+ end
+
+ def callbacks_for(callback_name)
+ full_callback_name = "#{callback_name}_for_#{reflection.name}"
+ owner.class.send(full_callback_name.to_sym) || []
+ end
+
+ # Should we deal with assoc.first or assoc.last by issuing an independent query to
+ # the database, or by getting the target, and then taking the first/last item from that?
+ #
+ # If the args is just a non-empty options hash, go to the database.
+ #
+ # Otherwise, go to the database only if none of the following are true:
+ # * target already loaded
+ # * owner is new record
+ # * custom :finder_sql exists
+ # * target contains new or changed record(s)
+ # * the first arg is an integer (which indicates the number of records to be returned)
+ def fetch_first_or_last_using_find?(args)
+ if args.first.is_a?(Hash)
+ true
+ else
+ !(loaded? ||
+ owner.new_record? ||
+ options[:finder_sql] ||
+ target.any? { |record| record.new_record? || record.changed? } ||
+ args.first.kind_of?(Integer))
+ end
+ end
+
+ def include_in_memory?(record)
+ if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection)
+ owner.send(reflection.through_reflection.name).any? { |source|
+ target = source.send(reflection.source_reflection.name)
+ target.respond_to?(:include?) ? target.include?(record) : target == record
+ } || target.include?(record)
+ else
+ target.include?(record)
+ end
+ end
+
+ # If using a custom finder_sql, #find scans the entire collection.
+ def find_by_scan(*args)
+ expects_array = args.first.kind_of?(Array)
+ ids = args.flatten.compact.uniq.map { |arg| arg.to_i }
+
+ if ids.size == 1
+ id = ids.first
+ record = load_target.detect { |r| id == r.id }
+ expects_array ? [ record ] : record
+ else
+ load_target.select { |r| ids.include?(r.id) }
+ end
+ end
+
+ # Fetches the first/last using SQL if possible, otherwise from the target array.
+ 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)
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
new file mode 100644
index 0000000000..cf77d770c9
--- /dev/null
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -0,0 +1,127 @@
+module ActiveRecord
+ module Associations
+ # Association proxies in Active Record are middlemen between the object that
+ # holds the association, known as the <tt>@owner</tt>, and the actual associated
+ # object, known as the <tt>@target</tt>. The kind of association any proxy is
+ # about is available in <tt>@reflection</tt>. That's an instance of the class
+ # ActiveRecord::Reflection::AssociationReflection.
+ #
+ # For example, given
+ #
+ # class Blog < ActiveRecord::Base
+ # has_many :posts
+ # end
+ #
+ # blog = Blog.find(:first)
+ #
+ # the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
+ # <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
+ # the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
+ #
+ # This class has most of the basic instance methods removed, and delegates
+ # unknown methods to <tt>@target</tt> via <tt>method_missing</tt>. As a
+ # corner case, it even removes the +class+ method and that's why you get
+ #
+ # blog.posts.class # => Array
+ #
+ # though the object behind <tt>blog.posts</tt> is not an Array, but an
+ # ActiveRecord::Associations::HasManyAssociation.
+ #
+ # The <tt>@target</tt> object is not \loaded until needed. For example,
+ #
+ # blog.posts.count
+ #
+ # is computed directly through SQL and does not trigger by itself the
+ # instantiation of the actual post records.
+ class CollectionProxy # :nodoc:
+ alias :proxy_extend :extend
+
+ instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil\?|send|object_id|to_a)$|^__|^respond_to|proxy_/ }
+
+ delegate :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from,
+ :lock, :readonly, :having, :to => :scoped
+
+ delegate :target, :load_target, :loaded?, :scoped,
+ :to => :@association
+
+ delegate :select, :find, :first, :last,
+ :build, :create, :create!,
+ :concat, :delete_all, :destroy_all, :delete, :destroy, :uniq,
+ :sum, :count, :size, :length, :empty?,
+ :any?, :many?, :include?,
+ :to => :@association
+
+ def initialize(association)
+ @association = association
+ Array.wrap(association.options[:extend]).each { |ext| proxy_extend(ext) }
+ end
+
+ def respond_to?(*args)
+ super ||
+ (load_target && target.respond_to?(*args)) ||
+ @association.klass.respond_to?(*args)
+ end
+
+ def method_missing(method, *args, &block)
+ match = DynamicFinderMatch.match(method)
+ if match && match.creator?
+ attributes = match.attribute_names
+ return send(:"find_by_#{attributes.join('_and_')}", *args) || create(Hash[attributes.zip(args)])
+ end
+
+ if target.respond_to?(method) || (!@association.klass.respond_to?(method) && Class.respond_to?(method))
+ if load_target
+ if target.respond_to?(method)
+ target.send(method, *args, &block)
+ else
+ begin
+ super
+ rescue NoMethodError => e
+ raise e, e.message.sub(/ for #<.*$/, " via proxy for #{target}")
+ end
+ end
+ end
+
+ elsif @association.klass.scopes[method]
+ @association.cached_scope(method, args)
+ else
+ scoped.readonly(nil).send(method, *args, &block)
+ end
+ end
+
+ # Forwards <tt>===</tt> explicitly to the \target because the instance method
+ # removal above doesn't catch it. Loads the \target if needed.
+ def ===(other)
+ other === load_target
+ end
+
+ def to_ary
+ load_target.dup
+ end
+ alias_method :to_a, :to_ary
+
+ def <<(*records)
+ @association.concat(records) && self
+ end
+ alias_method :push, :<<
+
+ def clear
+ delete_all
+ self
+ end
+
+ def reload
+ @association.reload
+ self
+ end
+
+ def new(*args, &block)
+ if @association.is_a?(HasManyThroughAssociation)
+ @association.build(*args, &block)
+ else
+ method_missing(:new, *args, &block)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
index e2ce9aefcf..028630977d 100644
--- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
@@ -1,134 +1,73 @@
module ActiveRecord
# = Active Record Has And Belongs To Many Association
module Associations
- class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
- def create(attributes = {})
- create_record(attributes) { |record| insert_record(record) }
- end
+ class HasAndBelongsToManyAssociation < CollectionAssociation #:nodoc:
+ attr_reader :join_table
- def create!(attributes = {})
- create_record(attributes) { |record| insert_record(record, true) }
+ def initialize(owner, reflection)
+ @join_table = Arel::Table.new(reflection.options[:join_table])
+ super
end
- def columns
- @reflection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns")
- end
+ def insert_record(record, validate = true)
+ return if record.new_record? && !record.save(:validate => validate)
+
+ if options[:insert_sql]
+ owner.connection.insert(interpolate(options[:insert_sql], record))
+ else
+ stmt = join_table.compile_insert(
+ join_table[reflection.foreign_key] => owner.id,
+ join_table[reflection.association_foreign_key] => record.id
+ )
- def reset_column_information
- @reflection.reset_column_information
+ owner.connection.insert stmt.to_sql
+ end
+
+ record
end
- def has_primary_key?
- @has_primary_key ||= @owner.connection.supports_primary_key? && @owner.connection.primary_key(@reflection.options[:join_table])
+ def association_scope
+ super.joins(construct_joins)
end
- protected
- def construct_find_options!(options)
- options[:joins] = Arel::SqlLiteral.new(@scope[:find][:joins])
- options[:readonly] = finding_with_ambiguous_select?(options[:select] || @reflection.options[:select])
- options[:select] ||= (@reflection.options[:select] || Arel::SqlLiteral.new('*'))
- end
+ private
def count_records
load_target.size
end
- def insert_record(record, force = true, validate = true)
- if record.new_record?
- if force
- record.save!
- else
- return false unless record.save(:validate => validate)
- end
- end
-
- if @reflection.options[:insert_sql]
- @owner.connection.insert(interpolate_sql(@reflection.options[:insert_sql], record))
+ def delete_records(records, method)
+ if sql = options[:delete_sql]
+ records.each { |record| owner.connection.delete(interpolate(sql, record)) }
else
- relation = Arel::Table.new(@reflection.options[:join_table])
- timestamps = record_timestamp_columns(record)
- timezone = record.send(:current_time_from_proper_timezone) if timestamps.any?
-
- attributes = columns.map do |column|
- name = column.name
- value = case name.to_s
- when @reflection.primary_key_name.to_s
- @owner.id
- when @reflection.association_foreign_key.to_s
- record.id
- when *timestamps
- timezone
- else
- @owner.send(:quote_value, record[name], column) if record.has_attribute?(name)
- end
- [relation[name], value] unless value.nil?
- end
-
- stmt = relation.compile_insert Hash[attributes]
- @owner.connection.insert stmt.to_sql
- end
-
- true
- end
-
- def delete_records(records)
- if sql = @reflection.options[:delete_sql]
- records.each { |record| @owner.connection.delete(interpolate_sql(sql, record)) }
- else
- relation = Arel::Table.new(@reflection.options[:join_table])
- stmt = relation.where(relation[@reflection.primary_key_name].eq(@owner.id).
- and(relation[@reflection.association_foreign_key].in(records.map { |x| x.id }.compact))
+ relation = join_table
+ stmt = relation.where(relation[reflection.foreign_key].eq(owner.id).
+ and(relation[reflection.association_foreign_key].in(records.map { |x| x.id }.compact))
).compile_delete
- @owner.connection.delete stmt.to_sql
+ owner.connection.delete stmt.to_sql
end
end
def construct_joins
- "INNER JOIN #{@owner.connection.quote_table_name @reflection.options[:join_table]} ON #{@reflection.quoted_table_name}.#{@reflection.klass.primary_key} = #{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.association_foreign_key}"
- end
+ right = join_table
+ left = reflection.klass.arel_table
- def construct_conditions
- sql = "#{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.primary_key_name} = #{owner_quoted_id} "
- sql << " AND (#{conditions})" if conditions
- sql
- end
+ condition = left[reflection.klass.primary_key].eq(
+ right[reflection.association_foreign_key])
- def construct_find_scope
- {
- :conditions => construct_conditions,
- :joins => construct_joins,
- :readonly => false,
- :order => @reflection.options[:order],
- :include => @reflection.options[:include],
- :limit => @reflection.options[:limit]
- }
+ right.create_join(right, right.create_on(condition))
end
- # Join tables with additional columns on top of the two foreign keys must be considered
- # ambiguous unless a select clause has been explicitly defined. Otherwise you can get
- # broken records back, if, for example, the join column also has an id column. This will
- # then overwrite the id column of the records coming back.
- def finding_with_ambiguous_select?(select_clause)
- !select_clause && columns.size != 2
+ def construct_owner_conditions
+ super(join_table)
end
- private
- def create_record(attributes, &block)
- # Can't use Base.create because the foreign key may be a protected attribute.
- ensure_owner_is_persisted!
- if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr) }
- else
- build_record(attributes, &block)
- end
+ def select_value
+ super || reflection.klass.arel_table[Arel.star]
end
- def record_timestamp_columns(record)
- if record.record_timestamps
- record.send(:all_timestamp_attributes).map { |x| x.to_s }
- else
- []
- end
+ def invertible_for?(record)
+ false
end
end
end
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index 851b10e300..cebf3e477a 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -5,15 +5,14 @@ module ActiveRecord
#
# If the association has a <tt>:through</tt> option further specialization
# is provided by its child HasManyThroughAssociation.
- class HasManyAssociation < AssociationCollection #:nodoc:
- protected
- def owner_quoted_id(reflection = @reflection)
- if reflection.options[:primary_key]
- @owner.class.quote_value(@owner.send(reflection.options[:primary_key]))
- else
- @owner.quoted_id
- end
- end
+ class HasManyAssociation < CollectionAssociation #:nodoc:
+
+ def insert_record(record, validate = true)
+ set_owner_attributes(record)
+ record.save(:validate => validate)
+ end
+
+ private
# Returns the number of records in this collection.
#
@@ -30,87 +29,73 @@ module ActiveRecord
# the loaded flag is set to true as well.
def count_records
count = if has_cached_counter?
- @owner.send(:read_attribute, cached_counter_attribute_name)
- elsif @reflection.options[:counter_sql] || @reflection.options[:finder_sql]
- @reflection.klass.count_by_sql(custom_counter_sql)
+ owner.send(:read_attribute, cached_counter_attribute_name)
+ elsif options[:counter_sql] || options[:finder_sql]
+ reflection.klass.count_by_sql(custom_counter_sql)
else
- @reflection.klass.count(@scope[:find].slice(:conditions, :joins, :include))
+ scoped.count
end
# If there's nothing in the database and @target has no new records
# we are certain the current target is an empty array. This is a
# documented side-effect of the method that may avoid an extra SELECT.
- @target ||= [] and loaded if count == 0
+ @target ||= [] and loaded! if count == 0
- [@reflection.options[:limit], count].compact.min
+ [options[:limit], count].compact.min
end
- def has_cached_counter?
- @owner.attribute_present?(cached_counter_attribute_name)
+ def has_cached_counter?(reflection = reflection)
+ owner.attribute_present?(cached_counter_attribute_name(reflection))
end
- def cached_counter_attribute_name
- "#{@reflection.name}_count"
+ def cached_counter_attribute_name(reflection = reflection)
+ "#{reflection.name}_count"
end
- def insert_record(record, force = false, validate = true)
- set_belongs_to_association_for(record)
- force ? record.save! : record.save(:validate => validate)
- end
-
- # Deletes the records according to the <tt>:dependent</tt> option.
- def delete_records(records)
- case @reflection.options[:dependent]
- when :destroy
- records.each { |r| r.destroy }
- when :delete_all
- @reflection.klass.delete(records.map { |record| record.id })
- else
- relation = Arel::Table.new(@reflection.table_name)
- stmt = relation.where(relation[@reflection.primary_key_name].eq(@owner.id).
- and(relation[@reflection.klass.primary_key].in(records.map { |r| r.id }))
- ).compile_update(relation[@reflection.primary_key_name] => nil)
- @owner.connection.update stmt.to_sql
-
- @owner.class.update_counters(@owner.id, cached_counter_attribute_name => -records.size) if has_cached_counter?
+ def update_counter(difference, reflection = reflection)
+ if has_cached_counter?(reflection)
+ counter = cached_counter_attribute_name(reflection)
+ owner.class.update_counters(owner.id, counter => difference)
+ owner[counter] += difference
+ owner.changed_attributes.delete(counter) # eww
end
end
- def target_obsolete?
- false
+ # This shit is nasty. We need to avoid the following situation:
+ #
+ # * An associated record is deleted via record.destroy
+ # * Hence the callbacks run, and they find a belongs_to on the record with a
+ # :counter_cache options which points back at our owner. So they update the
+ # counter cache.
+ # * In which case, we must make sure to *not* update the counter cache, or else
+ # it will be decremented twice.
+ #
+ # Hence this method.
+ def inverse_updates_counter_cache?(reflection = reflection)
+ counter_name = cached_counter_attribute_name(reflection)
+ reflection.klass.reflect_on_all_associations(:belongs_to).any? { |inverse_reflection|
+ inverse_reflection.counter_cache_column == counter_name
+ }
end
- def construct_conditions
- if @reflection.options[:as]
- sql =
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_id = #{owner_quoted_id} AND " +
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_type = #{@owner.class.quote_value(@owner.class.base_class.name.to_s)}"
+ # Deletes the records according to the <tt>:dependent</tt> option.
+ def delete_records(records, method)
+ if method == :destroy
+ records.each { |r| r.destroy }
+ update_counter(-records.length) unless inverse_updates_counter_cache?
else
- sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
- end
- sql << " AND (#{conditions})" if conditions
- sql
- end
+ keys = records.map { |r| r[reflection.association_primary_key] }
+ scope = scoped.where(reflection.association_primary_key => keys)
- def construct_find_scope
- {
- :conditions => construct_conditions,
- :readonly => false,
- :order => @reflection.options[:order],
- :limit => @reflection.options[:limit],
- :include => @reflection.options[:include]
- }
- end
-
- def construct_create_scope
- create_scoping = {}
- set_belongs_to_association_for(create_scoping)
- create_scoping
+ if method == :delete_all
+ update_counter(-scope.delete_all)
+ else
+ update_counter(-scope.update_all(reflection.foreign_key => nil))
+ end
+ end
end
- def we_can_set_the_inverse_on_this?(record)
- @reflection.inverse_of
- end
+ alias creation_attributes construct_owner_attributes
end
end
end
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 0b00132ad9..9d2b29685b 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -1,109 +1,144 @@
-require "active_record/associations/through_association_scope"
require 'active_support/core_ext/object/blank'
module ActiveRecord
# = Active Record Has Many Through Association
module Associations
class HasManyThroughAssociation < HasManyAssociation #:nodoc:
- include ThroughAssociationScope
-
- def build(attributes = {}, &block)
- ensure_not_nested
- super
- end
+ include ThroughAssociation
alias_method :new, :build
- def create!(attrs = nil)
- create_record(attrs, true)
- end
-
- def create(attrs = nil)
- create_record(attrs, false)
- end
-
- def destroy(*records)
- transaction do
- delete_records(flatten_deeper(records))
- super
- end
- end
-
# 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 fewer
# SELECT query if you use #length.
def size
- return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
- return @target.size if loaded?
- return count
+ if has_cached_counter?
+ owner.send(:read_attribute, cached_counter_attribute_name)
+ elsif loaded?
+ target.size
+ else
+ count
+ end
+ end
+
+ def concat(*records)
+ unless owner.new_record?
+ records.flatten.each do |record|
+ raise_on_type_mismatch(record)
+ record.save! if record.new_record?
+ end
+ end
+
+ super
end
- protected
- def create_record(attrs, force = true)
+ def insert_record(record, validate = true)
+ ensure_not_nested
+ return if record.new_record? && !record.save(:validate => validate)
+
+ through_record(record).save!
+ update_counter(1)
+ record
+ end
+
+ private
+
+ def through_record(record)
+ through_association = owner.association(through_reflection.name)
+ attributes = construct_join_attributes(record)
+
+ through_record = Array.wrap(through_association.target).find { |candidate|
+ candidate.attributes.slice(*attributes.keys) == attributes
+ }
+
+ unless through_record
+ through_record = through_association.build(attributes)
+ through_record.send("#{source_reflection.name}=", record)
+ end
+
+ through_record
+ end
+
+ def build_record(attributes)
ensure_not_nested
- ensure_owner_is_persisted!
- transaction do
- object = @reflection.klass.new(attrs)
- add_record_to_target_with_callbacks(object) {|r| insert_record(object, force) }
- object
+ record = super(attributes)
+
+ inverse = source_reflection.inverse_of
+ if inverse
+ if inverse.macro == :has_many
+ record.send(inverse.name) << through_record(record)
+ elsif inverse.macro == :has_one
+ record.send("#{inverse.name}=", through_record(record))
+ end
end
+
+ record
end
def target_reflection_has_associated_record?
- if @reflection.through_reflection.macro == :belongs_to && @owner[@reflection.through_reflection.primary_key_name].blank?
+ if through_reflection.macro == :belongs_to && owner[through_reflection.foreign_key].blank?
false
else
true
end
end
- def construct_find_options!(options)
- options[:joins] = construct_joins(options[:joins])
- options[:include] = @reflection.source_reflection.options[:include] if options[:include].nil? && @reflection.source_reflection.options[:include]
+ def update_through_counter?(method)
+ case method
+ when :destroy
+ !inverse_updates_counter_cache?(through_reflection)
+ when :nullify
+ false
+ else
+ true
+ end
end
- def insert_record(record, force = true, validate = true)
+ def delete_records(records, method)
ensure_not_nested
- if record.new_record?
- if force
- record.save!
- else
- return false unless record.save(:validate => validate)
- end
- end
+ through = owner.association(through_reflection.name)
+ scope = through.scoped.where(construct_join_attributes(*records))
- through_association = @owner.send(@reflection.through_reflection.name)
- through_association.create!(construct_join_attributes(record))
- end
+ case method
+ when :destroy
+ count = scope.destroy_all.length
+ when :nullify
+ count = scope.update_all(source_reflection.foreign_key => nil)
+ else
+ count = scope.delete_all
+ end
- # TODO - add dependent option support
- def delete_records(records)
- ensure_not_nested
+ delete_through_records(through, records)
- klass = @reflection.through_reflection.klass
- records.each do |associate|
- klass.delete_all(construct_join_attributes(associate))
+ if through_reflection.macro == :has_many && update_through_counter?(method)
+ update_counter(-count, through_reflection)
end
- end
- def find_target
- return [] unless target_reflection_has_associated_record?
- with_scope(@scope) { @reflection.klass.find(:all) }
+ update_counter(-count)
end
- def has_cached_counter?
- @owner.attribute_present?(cached_counter_attribute_name)
+ def delete_through_records(through, records)
+ if through_reflection.macro == :has_many
+ records.each do |record|
+ through.target.delete(through_record(record))
+ end
+ else
+ records.each do |record|
+ through.target = nil if through.target == through_record(record)
+ end
+ end
end
- def cached_counter_attribute_name
- "#{@reflection.name}_count"
+ def find_target
+ return [] unless target_reflection_has_associated_record?
+ scoped.all
end
# NOTE - not sure that we can actually cope with inverses here
- def we_can_set_the_inverse_on_this?(record)
+ def invertible_for?(record)
false
end
end
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index d581939f04..e13f97125f 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -1,135 +1,76 @@
module ActiveRecord
# = Active Record Belongs To Has One Association
module Associations
- class HasOneAssociation < AssociationProxy #:nodoc:
- def create(attrs = {}, replace_existing = true)
- new_record(replace_existing) do |reflection|
- attrs = merge_with_conditions(attrs)
- reflection.create_association(attrs)
- end
- end
+ class HasOneAssociation < SingularAssociation #:nodoc:
+ def replace(record, save = true)
+ raise_on_type_mismatch(record) if record
+ load_target
- def create!(attrs = {}, replace_existing = true)
- new_record(replace_existing) do |reflection|
- attrs = merge_with_conditions(attrs)
- reflection.create_association!(attrs)
- end
- end
+ reflection.klass.transaction do
+ if target && target != record
+ remove_target!(options[:dependent])
+ end
+
+ if record
+ set_inverse_instance(record)
+ set_owner_attributes(record)
- def build(attrs = {}, replace_existing = true)
- new_record(replace_existing) do |reflection|
- attrs = merge_with_conditions(attrs)
- reflection.build_association(attrs)
+ if owner.persisted? && save && !record.save
+ nullify_owner_attributes(record)
+ set_owner_attributes(target)
+ raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
+ end
+ end
end
- end
- def replace(obj, dont_save = false)
- load_target
+ self.target = record
+ end
- unless @target.nil? || @target == obj
- if dependent? && !dont_save
- case @reflection.options[:dependent]
+ def delete(method = options[:dependent])
+ if load_target
+ case method
when :delete
- @target.delete if @target.persisted?
- @owner.clear_association_cache
+ target.delete
when :destroy
- @target.destroy if @target.persisted?
- @owner.clear_association_cache
+ target.destroy
when :nullify
- @target[@reflection.primary_key_name] = nil
- @target.save if @owner.persisted? && @target.persisted?
- end
- else
- @target[@reflection.primary_key_name] = nil
- @target.save if @owner.persisted? && @target.persisted?
+ target.update_attribute(reflection.foreign_key, nil)
end
end
-
- if obj.nil?
- @target = nil
- else
- raise_on_type_mismatch(obj)
- set_belongs_to_association_for(obj)
- @target = (AssociationProxy === obj ? obj.target : obj)
- end
-
- set_inverse_instance(obj, @owner)
- @loaded = true
-
- unless !@owner.persisted? || obj.nil? || dont_save
- return (obj.save ? self : false)
- else
- return (obj.nil? ? nil : self)
- end
end
- protected
- def owner_quoted_id(reflection = @reflection)
- if reflection.options[:primary_key]
- @owner.class.quote_value(@owner.send(reflection.options[:primary_key]))
- else
- @owner.quoted_id
- end
- end
+ def association_scope
+ super.order(options[:order])
+ end
private
- def find_target
- options = @reflection.options.dup.slice(:select, :order, :include, :readonly)
- the_target = with_scope(:find => @scope[:find]) do
- @reflection.klass.find(:first, options)
- end
- set_inverse_instance(the_target, @owner)
- the_target
- end
-
- def construct_find_scope
- if @reflection.options[:as]
- sql =
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_id = #{owner_quoted_id} AND " +
- "#{@reflection.quoted_table_name}.#{@reflection.options[:as]}_type = #{@owner.class.quote_value(@owner.class.base_class.name.to_s)}"
- else
- sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
- end
- sql << " AND (#{conditions})" if conditions
- { :conditions => sql }
- end
+ alias creation_attributes construct_owner_attributes
- def construct_create_scope
- create_scoping = {}
- set_belongs_to_association_for(create_scoping)
- create_scoping
+ # The reason that the save param for replace is false, if for create (not just build),
+ # is because the setting of the foreign keys is actually handled by the scoping when
+ # the record is instantiated, and so they are set straight away and do not need to be
+ # updated within replace.
+ def set_new_record(record)
+ replace(record, false)
end
- def new_record(replace_existing)
- # Make sure we load the target first, if we plan on replacing the existing
- # instance. Otherwise, if the target has not previously been loaded
- # elsewhere, the instance we create will get orphaned.
- load_target if replace_existing
- record = @reflection.klass.send(:with_scope, :create => @scope[:create]) do
- yield @reflection
- end
-
- if replace_existing
- replace(record, true)
+ def remove_target!(method)
+ if [:delete, :destroy].include?(method)
+ target.send(method)
else
- record[@reflection.primary_key_name] = @owner.id if @owner.persisted?
- self.target = record
- set_inverse_instance(record, @owner)
- end
+ nullify_owner_attributes(target)
- record
- end
-
- def we_can_set_the_inverse_on_this?(record)
- inverse = @reflection.inverse_of
- return !inverse.nil?
+ 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
+ end
end
- def merge_with_conditions(attrs={})
- attrs ||= {}
- attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
- attrs
+ def nullify_owner_attributes(record)
+ record[reflection.foreign_key] = nil
end
end
end
diff --git a/activerecord/lib/active_record/associations/has_one_through_association.rb b/activerecord/lib/active_record/associations/has_one_through_association.rb
index e9dc32efd3..fdf8ae1453 100644
--- a/activerecord/lib/active_record/associations/has_one_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_through_association.rb
@@ -1,42 +1,36 @@
-require "active_record/associations/through_association_scope"
-
module ActiveRecord
# = Active Record Has One Through Association
module Associations
- class HasOneThroughAssociation < HasOneAssociation
- include ThroughAssociationScope
+ class HasOneThroughAssociation < HasOneAssociation #:nodoc:
+ include ThroughAssociation
- def replace(new_value)
- create_through_record(new_value)
- @target = new_value
+ def replace(record)
+ create_through_record(record)
+ self.target = record
end
private
- def create_through_record(new_value) #nodoc:
- ensure_not_nested
+ def create_through_record(record)
+ ensure_not_nested
- klass = @reflection.through_reflection.klass
+ through_proxy = owner.association(through_reflection.name)
+ through_record = through_proxy.send(:load_target)
- current_object = @owner.send(@reflection.through_reflection.name)
+ if through_record && !record
+ through_record.destroy
+ elsif record
+ attributes = construct_join_attributes(record)
- if current_object
- new_value ? current_object.update_attributes(construct_join_attributes(new_value)) : current_object.destroy
- elsif new_value
- if @owner.new_record?
- self.target = new_value
- through_association = @owner.send(:association_instance_get, @reflection.through_reflection.name)
- through_association.build(construct_join_attributes(new_value))
- else
- @owner.send(@reflection.through_reflection.name, klass.create(construct_join_attributes(new_value)))
+ if through_record
+ through_record.update_attributes(attributes)
+ elsif owner.new_record?
+ through_proxy.build(attributes)
+ else
+ through_proxy.create(attributes)
+ end
end
end
- end
-
- private
- def find_target
- with_scope(@scope) { @reflection.klass.find(:first) }
- end
end
end
end
diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb
new file mode 100644
index 0000000000..504f25271c
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency.rb
@@ -0,0 +1,215 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ autoload :JoinPart, 'active_record/associations/join_dependency/join_part'
+ autoload :JoinBase, 'active_record/associations/join_dependency/join_base'
+ autoload :JoinAssociation, 'active_record/associations/join_dependency/join_association'
+
+ attr_reader :join_parts, :reflections, :alias_tracker, :active_record
+
+ def initialize(base, associations, joins)
+ @active_record = base
+ @table_joins = joins
+ @join_parts = [JoinBase.new(base)]
+ @associations = {}
+ @reflections = []
+ @alias_tracker = AliasTracker.new(joins)
+ @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
+ build(associations)
+ end
+
+ def graft(*associations)
+ associations.each do |association|
+ join_associations.detect {|a| association == a} ||
+ build(association.reflection.name, association.find_parent_in(self) || join_base, association.join_type)
+ end
+ self
+ end
+
+ def join_associations
+ join_parts.last(join_parts.length - 1)
+ end
+
+ def join_base
+ join_parts.first
+ end
+
+ def columns
+ join_parts.collect { |join_part|
+ table = join_part.aliased_table
+ join_part.column_names_with_alias.collect{ |column_name, aliased_name|
+ table[column_name].as Arel.sql(aliased_name)
+ }
+ }.flatten
+ end
+
+ def instantiate(rows)
+ primary_key = join_base.aliased_primary_key
+ parents = {}
+
+ records = rows.map { |model|
+ primary_id = model[primary_key]
+ parent = parents[primary_id] ||= join_base.instantiate(model)
+ construct(parent, @associations, join_associations, model)
+ parent
+ }.uniq
+
+ remove_duplicate_results!(active_record, records, @associations)
+ records
+ end
+
+ def remove_duplicate_results!(base, records, associations)
+ case associations
+ when Symbol, String
+ reflection = base.reflections[associations]
+ remove_uniq_by_reflection(reflection, records)
+ when Array
+ associations.each do |association|
+ remove_duplicate_results!(base, records, association)
+ end
+ when Hash
+ associations.keys.each do |name|
+ reflection = base.reflections[name]
+ remove_uniq_by_reflection(reflection, records)
+
+ parent_records = []
+ records.each do |record|
+ if descendant = record.send(reflection.name)
+ if reflection.collection?
+ parent_records.concat descendant.target.uniq
+ else
+ parent_records << descendant
+ end
+ end
+ end
+
+ remove_duplicate_results!(reflection.klass, parent_records, associations[name]) unless parent_records.empty?
+ end
+ end
+ end
+
+ protected
+
+ def cache_joined_association(association)
+ associations = []
+ parent = association.parent
+ while parent != join_base
+ associations.unshift(parent.reflection.name)
+ parent = parent.parent
+ end
+ ref = @associations
+ associations.each do |key|
+ ref = ref[key]
+ end
+ ref[association.reflection.name] ||= {}
+ end
+
+ def build(associations, parent = nil, join_type = Arel::InnerJoin)
+ parent ||= join_parts.last
+ case associations
+ when Symbol, String
+ reflection = parent.reflections[associations.to_s.intern] or
+ raise ConfigurationError, "Association named '#{ associations }' was not found; perhaps you misspelled it?"
+ unless join_association = find_join_association(reflection, parent)
+ @reflections << reflection
+ join_association = build_join_association(reflection, parent)
+ join_association.join_type = join_type
+ @join_parts << join_association
+ cache_joined_association(join_association)
+ end
+ join_association
+ when Array
+ associations.each do |association|
+ build(association, parent, join_type)
+ end
+ when Hash
+ associations.keys.sort_by { |a| a.to_s }.each do |name|
+ join_association = build(name, parent, join_type)
+ build(associations[name], join_association, join_type)
+ end
+ else
+ raise ConfigurationError, associations.inspect
+ end
+ end
+
+ def find_join_association(name_or_reflection, parent)
+ if String === name_or_reflection
+ name_or_reflection = name_or_reflection.to_sym
+ end
+
+ join_associations.detect { |j|
+ j.reflection == name_or_reflection && j.parent == parent
+ }
+ end
+
+ def remove_uniq_by_reflection(reflection, records)
+ if reflection && reflection.collection?
+ records.each { |record| record.send(reflection.name).target.uniq! }
+ end
+ end
+
+ def build_join_association(reflection, parent)
+ JoinAssociation.new(reflection, self, parent)
+ end
+
+ def construct(parent, associations, join_parts, row)
+ case associations
+ when Symbol, String
+ name = associations.to_s
+
+ join_part = join_parts.detect { |j|
+ j.reflection.name.to_s == name &&
+ j.parent_table_name == parent.class.table_name }
+
+ raise(ConfigurationError, "No such association") unless join_part
+
+ join_parts.delete(join_part)
+ construct_association(parent, join_part, row)
+ when Array
+ associations.each do |association|
+ construct(parent, association, join_parts, row)
+ end
+ when Hash
+ associations.sort_by { |k,_| k.to_s }.each do |association_name, assoc|
+ association = construct(parent, association_name, join_parts, row)
+ construct(association, assoc, join_parts, row) if association
+ end
+ else
+ raise ConfigurationError, associations.inspect
+ end
+ end
+
+ def construct_association(record, join_part, row)
+ return if record.id.to_s != join_part.parent.record_id(row).to_s
+
+ macro = join_part.reflection.macro
+ if macro == :has_one
+ return if record.association_cache.key?(join_part.reflection.name)
+ association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil?
+ set_target_and_inverse(join_part, association, record)
+ else
+ return if row[join_part.aliased_primary_key].nil?
+ association = join_part.instantiate(row)
+ case macro
+ when :has_many, :has_and_belongs_to_many
+ other = record.association(join_part.reflection.name)
+ other.loaded!
+ other.target.push(association)
+ other.set_inverse_instance(association)
+ when :belongs_to
+ set_target_and_inverse(join_part, association, record)
+ else
+ raise ConfigurationError, "unknown macro: #{join_part.reflection.macro}"
+ end
+ end
+ association
+ end
+
+ def set_target_and_inverse(join_part, association, record)
+ other = record.association(join_part.reflection.name)
+ other.target = association
+ other.set_inverse_instance(association)
+ end
+ 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
new file mode 100644
index 0000000000..890e77fca9
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -0,0 +1,259 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ class JoinAssociation < JoinPart # :nodoc:
+ # The reflection of the association represented
+ attr_reader :reflection
+
+ # The JoinDependency object which this JoinAssociation exists within. This is mainly
+ # relevant for generating aliases which do not conflict with other joins which are
+ # part of the query.
+ attr_reader :join_dependency
+
+ # A JoinBase instance representing the active record we are joining onto.
+ # (So in Author.has_many :posts, the Author would be that base record.)
+ attr_reader :parent
+
+ # What type of join will be generated, either Arel::InnerJoin (default) or Arel::OuterJoin
+ attr_accessor :join_type
+
+ # These implement abstract methods from the superclass
+ attr_reader :aliased_prefix
+
+ attr_reader :tables
+
+ delegate :options, :through_reflection, :source_reflection, :through_reflection_chain, :to => :reflection
+ delegate :table, :table_name, :to => :parent, :prefix => :parent
+ delegate :alias_tracker, :to => :join_dependency
+
+ def initialize(reflection, join_dependency, parent = nil)
+ reflection.check_validity!
+
+ if reflection.options[:polymorphic]
+ raise EagerLoadPolymorphicError.new(reflection)
+ end
+
+ super(reflection.klass)
+
+ @reflection = reflection
+ @join_dependency = join_dependency
+ @parent = parent
+ @join_type = Arel::InnerJoin
+ @aliased_prefix = "t#{ join_dependency.join_parts.size }"
+
+ setup_tables
+ end
+
+ def ==(other)
+ other.class == self.class &&
+ other.reflection == reflection &&
+ other.parent == parent
+ end
+
+ def find_parent_in(other_join_dependency)
+ other_join_dependency.join_parts.detect do |join_part|
+ parent == join_part
+ end
+ end
+
+ def join_to(relation)
+ # The chain starts with the target table, but we want to end with it here (makes
+ # more sense in this context)
+ chain = through_reflection_chain.reverse
+
+ foreign_table = parent_table
+ index = 0
+
+ chain.each do |reflection|
+ table = tables[index]
+ conditions = []
+
+ if reflection.source_reflection.nil?
+ case reflection.macro
+ when :belongs_to
+ key = reflection.association_primary_key
+ foreign_key = reflection.foreign_key
+ when :has_many, :has_one
+ key = reflection.foreign_key
+ foreign_key = reflection.active_record_primary_key
+
+ conditions << polymorphic_conditions(reflection, table)
+ when :has_and_belongs_to_many
+ # For habtm, we need to deal with the join table at the same time as the
+ # target table (because unlike a :through association, there is no reflection
+ # to represent the join table)
+ table, join_table = table
+
+ join_key = reflection.foreign_key
+ join_foreign_key = reflection.active_record.primary_key
+
+ relation = relation.join(join_table, join_type).on(
+ join_table[join_key].
+ eq(foreign_table[join_foreign_key])
+ )
+
+ # We've done the first join now, so update the foreign_table for the second
+ foreign_table = join_table
+
+ key = reflection.klass.primary_key
+ foreign_key = reflection.association_foreign_key
+ end
+ else
+ case reflection.source_reflection.macro
+ when :belongs_to
+ key = reflection.association_primary_key
+ foreign_key = reflection.foreign_key
+
+ conditions << source_type_conditions(reflection, foreign_table)
+ when :has_many, :has_one
+ key = reflection.foreign_key
+ foreign_key = reflection.source_reflection.active_record_primary_key
+ when :has_and_belongs_to_many
+ table, join_table = table
+
+ join_key = reflection.foreign_key
+ join_foreign_key = reflection.klass.primary_key
+
+ relation = relation.join(join_table, join_type).on(
+ join_table[join_key].
+ eq(foreign_table[join_foreign_key])
+ )
+
+ foreign_table = join_table
+
+ key = reflection.klass.primary_key
+ foreign_key = reflection.association_foreign_key
+ end
+ end
+
+ conditions << table[key].eq(foreign_table[foreign_key])
+
+ conditions << reflection_conditions(index, table)
+ conditions << sti_conditions(reflection, table)
+
+ ands = relation.create_and(conditions.flatten.compact)
+
+ join = relation.create_join(
+ table,
+ relation.create_on(ands),
+ join_type)
+
+ relation = relation.from(join)
+
+ # The current table in this iteration becomes the foreign table in the next
+ foreign_table = table
+ index += 1
+ end
+
+ relation
+ end
+
+ def join_relation(joining_relation)
+ self.join_type = Arel::OuterJoin
+ joining_relation.joins(self)
+ end
+
+ def table
+ if tables.last.is_a?(Array)
+ tables.last.first
+ else
+ tables.last
+ end
+ end
+
+ def aliased_table_name
+ table.table_alias || table.name
+ end
+
+ protected
+
+ def table_alias_for(reflection, join = false)
+ name = alias_tracker.pluralize(reflection.name)
+ name << "_#{parent_table_name}"
+ name << "_join" if join
+ name
+ end
+
+ private
+
+ # Generate aliases and Arel::Table instances for each of the tables which we will
+ # later generate joins for. We must do this in advance in order to correctly allocate
+ # the proper alias.
+ def setup_tables
+ @tables = through_reflection_chain.map do |reflection|
+ table = alias_tracker.aliased_table_for(
+ reflection.table_name,
+ table_alias_for(reflection, reflection != self.reflection)
+ )
+
+ # For habtm, we have two Arel::Table instances related to a single reflection, so
+ # we just store them as a pair in the array.
+ if reflection.macro == :has_and_belongs_to_many ||
+ (reflection.source_reflection && reflection.source_reflection.macro == :has_and_belongs_to_many)
+
+ join_table = alias_tracker.aliased_table_for(
+ (reflection.source_reflection || reflection).options[:join_table],
+ table_alias_for(reflection, true)
+ )
+
+ [table, join_table]
+ else
+ table
+ end
+ end
+
+ # The joins are generated from the through_reflection_chain in reverse order, so
+ # reverse the tables too (but it's important to generate the aliases in the 'forward'
+ # order, which is why we only do the reversal now.
+ @tables.reverse!
+ end
+
+ def process_conditions(conditions, table_name)
+ if conditions.respond_to?(:to_proc)
+ conditions = instance_eval(&conditions)
+ end
+
+ Arel.sql(sanitize_sql(conditions, table_name))
+ end
+
+ def sanitize_sql(condition, table_name)
+ active_record.send(:sanitize_sql, condition, table_name)
+ end
+
+ def reflection_conditions(index, table)
+ reflection.through_conditions.reverse[index].map do |condition|
+ process_conditions(condition, table.table_alias || table.name)
+ end
+ end
+
+ def sti_conditions(reflection, table)
+ unless reflection.klass.descends_from_active_record?
+ sti_column = table[reflection.klass.inheritance_column]
+ sti_condition = sti_column.eq(reflection.klass.sti_name)
+ subclasses = reflection.klass.descendants
+
+ # TODO: use IN (...), or possibly AR::Base#type_condition
+ subclasses.inject(sti_condition) { |attr,subclass|
+ attr.or(sti_column.eq(subclass.sti_name))
+ }
+ end
+ end
+
+ def source_type_conditions(reflection, foreign_table)
+ if reflection.options[:source_type]
+ foreign_table[reflection.source_reflection.foreign_type].
+ eq(reflection.options[:source_type])
+ end
+ end
+
+ def polymorphic_conditions(reflection, table)
+ if reflection.options[:as]
+ table[reflection.type].
+ eq(reflection.active_record.base_class.name)
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_base.rb b/activerecord/lib/active_record/associations/join_dependency/join_base.rb
new file mode 100644
index 0000000000..3920e84976
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_base.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ class JoinBase < JoinPart # :nodoc:
+ def ==(other)
+ other.class == self.class &&
+ other.active_record == active_record
+ end
+
+ def aliased_prefix
+ "t0"
+ end
+
+ def table
+ Arel::Table.new(table_name, arel_engine)
+ end
+
+ def aliased_table_name
+ active_record.table_name
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_part.rb b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
new file mode 100644
index 0000000000..3279e56e7d
--- /dev/null
+++ b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
@@ -0,0 +1,78 @@
+module ActiveRecord
+ module Associations
+ class JoinDependency # :nodoc:
+ # A JoinPart represents a part of a JoinDependency. It is an abstract class, inherited
+ # by JoinBase and JoinAssociation. A JoinBase represents the Active Record which
+ # everything else is being joined onto. A JoinAssociation represents an association which
+ # is joining to the base. A JoinAssociation may result in more than one actual join
+ # operations (for example a has_and_belongs_to_many JoinAssociation would result in
+ # two; one for the join table and one for the target table).
+ class JoinPart # :nodoc:
+ # The Active Record class which this join part is associated 'about'; for a JoinBase
+ # this is the actual base model, for a JoinAssociation this is the target model of the
+ # association.
+ attr_reader :active_record
+
+ delegate :table_name, :column_names, :primary_key, :reflections, :arel_engine, :to => :active_record
+
+ def initialize(active_record)
+ @active_record = active_record
+ @cached_record = {}
+ @column_names_with_alias = nil
+ end
+
+ def aliased_table
+ Arel::Nodes::TableAlias.new aliased_table_name, table
+ end
+
+ def ==(other)
+ raise NotImplementedError
+ end
+
+ # An Arel::Table for the active_record
+ def table
+ raise NotImplementedError
+ end
+
+ # The prefix to be used when aliasing columns in the active_record's table
+ def aliased_prefix
+ raise NotImplementedError
+ end
+
+ # The alias for the active_record's table
+ def aliased_table_name
+ raise NotImplementedError
+ end
+
+ # The alias for the primary key of the active_record's table
+ def aliased_primary_key
+ "#{aliased_prefix}_r0"
+ end
+
+ # An array of [column_name, alias] pairs for the table
+ def column_names_with_alias
+ unless @column_names_with_alias
+ @column_names_with_alias = []
+
+ ([primary_key] + (column_names - [primary_key])).each_with_index do |column_name, i|
+ @column_names_with_alias << [column_name, "#{aliased_prefix}_r#{i}"]
+ end
+ end
+ @column_names_with_alias
+ end
+
+ def extract_record(row)
+ Hash[column_names_with_alias.map{|cn, an| [cn, row[an]]}]
+ end
+
+ def record_id(row)
+ row[aliased_primary_key]
+ end
+
+ def instantiate(row)
+ @cached_record[record_id(row)] ||= active_record.send(:instantiate, extract_record(row))
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
new file mode 100644
index 0000000000..fafed94ff2
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -0,0 +1,177 @@
+module ActiveRecord
+ module Associations
+ # Implements the details of eager loading of Active Record associations.
+ #
+ # Note that 'eager loading' and 'preloading' are actually the same thing.
+ # However, there are two different eager loading strategies.
+ #
+ # The first one is by using table joins. This was only strategy available
+ # prior to Rails 2.1. Suppose that you have an Author model with columns
+ # 'name' and 'age', and a Book model with columns 'name' and 'sales'. Using
+ # this strategy, Active Record would try to retrieve all data for an author
+ # and all of its books via a single query:
+ #
+ # SELECT * FROM authors
+ # LEFT OUTER JOIN books ON authors.id = books.id
+ # WHERE authors.name = 'Ken Akamatsu'
+ #
+ # However, this could result in many rows that contain redundant data. After
+ # having received the first row, we already have enough data to instantiate
+ # the Author object. In all subsequent rows, only the data for the joined
+ # 'books' table is useful; the joined 'authors' data is just redundant, and
+ # processing this redundant data takes memory and CPU time. The problem
+ # quickly becomes worse and worse as the level of eager loading increases
+ # (i.e. if Active Record is to eager load the associations' associations as
+ # well).
+ #
+ # The second strategy is to use multiple database queries, one for each
+ # level of association. Since Rails 2.1, this is the default strategy. In
+ # situations where a table join is necessary (e.g. when the +:conditions+
+ # option references an association's column), it will fallback to the table
+ # join strategy.
+ class Preloader #:nodoc:
+ autoload :Association, 'active_record/associations/preloader/association'
+ autoload :SingularAssociation, 'active_record/associations/preloader/singular_association'
+ autoload :CollectionAssociation, 'active_record/associations/preloader/collection_association'
+ autoload :ThroughAssociation, 'active_record/associations/preloader/through_association'
+
+ autoload :HasMany, 'active_record/associations/preloader/has_many'
+ autoload :HasManyThrough, 'active_record/associations/preloader/has_many_through'
+ autoload :HasOne, 'active_record/associations/preloader/has_one'
+ autoload :HasOneThrough, 'active_record/associations/preloader/has_one_through'
+ 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
+
+ # Eager loads the named associations for the given Active Record record(s).
+ #
+ # In this description, 'association name' shall refer to the name passed
+ # to an association creation method. For example, a model that specifies
+ # <tt>belongs_to :author</tt>, <tt>has_many :buyers</tt> has association
+ # names +:author+ and +:buyers+.
+ #
+ # == Parameters
+ # +records+ is an array of ActiveRecord::Base. This array needs not be flat,
+ # i.e. +records+ itself may also contain arrays of records. In any case,
+ # +preload_associations+ will preload the all associations records by
+ # flattening +records+.
+ #
+ # +associations+ specifies one or more associations that you want to
+ # preload. It may be:
+ # - a Symbol or a String which specifies a single association name. For
+ # example, specifying +:books+ allows this method to preload all books
+ # for an Author.
+ # - an Array which specifies multiple association names. This array
+ # is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
+ # allows this method to preload an author's avatar as well as all of his
+ # books.
+ # - a Hash which specifies multiple association names, as well as
+ # association names for the to-be-preloaded association objects. For
+ # example, specifying <tt>{ :author => :avatar }</tt> will preload a
+ # book's author, as well as that author's avatar.
+ #
+ # +:associations+ has the same format as the +:include+ option for
+ # <tt>ActiveRecord::Base.find</tt>. So +associations+ could look like this:
+ #
+ # :books
+ # [ :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
+ end
+
+ def run
+ unless records.empty?
+ associations.each { |association| preload(association) }
+ end
+ end
+
+ private
+
+ def preload(association)
+ case association
+ when Hash
+ preload_hash(association)
+ when String, Symbol
+ preload_one(association.to_sym)
+ else
+ raise ArgumentError, "#{association.inspect} was not recognised for preload"
+ end
+ end
+
+ def preload_hash(association)
+ association.each do |parent, child|
+ Preloader.new(records, parent, options).run
+ Preloader.new(records.map { |record| record.send(parent) }.flatten, child).run
+ end
+ end
+
+ # Not all records have the same class, so group then preload group on the reflection
+ # itself so that if various subclass share the same association then we do not split
+ # them unnecessarily
+ #
+ # Additionally, polymorphic belongs_to associations can have multiple associated
+ # classes, depending on the polymorphic_type field. So we group by the classes as
+ # well.
+ 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
+ end
+ end
+ end
+
+ def grouped_records(association)
+ Hash[
+ records_by_reflection(association).map do |reflection, records|
+ [reflection, records.group_by { |record| association_klass(reflection, record) }]
+ end
+ ]
+ end
+
+ def records_by_reflection(association)
+ records.group_by do |record|
+ reflection = record.class.reflections[association]
+
+ unless reflection
+ raise ActiveRecord::ConfigurationError, "Association named '#{association}' was not found; " \
+ "perhaps you misspelled it?"
+ end
+
+ reflection
+ end
+ end
+
+ def association_klass(reflection, record)
+ if reflection.macro == :belongs_to && reflection.options[:polymorphic]
+ klass = record.send(reflection.foreign_type)
+ klass && klass.constantize
+ else
+ reflection.klass
+ end
+ end
+
+ def preloader_for(reflection)
+ case reflection.macro
+ when :has_many
+ reflection.options[:through] ? HasManyThrough : HasMany
+ when :has_one
+ reflection.options[:through] ? HasOneThrough : HasOne
+ when :has_and_belongs_to_many
+ HasAndBelongsToMany
+ when :belongs_to
+ BelongsTo
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
new file mode 100644
index 0000000000..7256dd5288
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -0,0 +1,126 @@
+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
+ end
+
+ def run
+ unless owners.first.association(reflection.name).loaded?
+ preload
+ end
+ end
+
+ def preload
+ raise NotImplementedError
+ end
+
+ def scoped
+ @scoped ||= build_scope
+ end
+
+ def records_for(ids)
+ scoped.where(association_key.in(ids))
+ end
+
+ def table
+ klass.arel_table
+ end
+
+ # The name of the key on the associated records
+ def association_key_name
+ raise NotImplementedError
+ end
+
+ # This is overridden by HABTM as the condition should be on the foreign_key column in
+ # the join table
+ def association_key
+ table[association_key_name]
+ end
+
+ # The name of the key on the model which declares the association
+ def owner_key_name
+ raise NotImplementedError
+ end
+
+ # We're converting to a string here because postgres will return the aliased association
+ # key in a habtm as a string (for whatever reason)
+ def owners_by_key
+ @owners_by_key ||= owners.group_by do |owner|
+ key = owner[owner_key_name]
+ key && key.to_s
+ end
+ end
+
+ def options
+ reflection.options
+ end
+
+ private
+
+ def associated_records_by_owner
+ owner_keys = owners.map { |owner| owner[owner_key_name] }.compact.uniq
+
+ if klass.nil? || owner_keys.empty?
+ records = []
+ else
+ # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
+ # Make several smaller queries if necessary or make one query if the adapter supports it
+ sliced = owner_keys.each_slice(model.connection.in_clause_length || owner_keys.size)
+ records = sliced.map { |slice| records_for(slice) }.flatten
+ end
+
+ # Each record may have multiple owners, and vice-versa
+ records_by_owner = Hash[owners.map { |owner| [owner, []] }]
+ records.each do |record|
+ owner_key = record[association_key_name].to_s
+
+ owners_by_key[owner_key].each do |owner|
+ records_by_owner[owner] << record
+ end
+ end
+ records_by_owner
+ end
+
+ def build_scope
+ scope = klass.scoped
+
+ scope = scope.where(process_conditions(options[:conditions]))
+ scope = scope.where(process_conditions(preload_options[:conditions]))
+
+ scope = scope.select(preload_options[:select] || options[:select] || table[Arel.star])
+ scope = scope.includes(preload_options[:include] || options[:include])
+
+ if options[:as]
+ scope = scope.where(
+ klass.table_name => {
+ reflection.type => model.base_class.sti_name
+ }
+ )
+ end
+
+ scope
+ end
+
+ def process_conditions(conditions)
+ if conditions.respond_to?(:to_proc)
+ conditions = klass.send(:instance_eval, &conditions)
+ end
+
+ if conditions
+ klass.send(:sanitize_sql, conditions)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/belongs_to.rb b/activerecord/lib/active_record/associations/preloader/belongs_to.rb
new file mode 100644
index 0000000000..5091d4717a
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/belongs_to.rb
@@ -0,0 +1,17 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class BelongsTo < SingularAssociation #:nodoc:
+
+ def association_key_name
+ reflection.options[:primary_key] || klass && klass.primary_key
+ end
+
+ def owner_key_name
+ reflection.foreign_key
+ 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
new file mode 100644
index 0000000000..c248aeaaf6
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/collection_association.rb
@@ -0,0 +1,24 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class CollectionAssociation < Association #:nodoc:
+
+ private
+
+ def build_scope
+ super.order(preload_options[:order] || options[:order])
+ end
+
+ def preload
+ associated_records_by_owner.each do |owner, records|
+ association = owner.association(reflection.name)
+ association.loaded!
+ association.target.concat(records)
+ records.each { |record| association.set_inverse_instance(record) }
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
new file mode 100644
index 0000000000..e794f05340
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
@@ -0,0 +1,58 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasAndBelongsToMany < CollectionAssociation #:nodoc:
+ attr_reader :join_table
+
+ def initialize(klass, records, reflection, preload_options)
+ super
+ @join_table = Arel::Table.new(options[:join_table]).alias('t0')
+ end
+
+ # Unlike the other associations, we want to get a raw array of rows so that we can
+ # access the aliased column on the join table
+ def records_for(ids)
+ scope = super
+ klass.connection.select_all(scope.arel.to_sql, 'SQL', scope.bind_values)
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ def association_key_name
+ 'ar_association_key_name'
+ end
+
+ def association_key
+ join_table[reflection.foreign_key]
+ end
+
+ private
+
+ # Once we have used the join table column (in super), we manually instantiate the
+ # actual records
+ def associated_records_by_owner
+ super.each do |owner_key, rows|
+ rows.map! { |row| klass.instantiate(row) }
+ end
+ end
+
+ def build_scope
+ super.joins(join).select(join_select)
+ end
+
+ def join_select
+ association_key.as(Arel.sql(association_key_name))
+ end
+
+ def join
+ condition = table[reflection.association_primary_key].eq(
+ join_table[reflection.association_foreign_key])
+
+ table.create_join(join_table, table.create_on(condition))
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_many.rb b/activerecord/lib/active_record/associations/preloader/has_many.rb
new file mode 100644
index 0000000000..3ea91a8c11
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_many.rb
@@ -0,0 +1,17 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasMany < CollectionAssociation #:nodoc:
+
+ def association_key_name
+ reflection.foreign_key
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
new file mode 100644
index 0000000000..c6e9ede356
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
@@ -0,0 +1,15 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasManyThrough < CollectionAssociation #:nodoc:
+ include ThroughAssociation
+
+ def associated_records_by_owner
+ super.each do |owner, records|
+ records.uniq! if options[:uniq]
+ end
+ end
+ end
+ 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
new file mode 100644
index 0000000000..848448bb48
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_one.rb
@@ -0,0 +1,23 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasOne < SingularAssociation #:nodoc:
+
+ def association_key_name
+ reflection.foreign_key
+ end
+
+ def owner_key_name
+ reflection.active_record_primary_key
+ end
+
+ private
+
+ def build_scope
+ super.order(preload_options[:order] || options[:order])
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/has_one_through.rb b/activerecord/lib/active_record/associations/preloader/has_one_through.rb
new file mode 100644
index 0000000000..f063f85574
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/has_one_through.rb
@@ -0,0 +1,9 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class HasOneThrough < SingularAssociation #:nodoc:
+ include ThroughAssociation
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/singular_association.rb b/activerecord/lib/active_record/associations/preloader/singular_association.rb
new file mode 100644
index 0000000000..44e804d785
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/singular_association.rb
@@ -0,0 +1,21 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ class SingularAssociation < Association #:nodoc:
+
+ private
+
+ def preload
+ associated_records_by_owner.each do |owner, associated_records|
+ record = associated_records.first
+
+ association = owner.association(reflection.name)
+ association.target = record
+ association.set_inverse_instance(record)
+ end
+ end
+
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
new file mode 100644
index 0000000000..ad6374d09a
--- /dev/null
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -0,0 +1,67 @@
+module ActiveRecord
+ module Associations
+ class Preloader
+ module ThroughAssociation #:nodoc:
+
+ def through_reflection
+ reflection.through_reflection
+ end
+
+ def source_reflection
+ reflection.source_reflection
+ end
+
+ def associated_records_by_owner
+ through_records = through_records_by_owner
+
+ ActiveRecord::Associations::Preloader.new(
+ through_records.values.flatten,
+ source_reflection.name, options
+ ).run
+
+ through_records.each do |owner, records|
+ records.map! { |r| r.send(source_reflection.name) }.flatten!
+ records.compact!
+ end
+ end
+
+ private
+
+ def through_records_by_owner
+ ActiveRecord::Associations::Preloader.new(
+ owners, through_reflection.name,
+ through_options
+ ).run
+
+ Hash[owners.map do |owner|
+ through_records = Array.wrap(owner.send(through_reflection.name))
+
+ # Dont cache the association - we would only be caching a subset
+ if reflection.options[:source_type] && through_reflection.collection?
+ owner.association(through_reflection.name).reset
+ end
+
+ [owner, through_records]
+ end]
+ end
+
+ def through_options
+ through_options = {}
+
+ if options[:source_type]
+ through_options[:conditions] = { reflection.foreign_type => options[:source_type] }
+ else
+ if options[:conditions]
+ through_options[:include] = options[:include] || options[:source]
+ through_options[:conditions] = options[:conditions]
+ end
+
+ through_options[:order] = options[:order]
+ end
+
+ through_options
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
new file mode 100644
index 0000000000..0d8e45adb5
--- /dev/null
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -0,0 +1,55 @@
+module ActiveRecord
+ module Associations
+ class SingularAssociation < Association #:nodoc:
+ # Implements the reader method, e.g. foo.bar for Foo.has_one :bar
+ def reader(force_reload = false)
+ if force_reload
+ klass.uncached { reload }
+ elsif !loaded? || stale_target?
+ reload
+ end
+
+ target
+ end
+
+ # Implements the writer method, e.g. foo.items= for Foo.has_many :items
+ def writer(record)
+ replace(record)
+ end
+
+ def create(attributes = {})
+ new_record(:create, attributes)
+ end
+
+ def create!(attributes = {})
+ build(attributes).tap { |record| record.save! }
+ end
+
+ def build(attributes = {})
+ new_record(:build, attributes)
+ end
+
+ private
+
+ def find_target
+ scoped.first.tap { |record| set_inverse_instance(record) }
+ end
+
+ # Implemented by subclasses
+ def replace(record)
+ raise NotImplementedError
+ end
+
+ def set_new_record(record)
+ replace(record)
+ end
+
+ def new_record(method, attributes)
+ attributes = scoped.scope_for_create.merge(attributes || {})
+ record = reflection.send("#{method}_association", attributes)
+ set_new_record(record)
+ record
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb
new file mode 100644
index 0000000000..ed24373cba
--- /dev/null
+++ b/activerecord/lib/active_record/associations/through_association.rb
@@ -0,0 +1,281 @@
+require 'enumerator'
+
+module ActiveRecord
+ # = Active Record Through Association
+ module Associations
+ module ThroughAssociation #:nodoc:
+
+ delegate :source_options, :through_options, :source_reflection, :through_reflection,
+ :through_reflection_chain, :through_conditions, :to => :reflection
+
+ protected
+
+ def target_scope
+ super.merge(through_reflection.klass.scoped)
+ end
+
+ def association_scope
+ scope = super.joins(construct_joins)
+ scope = scope.where(reflection_conditions(0))
+
+ unless options[:include]
+ scope = scope.includes(source_options[:include])
+ end
+
+ scope
+ end
+
+ private
+
+ # This scope affects the creation of the associated records (not the join records). At the
+ # moment we only support creating on a :through association when the source reflection is a
+ # belongs_to. Thus it's not necessary to set a foreign key on the associated record(s), so
+ # this scope has can legitimately be empty.
+ def creation_attributes
+ { }
+ end
+
+ # TODO: Needed?
+ def aliased_through_table
+ name = through_reflection.table_name
+
+ reflection.table_name == name ?
+ through_reflection.klass.arel_table.alias(name + "_join") :
+ through_reflection.klass.arel_table
+ end
+
+ def construct_owner_conditions
+ reflection = through_reflection_chain.last
+
+ if reflection.macro == :has_and_belongs_to_many
+ table = tables[reflection].first
+ else
+ table = Array.wrap(tables[reflection]).first
+ end
+
+ super(table, reflection)
+ end
+
+ def construct_joins
+ joins, right_index = [], 1
+
+ # Iterate over each pair in the through reflection chain, joining them together
+ through_reflection_chain.each_cons(2) do |left, right|
+ left_table, right_table = tables[left], tables[right]
+
+ if left.source_reflection.nil?
+ case left.macro
+ when :belongs_to
+ joins << inner_join(
+ right_table,
+ left_table[left.association_primary_key],
+ right_table[left.foreign_key],
+ reflection_conditions(right_index)
+ )
+ when :has_many, :has_one
+ joins << inner_join(
+ right_table,
+ left_table[left.foreign_key],
+ right_table[right.association_primary_key],
+ polymorphic_conditions(left, left),
+ reflection_conditions(right_index)
+ )
+ when :has_and_belongs_to_many
+ joins << inner_join(
+ right_table,
+ left_table.first[left.foreign_key],
+ right_table[right.klass.primary_key],
+ reflection_conditions(right_index)
+ )
+ end
+ else
+ case left.source_reflection.macro
+ when :belongs_to
+ joins << inner_join(
+ right_table,
+ left_table[left.association_primary_key],
+ right_table[left.foreign_key],
+ source_type_conditions(left),
+ reflection_conditions(right_index)
+ )
+ when :has_many, :has_one
+ if right.macro == :has_and_belongs_to_many
+ join_table, right_table = tables[right]
+ end
+
+ joins << inner_join(
+ right_table,
+ left_table[left.foreign_key],
+ right_table[left.source_reflection.active_record_primary_key],
+ polymorphic_conditions(left, left.source_reflection),
+ reflection_conditions(right_index)
+ )
+
+ if right.macro == :has_and_belongs_to_many
+ joins << inner_join(
+ join_table,
+ right_table[right.klass.primary_key],
+ join_table[right.association_foreign_key]
+ )
+ end
+ when :has_and_belongs_to_many
+ join_table, left_table = tables[left]
+
+ joins << inner_join(
+ join_table,
+ left_table[left.klass.primary_key],
+ join_table[left.association_foreign_key]
+ )
+
+ joins << inner_join(
+ right_table,
+ join_table[left.foreign_key],
+ right_table[right.klass.primary_key],
+ reflection_conditions(right_index)
+ )
+ end
+ end
+
+ right_index += 1
+ end
+
+ joins
+ end
+
+ # Construct attributes for :through pointing to owner and associate. This is used by the
+ # methods which create and delete records on the association.
+ #
+ # We only support indirectly modifying through associations which has a belongs_to source.
+ # This is the "has_many :tags, :through => :taggings" situation, where the join model
+ # typically has a belongs_to on both side. In other words, associations which could also
+ # be represented as has_and_belongs_to_many associations.
+ #
+ # We do not support creating/deleting records on the association where the source has
+ # some other type, because this opens up a whole can of worms, and in basically any
+ # situation it is more natural for the user to just create or modify their join records
+ # directly as required.
+ def construct_join_attributes(*records)
+ if source_reflection.macro != :belongs_to
+ raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection)
+ end
+
+ join_attributes = {
+ source_reflection.foreign_key =>
+ records.map { |record|
+ record.send(source_reflection.association_primary_key)
+ }
+ }
+
+ if options[:source_type]
+ join_attributes[source_reflection.foreign_type] =
+ records.map { |record| record.class.base_class.name }
+ end
+
+ if records.count == 1
+ Hash[join_attributes.map { |k, v| [k, v.first] }]
+ else
+ join_attributes
+ end
+ end
+
+ def alias_tracker
+ @alias_tracker ||= AliasTracker.new
+ end
+
+ # TODO: It is decidedly icky to have an array for habtm entries, and no array for others
+ def tables
+ @tables ||= begin
+ Hash[
+ through_reflection_chain.map do |reflection|
+ table = alias_tracker.aliased_table_for(
+ reflection.table_name,
+ table_alias_for(reflection, reflection != self.reflection)
+ )
+
+ if reflection.macro == :has_and_belongs_to_many ||
+ (reflection.source_reflection &&
+ reflection.source_reflection.macro == :has_and_belongs_to_many)
+
+ join_table = alias_tracker.aliased_table_for(
+ (reflection.source_reflection || reflection).options[:join_table],
+ table_alias_for(reflection, true)
+ )
+
+ [reflection, [join_table, table]]
+ else
+ [reflection, table]
+ end
+ end
+ ]
+ end
+ end
+
+ def table_alias_for(reflection, join = false)
+ name = alias_tracker.pluralize(reflection.name)
+ name << "_#{self.reflection.name}"
+ name << "_join" if join
+ name
+ end
+
+ def inner_join(table, left_column, right_column, *conditions)
+ conditions << left_column.eq(right_column)
+
+ table.create_join(
+ table,
+ table.create_on(table.create_and(conditions.flatten.compact)))
+ end
+
+ def reflection_conditions(index)
+ reflection = through_reflection_chain[index]
+ conditions = through_conditions[index].dup
+
+ # TODO: maybe this should go in Reflection#through_conditions directly?
+ unless reflection.klass.descends_from_active_record?
+ conditions << reflection.klass.send(:type_condition)
+ end
+
+ unless conditions.empty?
+ conditions.map! do |condition|
+ condition = reflection.klass.send(:sanitize_sql, interpolate(condition), reflection.table_name)
+ condition = Arel.sql(condition) unless condition.is_a?(Arel::Node)
+ condition
+ end
+
+ Arel::Nodes::And.new(conditions)
+ end
+ end
+
+ def polymorphic_conditions(reflection, polymorphic_reflection)
+ if polymorphic_reflection.options[:as]
+ tables[reflection][polymorphic_reflection.type].
+ eq(polymorphic_reflection.active_record.base_class.name)
+ end
+ end
+
+ def source_type_conditions(reflection)
+ if reflection.options[:source_type]
+ tables[reflection.through_reflection][reflection.foreign_type].
+ eq(reflection.options[:source_type])
+ end
+ end
+
+ # TODO: Think about this in the context of nested associations
+ def stale_state
+ if through_reflection.macro == :belongs_to
+ owner[through_reflection.foreign_key].to_s
+ end
+ end
+
+ def foreign_key_present?
+ through_reflection.macro == :belongs_to &&
+ !owner[through_reflection.foreign_key].nil?
+ end
+
+ def ensure_not_nested
+ if reflection.nested?
+ raise HasManyThroughNestedAssociationsAreReadonly.new(owner, reflection)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/associations/through_association_scope.rb b/activerecord/lib/active_record/associations/through_association_scope.rb
deleted file mode 100644
index f6d02a215f..0000000000
--- a/activerecord/lib/active_record/associations/through_association_scope.rb
+++ /dev/null
@@ -1,300 +0,0 @@
-require 'enumerator'
-
-module ActiveRecord
- # = Active Record Through Association Scope
- module Associations
- module ThroughAssociationScope
-
- protected
-
- def construct_find_scope
- {
- :conditions => construct_conditions,
- :joins => construct_joins,
- :include => @reflection.options[:include] || @reflection.source_reflection.options[:include],
- :select => construct_select,
- :order => @reflection.options[:order],
- :limit => @reflection.options[:limit],
- :readonly => @reflection.options[:readonly]
- }
- end
-
- def construct_create_scope
- @reflection.nested? ? {} : construct_owner_attributes(@reflection)
- end
-
- # Build SQL conditions from attributes, qualified by table name.
- def construct_conditions
- reflection = @reflection.through_reflection_chain.last
-
- if reflection.macro == :has_and_belongs_to_many
- table_alias = table_aliases[reflection].first
- else
- table_alias = table_aliases[reflection]
- end
-
- parts = construct_quoted_owner_attributes(reflection).map do |attr, value|
- "#{table_alias}.#{attr} = #{value}"
- end
- parts += reflection_conditions(0)
-
- "(" + parts.join(') AND (') + ")"
- end
-
- # Associate attributes pointing to owner, quoted.
- def construct_quoted_owner_attributes(reflection)
- if as = reflection.options[:as]
- { "#{as}_id" => owner_quoted_id(reflection),
- "#{as}_type" => reflection.klass.quote_value(
- @owner.class.base_class.name.to_s,
- reflection.klass.columns_hash["#{as}_type"]) }
- elsif reflection.macro == :belongs_to
- { reflection.klass.primary_key => @owner.class.quote_value(@owner[reflection.primary_key_name]) }
- else
- { reflection.primary_key_name => owner_quoted_id(reflection) }
- end
- end
-
- def construct_select(custom_select = nil)
- distinct = "DISTINCT " if @reflection.options[:uniq]
- custom_select || @reflection.options[:select] || "#{distinct}#{@reflection.quoted_table_name}.*"
- end
-
- def construct_joins(custom_joins = nil)
- "#{construct_through_joins} #{@reflection.options[:joins]} #{custom_joins}"
- end
-
- def construct_through_joins
- joins, right_index = [], 1
-
- # Iterate over each pair in the through reflection chain, joining them together
- @reflection.through_reflection_chain.each_cons(2) do |left, right|
- right_table_and_alias = table_name_and_alias(right.quoted_table_name, table_aliases[right])
-
- if left.source_reflection.nil?
- case left.macro
- when :belongs_to
- joins << inner_join_sql(
- right_table_and_alias,
- table_aliases[left], left.association_primary_key,
- table_aliases[right], left.primary_key_name,
- reflection_conditions(right_index)
- )
- when :has_many, :has_one
- joins << inner_join_sql(
- right_table_and_alias,
- table_aliases[left], left.primary_key_name,
- table_aliases[right], right.association_primary_key,
- polymorphic_conditions(left, left),
- reflection_conditions(right_index)
- )
- when :has_and_belongs_to_many
- joins << inner_join_sql(
- right_table_and_alias,
- table_aliases[left].first, left.primary_key_name,
- table_aliases[right], right.klass.primary_key,
- reflection_conditions(right_index)
- )
- end
- else
- case left.source_reflection.macro
- when :belongs_to
- joins << inner_join_sql(
- right_table_and_alias,
- table_aliases[left], left.association_primary_key,
- table_aliases[right], left.primary_key_name,
- source_type_conditions(left),
- reflection_conditions(right_index)
- )
- when :has_many, :has_one
- if right.macro == :has_and_belongs_to_many
- join_table, right_table = table_aliases[right]
- right_table_and_alias = table_name_and_alias(right.quoted_table_name, right_table)
- else
- right_table = table_aliases[right]
- end
-
- joins << inner_join_sql(
- right_table_and_alias,
- table_aliases[left], left.primary_key_name,
- right_table, left.source_reflection.active_record_primary_key,
- polymorphic_conditions(left, left.source_reflection),
- reflection_conditions(right_index)
- )
-
- if right.macro == :has_and_belongs_to_many
- joins << inner_join_sql(
- table_name_and_alias(
- quote_table_name(right.options[:join_table]),
- join_table
- ),
- right_table, right.klass.primary_key,
- join_table, right.association_foreign_key
- )
- end
- when :has_and_belongs_to_many
- join_table, left_table = table_aliases[left]
-
- joins << inner_join_sql(
- table_name_and_alias(
- quote_table_name(left.source_reflection.options[:join_table]),
- join_table
- ),
- left_table, left.klass.primary_key,
- join_table, left.association_foreign_key
- )
-
- joins << inner_join_sql(
- right_table_and_alias,
- join_table, left.primary_key_name,
- table_aliases[right], right.klass.primary_key,
- reflection_conditions(right_index)
- )
- end
- end
-
- right_index += 1
- end
-
- joins.join(" ")
- end
-
- def alias_tracker
- @alias_tracker ||= AliasTracker.new
- end
-
- def table_aliases
- @table_aliases ||= begin
- @reflection.through_reflection_chain.inject({}) do |aliases, reflection|
- table_alias = quote_table_name(alias_tracker.aliased_name_for(
- reflection.table_name,
- table_alias_for(reflection, reflection != @reflection)
- ))
-
- if reflection.macro == :has_and_belongs_to_many ||
- (reflection.source_reflection &&
- reflection.source_reflection.macro == :has_and_belongs_to_many)
-
- join_table_alias = quote_table_name(alias_tracker.aliased_name_for(
- (reflection.source_reflection || reflection).options[:join_table],
- table_alias_for(reflection, true)
- ))
-
- aliases[reflection] = [join_table_alias, table_alias]
- else
- aliases[reflection] = table_alias
- end
-
- aliases
- end
- end
- end
-
- def table_alias_for(reflection, join = false)
- name = alias_tracker.pluralize(reflection.name)
- name << "_#{@reflection.name}"
- name << "_join" if join
- name
- end
-
- def quote_table_name(table_name)
- @reflection.klass.connection.quote_table_name(table_name)
- end
-
- def table_name_and_alias(table_name, table_alias)
- "#{table_name} #{table_alias if table_alias != table_name}".strip
- end
-
- def inner_join_sql(table, on_left_table, on_left_key, on_right_table, on_right_key, *conditions)
- conditions << "#{on_left_table}.#{on_left_key} = #{on_right_table}.#{on_right_key}"
- conditions = conditions.flatten.compact
- conditions = conditions.map { |sql| "(#{sql})" } * ' AND '
-
- "INNER JOIN #{table} ON #{conditions}"
- end
-
- def reflection_conditions(index)
- reflection = @reflection.through_reflection_chain[index]
- reflection_conditions = @reflection.through_conditions[index]
-
- conditions = []
-
- if reflection.options[:as].nil? && # reflection.klass is a Module if :as is used
- reflection.klass.finder_needs_type_condition?
- conditions << reflection.klass.send(:type_condition).to_sql
- end
-
- reflection_conditions.each do |condition|
- sanitized_condition = reflection.klass.send(:sanitize_sql, condition)
- interpolated_condition = interpolate_sql(sanitized_condition)
-
- if condition.is_a?(Hash)
- interpolated_condition.gsub!(
- @reflection.quoted_table_name,
- reflection.quoted_table_name
- )
- end
-
- conditions << interpolated_condition
- end
-
- conditions
- end
-
- def polymorphic_conditions(reflection, polymorphic_reflection)
- if polymorphic_reflection.options[:as]
- "%s.%s = %s" % [
- table_aliases[reflection], "#{polymorphic_reflection.options[:as]}_type",
- @owner.class.quote_value(polymorphic_reflection.active_record.base_class.name)
- ]
- end
- end
-
- def source_type_conditions(reflection)
- if reflection.options[:source_type]
- "%s.%s = %s" % [
- table_aliases[reflection.through_reflection],
- reflection.source_reflection.options[:foreign_type].to_s,
- @owner.class.quote_value(reflection.options[:source_type])
- ]
- end
- end
-
- # Construct attributes for associate pointing to owner.
- def construct_owner_attributes(reflection)
- if as = reflection.options[:as]
- { "#{as}_id" => @owner.id,
- "#{as}_type" => @owner.class.base_class.name.to_s }
- else
- { reflection.primary_key_name => @owner.id }
- end
- end
-
- # Construct attributes for :through pointing to owner and associate.
- # This method is used when adding records to the association. Since this only makes sense for
- # non-nested through associations, that's the only case we have to worry about here.
- def construct_join_attributes(associate)
- # TODO: revisit this to allow it for deletion, supposing dependent option is supported
- raise ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(@owner, @reflection) if [:has_one, :has_many].include?(@reflection.source_reflection.macro)
-
- join_attributes = construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id)
-
- if @reflection.options[:source_type]
- join_attributes.merge!(@reflection.source_reflection.options[:foreign_type] => associate.class.base_class.name.to_s)
- end
-
- if @reflection.through_reflection.options[:conditions].is_a?(Hash)
- join_attributes.merge!(@reflection.through_reflection.options[:conditions])
- end
-
- join_attributes
- end
-
- def ensure_not_nested
- if @reflection.nested?
- raise HasManyThroughNestedAssociationsAreReadonly.new(@owner, @reflection)
- end
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 4f4a0a5fee..5833c65893 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -10,7 +10,18 @@ module ActiveRecord
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods
- super(columns_hash.keys)
+ return if attribute_methods_generated?
+ super(column_names)
+ @attribute_methods_generated = true
+ end
+
+ def attribute_methods_generated?
+ @attribute_methods_generated ||= false
+ end
+
+ def undefine_attribute_methods(*args)
+ super
+ @attribute_methods_generated = false
end
# Checks whether the method is defined in the model or any of its subclasses
@@ -18,7 +29,11 @@ module ActiveRecord
# method is defined by Active Record though.
def instance_method_already_implemented?(method_name)
method_name = method_name.to_s
- @_defined_class_methods ||= ancestors.first(ancestors.index(ActiveRecord::Base)).sum([]) { |m| m.instance_methods(false) | m.private_instance_methods(false) }.map {|m| m.to_s }.to_set
+ index = ancestors.index(ActiveRecord::Base) || ancestors.length
+ @_defined_class_methods ||= ancestors.first(index).map { |m|
+ m.instance_methods(false) | m.private_instance_methods(false)
+ }.flatten.map {|m| m.to_s }.to_set
+
@@_defined_activerecord_methods ||= defined_activerecord_methods
raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord" if @@_defined_activerecord_methods.include?(method_name)
@_defined_class_methods.include?(method_name)
@@ -27,9 +42,8 @@ module ActiveRecord
def defined_activerecord_methods
active_record = ActiveRecord::Base
super_klass = ActiveRecord::Base.superclass
- methods = active_record.public_instance_methods - super_klass.public_instance_methods
- methods += active_record.private_instance_methods - super_klass.private_instance_methods
- methods += active_record.protected_instance_methods - super_klass.protected_instance_methods
+ methods = (active_record.instance_methods - super_klass.instance_methods) +
+ (active_record.private_instance_methods - super_klass.private_instance_methods)
methods.map {|m| m.to_s }.to_set
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
index c19a33faa8..3eff3d54e3 100644
--- a/activerecord/lib/active_record/attribute_methods/dirty.rb
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -22,6 +22,8 @@ module ActiveRecord
if status = super
@previously_changed = changes
@changed_attributes.clear
+ elsif IdentityMap.enabled?
+ IdentityMap.remove(self)
end
status
end
@@ -32,6 +34,9 @@ module ActiveRecord
@previously_changed = changes
@changed_attributes.clear
end
+ rescue
+ IdentityMap.remove(self) if IdentityMap.enabled?
+ raise
end
# <tt>reload</tt> the record and clears changed attributes.
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb
index 75ae06f5e9..fcdd31ddea 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -14,26 +14,37 @@ module ActiveRecord
# Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
# primary_key_prefix_type setting, though.
def primary_key
- reset_primary_key
+ @primary_key ||= reset_primary_key
end
def reset_primary_key #:nodoc:
- key = get_primary_key(base_class.name)
+ key = self == base_class ? get_primary_key(base_class.name) :
+ base_class.primary_key
+
set_primary_key(key)
key
end
def get_primary_key(base_name) #:nodoc:
- key = 'id'
+ return 'id' unless base_name && !base_name.blank?
+
case primary_key_prefix_type
- when :table_name
- key = base_name.to_s.foreign_key(false)
- when :table_name_with_underscore
- key = base_name.to_s.foreign_key
+ when :table_name
+ base_name.foreign_key(false)
+ when :table_name_with_underscore
+ base_name.foreign_key
+ else
+ if ActiveRecord::Base != self && connection.table_exists?(table_name)
+ connection.primary_key(table_name)
+ else
+ 'id'
+ end
end
- key
end
+ attr_accessor :original_primary_key
+ attr_writer :primary_key
+
# Sets the name of the primary key column to use to the given value,
# or (if the value is nil or false) to the value returned by the given
# block.
@@ -42,9 +53,12 @@ module ActiveRecord
# set_primary_key "sysid"
# end
def set_primary_key(value = nil, &block)
- define_attr_method :primary_key, value, &block
+ @primary_key ||= ''
+ self.original_primary_key = @primary_key
+ value &&= value.to_s
+ connection_pool.primary_keys[table_name] = value
+ self.primary_key = block_given? ? instance_eval(&block) : value
end
- alias :primary_key= :set_primary_key
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index 506f6e878f..ab86d8bad1 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -20,7 +20,7 @@ module ActiveRecord
# be cached. Usually caching only pays off for attributes with expensive conversion
# methods, like time related columns (e.g. +created_at+, +updated_at+).
def cache_attributes(*attribute_names)
- attribute_names.each {|attr| cached_attributes << attr.to_s}
+ cached_attributes.merge attribute_names.map { |attr| attr.to_s }
end
# Returns the attributes which are cached. By default time related columns
@@ -39,7 +39,7 @@ module ActiveRecord
if serialized_attributes.include?(attr_name)
define_read_method_for_serialized_attribute(attr_name)
else
- define_read_method(attr_name.to_sym, attr_name, columns_hash[attr_name])
+ define_read_method(attr_name, attr_name, columns_hash[attr_name])
end
if attr_name == primary_key && attr_name != "id"
@@ -54,17 +54,17 @@ module ActiveRecord
# Define read method for serialized attribute.
def define_read_method_for_serialized_attribute(attr_name)
- access_code = "@attributes_cache['#{attr_name}'] ||= unserialize_attribute('#{attr_name}')"
- generated_attribute_methods.module_eval("def #{attr_name}; #{access_code}; end", __FILE__, __LINE__)
+ access_code = "@attributes_cache['#{attr_name}'] ||= @attributes['#{attr_name}']"
+ generated_attribute_methods.module_eval("def _#{attr_name}; #{access_code}; end; alias #{attr_name} _#{attr_name}", __FILE__, __LINE__)
end
# Define an attribute reader method. Cope with nil column.
def define_read_method(symbol, attr_name, column)
- cast_code = column.type_cast_code('v') if column
- access_code = cast_code ? "(v=@attributes['#{attr_name}']) && #{cast_code}" : "@attributes['#{attr_name}']"
+ cast_code = column.type_cast_code('v')
+ access_code = "(v=@attributes['#{attr_name}']) && #{cast_code}"
unless attr_name.to_s == self.primary_key.to_s
- access_code = access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
+ access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
end
if cache_attribute?(attr_name)
@@ -106,14 +106,10 @@ module ActiveRecord
# Returns the unserialized object of the attribute.
def unserialize_attribute(attr_name)
- unserialized_object = object_from_yaml(@attributes[attr_name])
+ coder = self.class.serialized_attributes[attr_name]
+ unserialized_object = coder.load(@attributes[attr_name])
- if unserialized_object.is_a?(self.class.serialized_attributes[attr_name]) || unserialized_object.nil?
- @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object
- else
- raise SerializationTypeMismatch,
- "#{attr_name} was supposed to be a #{self.class.serialized_attributes[attr_name]}, but was a #{unserialized_object.class.to_s}"
- end
+ @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object
end
private
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 dc2785b6bf..76218d2a73 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -40,12 +40,13 @@ module ActiveRecord
def define_method_attribute=(attr_name)
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
method_body, line = <<-EOV, __LINE__ + 1
- def #{attr_name}=(time)
+ def #{attr_name}=(original_time)
+ time = original_time.dup unless original_time.nil?
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
- write_attribute(:#{attr_name}, time)
+ write_attribute(:#{attr_name}, (time || original_time))
end
EOV
generated_attribute_methods.module_eval(method_body, __FILE__, line)
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index c3dda29d03..748cc99a62 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -116,28 +116,44 @@ module ActiveRecord
module AutosaveAssociation
extend ActiveSupport::Concern
- ASSOCIATION_TYPES = %w{ has_one belongs_to has_many has_and_belongs_to_many }
+ 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
+ end
+ end
included do
ASSOCIATION_TYPES.each do |type|
- send("valid_keys_for_#{type}_association") << :autosave
+ Associations::Builder.const_get(type).send(:include, AssociationBuilderExtension)
end
end
module ClassMethods
private
- # def belongs_to(name, options = {})
- # super
- # add_autosave_association_callbacks(reflect_on_association(name))
- # end
- ASSOCIATION_TYPES.each do |type|
- module_eval <<-CODE, __FILE__, __LINE__ + 1
- def #{type}(name, options = {})
- super
- add_autosave_association_callbacks(reflect_on_association(name))
+ def define_non_cyclic_method(name, reflection, &block)
+ define_method(name) do |*args|
+ result = true; @_already_called ||= {}
+ # Loop prevention for validation of associations
+ unless @_already_called[[name, reflection.name]]
+ begin
+ @_already_called[[name, reflection.name]]=true
+ result = instance_eval(&block)
+ ensure
+ @_already_called[[name, reflection.name]]=false
+ end
end
- CODE
+
+ result
+ end
end
# Adds validation and save callbacks for the association as specified by
@@ -160,7 +176,7 @@ module ActiveRecord
if collection
before_save :before_save_collection_association
- define_method(save_method) { save_collection_association(reflection) }
+ define_non_cyclic_method(save_method, reflection) { save_collection_association(reflection) }
# Doesn't use after_save as that would save associations added in after_create/after_update twice
after_create save_method
after_update save_method
@@ -178,7 +194,7 @@ module ActiveRecord
after_create save_method
after_update save_method
else
- define_method(save_method) { save_belongs_to_association(reflection) }
+ define_non_cyclic_method(save_method, reflection) { save_belongs_to_association(reflection) }
before_save save_method
end
end
@@ -186,7 +202,7 @@ module ActiveRecord
if reflection.validate? && !method_defined?(validation_method)
method = (collection ? :validate_collection_association : :validate_single_association)
- define_method(validation_method) { send(method, reflection) }
+ define_non_cyclic_method(validation_method, reflection) { send(method, reflection) }
validate validation_method
end
end
@@ -227,7 +243,7 @@ module ActiveRecord
# unless the parent is/was a new record itself.
def associated_records_to_validate_or_save(association, new_record, autosave)
if new_record
- association
+ association && association.target
elsif autosave
association.target.find_all { |record| record.changed_for_autosave? }
else
@@ -247,9 +263,9 @@ module ActiveRecord
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
# turned on for the association.
def validate_single_association(reflection)
- if (association = association_instance_get(reflection.name)) && !association.target.nil?
- association_valid?(reflection, association)
- end
+ association = association_instance_get(reflection.name)
+ record = association && association.target
+ association_valid?(reflection, record) if record
end
# Validate the associated records if <tt>:validate</tt> or
@@ -266,12 +282,12 @@ module ActiveRecord
# Returns whether or not the association is valid and applies any errors to
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
# enabled records if they're marked_for_destruction? or destroyed.
- def association_valid?(reflection, association)
- return true if association.destroyed? || association.marked_for_destruction?
+ def association_valid?(reflection, record)
+ return true if record.destroyed? || record.marked_for_destruction?
- unless valid = association.valid?
+ unless valid = record.valid?
if reflection.options[:autosave]
- association.errors.each do |attribute, message|
+ record.errors.each do |attribute, message|
attribute = "#{reflection.name}.#{attribute}"
errors[attribute] << message
errors[attribute].uniq!
@@ -303,23 +319,31 @@ module ActiveRecord
autosave = reflection.options[:autosave]
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
+ begin
records.each do |record|
next if record.destroyed?
+ saved = true
+
if autosave && record.marked_for_destruction?
- association.destroy(record)
+ association.proxy.destroy(record)
elsif autosave != false && (@new_record_before_save || record.new_record?)
if autosave
- saved = association.send(:insert_record, record, false, false)
+ saved = association.insert_record(record, false)
else
- association.send(:insert_record, record)
+ association.insert_record(record)
end
elsif autosave
saved = record.save(:validate => false)
end
- raise ActiveRecord::Rollback if saved == false
+ raise ActiveRecord::Rollback unless saved
+ end
+ rescue
+ records.each {|x| IdentityMap.remove(x) } if IdentityMap.enabled?
+ raise
end
+
end
# reconstruct the scope now that we know the owner's id
@@ -336,16 +360,18 @@ module ActiveRecord
# This all happens inside a transaction, _if_ the Transactions module is included into
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
def save_has_one_association(reflection)
- if (association = association_instance_get(reflection.name)) && !association.target.nil? && !association.destroyed?
+ association = association_instance_get(reflection.name)
+ record = association && association.load_target
+ if record && !record.destroyed?
autosave = reflection.options[:autosave]
- if autosave && association.marked_for_destruction?
- association.destroy
+ if autosave && record.marked_for_destruction?
+ record.destroy
else
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
- if autosave != false && (new_record? || association.new_record? || association[reflection.primary_key_name] != key || autosave)
- association[reflection.primary_key_name] = key
- saved = association.save(:validate => !autosave)
+ if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave)
+ record[reflection.foreign_key] = key
+ saved = record.save(:validate => !autosave)
raise ActiveRecord::Rollback if !saved && autosave
saved
end
@@ -357,17 +383,20 @@ module ActiveRecord
#
# In addition, it will destroy the association if it was marked for destruction.
def save_belongs_to_association(reflection)
- if (association = association_instance_get(reflection.name)) && !association.destroyed?
+ association = association_instance_get(reflection.name)
+ record = association && association.load_target
+ if record && !record.destroyed?
autosave = reflection.options[:autosave]
- if autosave && association.marked_for_destruction?
- association.destroy
+ if autosave && record.marked_for_destruction?
+ record.destroy
elsif autosave != false
- saved = association.save(:validate => !autosave) if association.new_record? || autosave
+ saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
if association.updated?
- association_id = association.send(reflection.options[:primary_key] || :id)
- self[reflection.primary_key_name] = association_id
+ association_id = record.send(reflection.options[:primary_key] || :id)
+ self[reflection.foreign_key] = association_id
+ association.loaded!
end
saved if autosave
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 7b9ce21ceb..b3204b2bda 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -1,3 +1,8 @@
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'set'
require 'active_support/benchmarkable'
@@ -175,10 +180,7 @@ module ActiveRecord #:nodoc:
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
#
# Person.where(:user_name => user_name, :password => password).first
- # Person.find_by_user_name_and_password #with dynamic finder
- #
- # Person.where(:user_name => user_name, :password => password, :gender => 'male').first
- # Payment.find_by_user_name_and_password_and_gender
+ # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
#
# It's even possible to call these dynamic finder methods on relations and named scopes.
#
@@ -244,6 +246,17 @@ module ActiveRecord #:nodoc:
# user = User.create(:preferences => %w( one two three ))
# User.find(user.id).preferences # raises SerializationTypeMismatch
#
+ # When you specify a class option, the default value for that attribute will be a new
+ # instance of that class.
+ #
+ # class User < ActiveRecord::Base
+ # serialize :preferences, OpenStruct
+ # end
+ #
+ # user = User.new
+ # user.preferences.theme_color = "red"
+ #
+ #
# == Single table inheritance
#
# Active Record allows inheritance by storing the name of the class in a column that by
@@ -527,11 +540,19 @@ module ActiveRecord #:nodoc:
#
# ==== Example
# # Serialize a preferences attribute
- # class User
+ # class User < ActiveRecord::Base
# serialize :preferences
# end
def serialize(attr_name, class_name = Object)
- serialized_attributes[attr_name.to_s] = class_name
+ 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
# Guesses the table name (in forced lower-case) based on the name of the class in the
@@ -614,6 +635,9 @@ module ActiveRecord #:nodoc:
def set_table_name(value = nil, &block)
@quoted_table_name = nil
define_attr_method :table_name, value, &block
+
+ @arel_table = Arel::Table.new(table_name, :engine => arel_engine)
+ @relation = Relation.new(self, arel_table)
end
alias :table_name= :set_table_name
@@ -657,16 +681,12 @@ module ActiveRecord #:nodoc:
# Returns an array of column objects for the table associated with this class.
def columns
- unless defined?(@columns) && @columns
- @columns = connection.columns(table_name, "#{name} Columns")
- @columns.each { |column| column.primary = column.name == primary_key }
- end
- @columns
+ connection_pool.columns[table_name]
end
# Returns a hash of column objects for the table associated with this class.
def columns_hash
- @columns_hash ||= Hash[columns.map { |column| [column.name, column] }]
+ connection_pool.columns_hash[table_name]
end
# Returns an array of column names as strings.
@@ -723,8 +743,14 @@ module ActiveRecord #:nodoc:
def reset_column_information
connection.clear_cache!
undefine_attribute_methods
- @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
- @arel_engine = @relation = @arel_table = nil
+ connection_pool.clear_table_cache!(table_name) if table_exists?
+
+ @column_names = @content_columns = @dynamic_methods_hash = @inheritance_column = nil
+ @arel_engine = @relation = nil
+ end
+
+ def clear_cache! # :nodoc:
+ connection_pool.clear_cache!
end
def attribute_method?(attribute)
@@ -762,7 +788,7 @@ module ActiveRecord #:nodoc:
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
end
- # Returns a string like 'Post id:integer, title:string, body:text'
+ # Returns a string like 'Post(id:integer, title:string, body:text)'
def inspect
if self == Base
super
@@ -790,6 +816,10 @@ module ActiveRecord #:nodoc:
object.is_a?(self)
end
+ def symbolized_base_class
+ @symbolized_base_class ||= base_class.to_s.to_sym
+ 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
# through some arbitrarily deep hierarchy, B.base_class will return A.
@@ -823,13 +853,13 @@ module ActiveRecord #:nodoc:
end
def arel_table
- @arel_table ||= Arel::Table.new(table_name, arel_engine)
+ Arel::Table.new(table_name, arel_engine)
end
def arel_engine
@arel_engine ||= begin
if self == ActiveRecord::Base
- Arel::Table.engine
+ ActiveRecord::Base
else
connection_handler.connection_pools[name] ? self : superclass.arel_engine
end
@@ -852,8 +882,8 @@ module ActiveRecord #:nodoc:
# limit(10) # Fires "SELECT * FROM posts LIMIT 10"
# }
#
- # It is recommended to use block form of unscoped because chaining unscoped with <tt>named_scope</tt>
- # does not work. Assuming that <tt>published</tt> is a <tt>named_scope</tt> following two statements are same.
+ # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt>
+ # does not work. Assuming that <tt>published</tt> is a <tt>scope</tt> following two statements are same.
#
# Post.unscoped.published
# Post.published
@@ -870,20 +900,51 @@ module ActiveRecord #:nodoc:
reset_scoped_methods
end
+ # Specifies how the record is loaded by +Marshal+.
+ #
+ # +_load+ sets an instance variable for each key in the hash it takes as input.
+ # Override this method if you require more complex marshalling.
+ def _load(data)
+ record = allocate
+ record.init_with(Marshal.load(data))
+ record
+ end
+
+
+ # Finder methods must instantiate through this method to work with the
+ # single-table inheritance model that makes it possible to create
+ # objects of different types from the same table.
+ def instantiate(record)
+ sti_class = find_sti_class(record[inheritance_column])
+ record_id = sti_class.primary_key && record[sti_class.primary_key]
+
+ if ActiveRecord::IdentityMap.enabled? && record_id
+ if (column = sti_class.columns_hash[sti_class.primary_key]) && column.number?
+ record_id = record_id.to_i
+ end
+ if instance = IdentityMap.get(sti_class, record_id)
+ instance.reinit_with('attributes' => record)
+ else
+ instance = sti_class.allocate.init_with('attributes' => record)
+ IdentityMap.add(instance)
+ end
+ else
+ instance = sti_class.allocate.init_with('attributes' => record)
+ end
+
+ instance
+ end
+
private
def relation #:nodoc:
@relation ||= Relation.new(self, arel_table)
- finder_needs_type_condition? ? @relation.where(type_condition) : @relation
- end
- # Finder methods must instantiate through this method to work with the
- # single-table inheritance model that makes it possible to create
- # objects of different types from the same table.
- def instantiate(record)
- model = find_sti_class(record[inheritance_column]).allocate
- model.init_with('attributes' => record)
- model
+ if finder_needs_type_condition?
+ @relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
+ else
+ @relation
+ end
end
def find_sti_class(type_name)
@@ -913,11 +974,10 @@ module ActiveRecord #:nodoc:
end
def type_condition
- sti_column = arel_table[inheritance_column]
- condition = sti_column.eq(sti_name)
- descendants.each { |subclass| condition = condition.or(sti_column.eq(subclass.sti_name)) }
+ sti_column = arel_table[inheritance_column.to_sym]
+ sti_names = ([self] + descendants).map { |model| model.sti_name }
- condition
+ sti_column.in(sti_names)
end
# Guesses the table name, but does not decorate it with prefix and suffix information.
@@ -1364,6 +1424,8 @@ MSG
# hence you can't have attributes that aren't part of the table columns.
def initialize(attributes = nil)
@attributes = attributes_from_column_definition
+ @association_cache = {}
+ @aggregation_cache = {}
@attributes_cache = {}
@new_record = true
@readonly = false
@@ -1373,15 +1435,32 @@ MSG
@changed_attributes = {}
ensure_proper_type
+ set_serialized_attributes
populate_with_current_scope_attributes
self.attributes = attributes unless attributes.nil?
result = yield self if block_given?
- _run_initialize_callbacks
+ run_callbacks :initialize
result
end
+ # Populate +coder+ with attributes about this record that should be
+ # serialized. The structure of +coder+ defined in this method is
+ # guaranteed to match the structure of +coder+ passed to the +init_with+
+ # method.
+ #
+ # Example:
+ #
+ # class Post < ActiveRecord::Base
+ # end
+ # coder = {}
+ # Post.new.encode_with(coder)
+ # coder # => { 'id' => nil, ... }
+ def encode_with(coder)
+ coder['attributes'] = attributes
+ end
+
# Initialize an empty model object from +coder+. +coder+ must contain
# the attributes necessary for initializing an empty model object. For
# example:
@@ -1394,11 +1473,28 @@ MSG
# post.title # => 'hello world'
def init_with(coder)
@attributes = coder['attributes']
+
+ set_serialized_attributes
+
@attributes_cache, @previously_changed, @changed_attributes = {}, {}, {}
+ @association_cache = {}
+ @aggregation_cache = {}
@readonly = @destroyed = @marked_for_destruction = false
@new_record = false
- _run_find_callbacks
- _run_initialize_callbacks
+ run_callbacks :find
+ run_callbacks :initialize
+
+ self
+ end
+
+ # Specifies how the record is dumped by +Marshal+.
+ #
+ # +_dump+ emits a marshalled hash which has been passed to +encode_with+. Override this
+ # method if you require more complex marshalling.
+ def _dump(level)
+ dump = {}
+ encode_with(dump)
+ Marshal.dump(dump)
end
# Returns a String, which Action Pack uses for constructing an URL to this
@@ -1490,8 +1586,10 @@ MSG
attributes.each do |k, v|
if k.include?("(")
multi_parameter_attributes << [ k, v ]
+ elsif respond_to?("#{k}=")
+ send("#{k}=", v)
else
- respond_to?(:"#{k}=") ? send(:"#{k}=", v) : raise(UnknownAttributeError, "unknown attribute: #{k}")
+ raise(UnknownAttributeError, "unknown attribute: #{k}")
end
end
@@ -1531,7 +1629,7 @@ MSG
# Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
# nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
def attribute_present?(attribute)
- !read_attribute(attribute).blank?
+ !_read_attribute(attribute).blank?
end
# Returns the column object for the named attribute.
@@ -1604,9 +1702,9 @@ MSG
@changed_attributes[attr] = orig_value if field_changed?(attr, orig_value, @attributes[attr])
end
- clear_aggregation_cache
- clear_association_cache
- @attributes_cache = {}
+ @aggregation_cache = {}
+ @association_cache = {}
+ @attributes_cache = {}
@new_record = true
ensure_proper_type
@@ -1628,7 +1726,7 @@ MSG
# Returns the contents of the record as a nicely formatted string.
def inspect
attributes_as_nice_string = self.class.column_names.collect { |name|
- if has_attribute?(name) || new_record?
+ if has_attribute?(name)
"#{name}: #{attribute_for_inspect(name)}"
end
}.compact.join(", ")
@@ -1652,6 +1750,13 @@ MSG
private
+ def set_serialized_attributes
+ (@attributes.keys & self.class.serialized_attributes.keys).each do |key|
+ coder = self.class.serialized_attributes[key]
+ @attributes[key] = coder.load @attributes[key]
+ end
+ end
+
# Sets the attribute used for single table inheritance to this class name if this is not the
# ActiveRecord::Base descendant.
# Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
@@ -1673,17 +1778,25 @@ MSG
# Returns a copy of the attributes hash where all the values have been safely quoted for use in
# an Arel insert/update method.
def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
- attrs = {}
+ attrs = {}
+ klass = self.class
+ arel_table = klass.arel_table
+
attribute_names.each do |name|
if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
- value = read_attribute(name)
- if !value.nil? && self.class.serialized_attributes.key?(name)
- value = YAML.dump value
- end
- attrs[self.class.arel_table[name]] = value
+ value = if coder = klass.serialized_attributes[name]
+ coder.dump @attributes[name]
+ else
+ # FIXME: we need @attributes to be used consistently.
+ # If the values stored in @attributes were already type
+ # casted, this code could be simplified
+ read_attribute(name)
+ end
+
+ attrs[arel_table[name]] = value
end
end
end
@@ -1695,12 +1808,6 @@ MSG
self.class.connection.quote(value, column)
end
- # Interpolate custom SQL string in instance context.
- # Optional record argument is meant for custom insert_sql.
- def interpolate_sql(sql, record = nil)
- instance_eval("%@#{sql.gsub('@', '\@')}@", __FILE__, __LINE__)
- 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 (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
@@ -1807,27 +1914,20 @@ MSG
end
end
- def object_from_yaml(string)
- return string unless string.is_a?(String) && string =~ /^---/
- YAML::load(string) rescue string
- end
-
def populate_with_current_scope_attributes
if scope = self.class.send(:current_scoped_methods)
create_with = scope.scope_for_create
create_with.each { |att,value|
- respond_to?(:"#{att}=") && send("#{att}=", value)
+ respond_to?("#{att}=") && send("#{att}=", value)
}
end
end
# Clear attributes and changed_attributes
def clear_timestamp_attributes
- %w(created_at created_on updated_at updated_on).each do |attribute_name|
- if has_attribute?(attribute_name)
- self[attribute_name] = nil
- changed_attributes.delete(attribute_name)
- end
+ all_timestamp_attributes_in_model.each do |attribute_name|
+ self[attribute_name] = nil
+ changed_attributes.delete(attribute_name)
end
end
end
@@ -1850,7 +1950,9 @@ MSG
include AttributeMethods::Dirty
include ActiveModel::MassAssignmentSecurity
include Callbacks, ActiveModel::Observing, Timestamp
- include Associations, AssociationPreload, NamedScope
+ include Associations, NamedScope
+ include IdentityMap
+ include ActiveModel::SecurePassword
# AutosaveAssociation needs to be included before Transactions, because we want
# #save_with_autosave_associations to be wrapped inside a transaction.
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index 47428cfd0f..ff4ce1b605 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -25,9 +25,13 @@ module ActiveRecord
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
# <tt>after_rollback</tt>.
#
- # That's a total of ten callbacks, which gives you immense power to react and prepare for each state in the
+ # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
+ # is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
+ # are instantiated as well.
+ #
+ # That's a total of twelve callbacks, which gives you immense power to react and prepare for each state in the
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
- # except that each <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
+ # except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
#
# Examples:
# class CreditCard < ActiveRecord::Base
@@ -185,14 +189,6 @@ module ActiveRecord
# 'puts "Evaluated after parents are destroyed"'
# end
#
- # == The +after_find+ and +after_initialize+ exceptions
- #
- # Because +after_find+ and +after_initialize+ are called for each object found and instantiated by a finder,
- # such as <tt>Base.find(:all)</tt>, we've had to implement a simple performance constraint (50% more speed
- # on a simple test case). Unlike all the other callbacks, +after_find+ and +after_initialize+ will only be
- # run if an explicit implementation is defined (<tt>def after_find</tt>). In that case, all of the
- # callback types will be called.
- #
# == <tt>before_validation*</tt> returning statements
#
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
@@ -237,25 +233,25 @@ module ActiveRecord
end
def destroy #:nodoc:
- _run_destroy_callbacks { super }
+ run_callbacks(:destroy) { super }
end
def touch(*) #:nodoc:
- _run_touch_callbacks { super }
+ run_callbacks(:touch) { super }
end
private
def create_or_update #:nodoc:
- _run_save_callbacks { super }
+ run_callbacks(:save) { super }
end
def create #:nodoc:
- _run_create_callbacks { super }
+ run_callbacks(:create) { super }
end
def update(*) #:nodoc:
- _run_update_callbacks { super }
+ run_callbacks(:update) { super }
end
end
end
diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb
new file mode 100644
index 0000000000..fb59d9fb07
--- /dev/null
+++ b/activerecord/lib/active_record/coders/yaml_column.rb
@@ -0,0 +1,41 @@
+module ActiveRecord
+ # :stopdoc:
+ module Coders
+ class YAMLColumn
+ RESCUE_ERRORS = [ ArgumentError ]
+
+ if defined?(Psych) && defined?(Psych::SyntaxError)
+ RESCUE_ERRORS << Psych::SyntaxError
+ end
+
+ attr_accessor :object_class
+
+ def initialize(object_class = Object)
+ @object_class = object_class
+ end
+
+ def dump(obj)
+ YAML.dump obj
+ end
+
+ def load(yaml)
+ return object_class.new if object_class != Object && yaml.nil?
+ return yaml unless yaml.is_a?(String) && yaml =~ /^---/
+ begin
+ obj = YAML.load(yaml)
+
+ unless obj.is_a?(object_class) || obj.nil?
+ raise SerializationTypeMismatch,
+ "Attribute was supposed to be a #{object_class}, but was a #{obj.class}"
+ end
+ obj ||= object_class.new if object_class != Object
+
+ obj
+ rescue *RESCUE_ERRORS
+ yaml
+ end
+ end
+ end
+ end
+ # :startdoc
+end
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 cffa2387de..4297c26413 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -57,7 +57,9 @@ module ActiveRecord
# * +wait_timeout+: number of seconds to block and wait for a connection
# before giving up and raising a timeout error (default 5 seconds).
class ConnectionPool
+ attr_accessor :automatic_reconnect
attr_reader :spec, :connections
+ attr_reader :columns, :columns_hash, :primary_keys, :tables
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
# object which describes database connection information (e.g. adapter,
@@ -81,6 +83,63 @@ module ActiveRecord
@connections = []
@checked_out = []
+ @automatic_reconnect = true
+ @tables = {}
+
+ @columns = Hash.new do |h, table_name|
+ h[table_name] = with_connection do |conn|
+
+ # Fetch a list of columns
+ conn.columns(table_name, "#{table_name} Columns").tap do |columns|
+
+ # set primary key information
+ columns.each do |column|
+ column.primary = column.name == primary_keys[table_name]
+ end
+ end
+ end
+ end
+
+ @columns_hash = Hash.new do |h, table_name|
+ h[table_name] = Hash[columns[table_name].map { |col|
+ [col.name, col]
+ }]
+ end
+
+ @primary_keys = Hash.new do |h, table_name|
+ h[table_name] = with_connection do |conn|
+ table_exists?(table_name) ? conn.primary_key(table_name) : 'id'
+ end
+ end
+ end
+
+ # A cached lookup for table existence
+ def table_exists?(name)
+ return true if @tables.key? name
+
+ with_connection do |conn|
+ conn.tables.each { |table| @tables[table] = true }
+ end
+
+ @tables.key? name
+ end
+
+ # Clears out internal caches:
+ #
+ # * columns
+ # * columns_hash
+ # * tables
+ def clear_cache!
+ @columns.clear
+ @columns_hash.clear
+ @tables.clear
+ end
+
+ # Clear out internal caches for table with +table_name+
+ def clear_table_cache!(table_name)
+ @columns.delete table_name
+ @columns_hash.delete table_name
+ @primary_keys.delete table_name
end
# Retrieve the connection associated with the current thread, or call
@@ -212,7 +271,7 @@ module ActiveRecord
# calling +checkout+ on this pool.
def checkin(conn)
@connection_mutex.synchronize do
- conn.send(:_run_checkin_callbacks) do
+ conn.run_callbacks :checkin do
@checked_out.delete conn
@queue.signal
end
@@ -232,6 +291,8 @@ module ActiveRecord
end
def checkout_new_connection
+ raise ConnectionNotEstablished unless @automatic_reconnect
+
c = new_connection
@connections << c
checkout_and_verify(c)
@@ -330,7 +391,7 @@ module ActiveRecord
pool = @connection_pools[klass.name]
return nil unless pool
- @connection_pools.delete_if { |key, value| value == pool }
+ pool.automatic_reconnect = false
pool.disconnect!
pool.spec.config
end
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 ee9a0af35c..5c1ce173c8 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/module/deprecation'
+
module ActiveRecord
module ConnectionAdapters # :nodoc:
module DatabaseStatements
@@ -229,6 +231,8 @@ module ActiveRecord
#
# This method *modifies* the +sql+ parameter.
#
+ # This method is deprecated!! Stop using it!
+ #
# ===== Examples
# add_limit_offset!('SELECT * FROM suppliers', {:limit => 10, :offset => 50})
# generates
@@ -243,6 +247,7 @@ module ActiveRecord
end
sql
end
+ deprecate :add_limit_offset!
def default_sequence_name(table, column)
nil
@@ -256,7 +261,15 @@ module ActiveRecord
# Inserts the given fixture into the table. Overridden in adapters that require
# something beyond a simple insert (eg. Oracle).
def insert_fixture(fixture, table_name)
- execute "INSERT INTO #{quote_table_name(table_name)} (#{fixture.key_list}) VALUES (#{fixture.value_list})", 'Fixture Insert'
+ columns = Hash[columns(table_name).map { |c| [c.name, c] }]
+
+ key_list = []
+ value_list = fixture.map do |name, value|
+ key_list << quote_column_name(name)
+ quote(value, columns[name])
+ end
+
+ execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
end
def empty_insert_statement_value
@@ -271,6 +284,25 @@ module ActiveRecord
"WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
end
+ # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
+ #
+ # The +limit+ may be anything that can evaluate to a string via #to_s. It
+ # should look like an integer, or a comma-delimited list of integers, or
+ # an Arel SQL literal.
+ #
+ # Returns Integer and Arel::Nodes::SqlLiteral limits as is.
+ # Returns the sanitized limit parameter, either as an integer, or as a
+ # string which contains a comma-delimited list of integers.
+ def sanitize_limit(limit)
+ if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
+ limit
+ elsif limit.to_s =~ /,/
+ Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
+ else
+ Integer(limit)
+ end
+ end
+
protected
# Returns an array of record hashes with the column names as keys and
# column values as values.
@@ -294,21 +326,6 @@ module ActiveRecord
update_sql(sql, name)
end
- # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
- #
- # +limit+ may be anything that can evaluate to a string via #to_s. It
- # should look like an integer, or a comma-delimited list of integers.
- #
- # Returns the sanitized limit parameter, either as an integer, or as a
- # string which contains a comma-delimited list of integers.
- def sanitize_limit(limit)
- if limit.to_s =~ /,/
- limit.to_s.split(',').map{ |i| i.to_i }.join(',')
- else
- limit.to_i
- end
- end
-
# Send a rollback message to all records after they have been rolled back. If rollback
# is false, only rollback records since the last save point.
def rollback_transaction_records(rollback) #:nodoc
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 d555308485..1db397f584 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
@@ -60,7 +60,7 @@ module ActiveRecord
result =
if @query_cache[sql].key?(binds)
ActiveSupport::Notifications.instrument("sql.active_record",
- :sql => sql, :name => "CACHE", :connection_id => self.object_id)
+ :sql => sql, :name => "CACHE", :connection_id => object_id)
@query_cache[sql][binds]
else
@query_cache[sql][binds] = yield
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
index a7a12faac2..7489e88eef 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -33,8 +33,9 @@ module ActiveRecord
when BigDecimal then value.to_s('F')
when Numeric then value.to_s
when Date, Time then "'#{quoted_date(value)}'"
+ when Symbol then "'#{quote_string(value.to_s)}'"
else
- "'#{quote_string(value.to_s)}'"
+ "'#{quote_string(value.to_yaml)}'"
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 60ccf9edf3..7ac48c6646 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -6,264 +6,6 @@ require 'bigdecimal/util'
module ActiveRecord
module ConnectionAdapters #:nodoc:
- # An abstract definition of a column in a table.
- class Column
- TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
- FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
-
- module Format
- ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
- ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
- end
-
- attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
- attr_accessor :primary
-
- # Instantiates a new column in the table.
- #
- # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
- # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
- # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
- # <tt>company_name varchar(60)</tt>.
- # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
- # +null+ determines if this column allows +NULL+ values.
- def initialize(name, default, sql_type = nil, null = true)
- @name, @sql_type, @null = name, sql_type, null
- @limit, @precision, @scale = extract_limit(sql_type), extract_precision(sql_type), extract_scale(sql_type)
- @type = simplified_type(sql_type)
- @default = extract_default(default)
-
- @primary = nil
- end
-
- # Returns +true+ if the column is either of type string or text.
- def text?
- type == :string || type == :text
- end
-
- # Returns +true+ if the column is either of type integer, float or decimal.
- def number?
- type == :integer || type == :float || type == :decimal
- end
-
- def has_default?
- !default.nil?
- end
-
- # Returns the Ruby class that corresponds to the abstract data type.
- def klass
- case type
- when :integer then Fixnum
- when :float then Float
- when :decimal then BigDecimal
- when :datetime then Time
- when :date then Date
- when :timestamp then Time
- when :time then Time
- when :text, :string then String
- when :binary then String
- when :boolean then Object
- end
- end
-
- # Casts value (which is a String) to an appropriate instance.
- def type_cast(value)
- return nil if value.nil?
- case type
- when :string then value
- when :text then value
- when :integer then value.to_i rescue value ? 1 : 0
- when :float then value.to_f
- when :decimal then self.class.value_to_decimal(value)
- when :datetime then self.class.string_to_time(value)
- when :timestamp then self.class.string_to_time(value)
- when :time then self.class.string_to_dummy_time(value)
- when :date then self.class.string_to_date(value)
- when :binary then self.class.binary_to_string(value)
- when :boolean then self.class.value_to_boolean(value)
- else value
- end
- end
-
- def type_cast_code(var_name)
- case type
- when :string then nil
- when :text then nil
- when :integer then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
- when :float then "#{var_name}.to_f"
- when :decimal then "#{self.class.name}.value_to_decimal(#{var_name})"
- when :datetime then "#{self.class.name}.string_to_time(#{var_name})"
- when :timestamp then "#{self.class.name}.string_to_time(#{var_name})"
- when :time then "#{self.class.name}.string_to_dummy_time(#{var_name})"
- when :date then "#{self.class.name}.string_to_date(#{var_name})"
- when :binary then "#{self.class.name}.binary_to_string(#{var_name})"
- when :boolean then "#{self.class.name}.value_to_boolean(#{var_name})"
- else nil
- end
- end
-
- # Returns the human name of the column name.
- #
- # ===== Examples
- # Column.new('sales_stage', ...).human_name # => 'Sales stage'
- def human_name
- Base.human_attribute_name(@name)
- end
-
- def extract_default(default)
- type_cast(default)
- end
-
- # Used to convert from Strings to BLOBs
- def string_to_binary(value)
- self.class.string_to_binary(value)
- end
-
- class << self
- # Used to convert from Strings to BLOBs
- def string_to_binary(value)
- value
- end
-
- # Used to convert from BLOBs to Strings
- def binary_to_string(value)
- value
- end
-
- def string_to_date(string)
- return string unless string.is_a?(String)
- return nil if string.empty?
-
- fast_string_to_date(string) || fallback_string_to_date(string)
- end
-
- def string_to_time(string)
- return string unless string.is_a?(String)
- return nil if string.empty?
-
- fast_string_to_time(string) || fallback_string_to_time(string)
- end
-
- def string_to_dummy_time(string)
- return string unless string.is_a?(String)
- return nil if string.empty?
-
- string_to_time "2000-01-01 #{string}"
- end
-
- # convert something to a boolean
- def value_to_boolean(value)
- if value.is_a?(String) && value.blank?
- nil
- else
- TRUE_VALUES.include?(value)
- end
- end
-
- # convert something to a BigDecimal
- def value_to_decimal(value)
- # Using .class is faster than .is_a? and
- # subclasses of BigDecimal will be handled
- # in the else clause
- if value.class == BigDecimal
- value
- elsif value.respond_to?(:to_d)
- value.to_d
- else
- value.to_s.to_d
- end
- end
-
- protected
- # '0.123456' -> 123456
- # '1.123456' -> 123456
- def microseconds(time)
- ((time[:sec_fraction].to_f % 1) * 1_000_000).to_i
- end
-
- def new_date(year, mon, mday)
- if year && year != 0
- Date.new(year, mon, mday) rescue nil
- end
- end
-
- def new_time(year, mon, mday, hour, min, sec, microsec)
- # Treat 0000-00-00 00:00:00 as nil.
- return nil if year.nil? || year == 0
-
- Time.time_with_datetime_fallback(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
- end
-
- def fast_string_to_date(string)
- if string =~ Format::ISO_DATE
- new_date $1.to_i, $2.to_i, $3.to_i
- end
- end
-
- # 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
- new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
- end
- end
-
- def fallback_string_to_date(string)
- new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
- end
-
- def fallback_string_to_time(string)
- time_hash = Date._parse(string)
- time_hash[:sec_fraction] = microseconds(time_hash)
-
- new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
- end
- end
-
- private
- def extract_limit(sql_type)
- $1.to_i if sql_type =~ /\((.*)\)/
- end
-
- def extract_precision(sql_type)
- $2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
- end
-
- def extract_scale(sql_type)
- case sql_type
- when /^(numeric|decimal|number)\((\d+)\)/i then 0
- when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
- end
- end
-
- def simplified_type(field_type)
- case field_type
- when /int/i
- :integer
- when /float|double/i
- :float
- when /decimal|numeric|number/i
- extract_scale(field_type) == 0 ? :integer : :decimal
- when /datetime/i
- :datetime
- when /timestamp/i
- :timestamp
- when /time/i
- :time
- when /date/i
- :date
- when /clob/i, /text/i
- :text
- when /blob/i, /binary/i
- :binary
- when /char/i, /string/i
- :string
- when /boolean/i
- :boolean
- end
- end
- end
-
class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc:
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 5b9c48bafa..3ec7dd02a4 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -176,6 +176,13 @@ module ActiveRecord
# # Other column alterations here
# end
#
+ # The +options+ hash can include the following keys:
+ # [<tt>:bulk</tt>]
+ # Set this to true to make this a bulk alter query, such as
+ # ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
+ #
+ # Defaults to false.
+ #
# ===== Examples
# ====== Add a column
# change_table(:suppliers) do |t|
@@ -224,8 +231,14 @@ module ActiveRecord
#
# See also Table for details on
# all of the various column transformation
- def change_table(table_name)
- yield Table.new(table_name, self)
+ def change_table(table_name, options = {})
+ if supports_bulk_alter? && options[:bulk]
+ recorder = ActiveRecord::Migration::CommandRecorder.new(self)
+ yield Table.new(table_name, recorder)
+ bulk_change_table(table_name, recorder.commands)
+ else
+ yield Table.new(table_name, self)
+ end
end
# Renames a table.
@@ -253,10 +266,7 @@ module ActiveRecord
# remove_column(:suppliers, :qualification)
# remove_columns(:suppliers, :qualification, :experience)
def remove_column(table_name, *column_names)
- raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.empty?
- column_names.flatten.each do |column_name|
- execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}"
- end
+ columns_for_remove(table_name, *column_names).each {|column_name| execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{column_name}" }
end
alias :remove_columns :remove_column
@@ -327,25 +337,8 @@ module ActiveRecord
#
# Note: SQLite doesn't support index length
def add_index(table_name, column_name, options = {})
- column_names = Array.wrap(column_name)
- index_name = index_name(table_name, :column => column_names)
-
- if Hash === options # legacy support, since this param was a string
- index_type = options[:unique] ? "UNIQUE" : ""
- index_name = options[:name].to_s if options.key?(:name)
- else
- index_type = options
- end
-
- if index_name.length > index_name_length
- raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters"
- end
- if index_name_exists?(table_name, index_name, false)
- raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
- end
- quoted_column_names = quoted_columns_for_index(column_names, options).join(", ")
-
- execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{quoted_column_names})"
+ index_name, index_type, index_columns = add_index_options(table_name, column_name, options)
+ execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})"
end
# Remove the given index from the table.
@@ -359,11 +352,7 @@ module ActiveRecord
# Remove the index named by_branch_party in the accounts table.
# remove_index :accounts, :name => :by_branch_party
def remove_index(table_name, options = {})
- index_name = index_name(table_name, options)
- unless index_name_exists?(table_name, index_name, true)
- raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
- end
- remove_index!(table_name, index_name)
+ remove_index!(table_name, index_name_for_remove(table_name, options))
end
def remove_index!(table_name, index_name) #:nodoc:
@@ -469,7 +458,7 @@ module ActiveRecord
end
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
- if native = native_database_types[type]
+ if native = native_database_types[type.to_sym]
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
if type == :decimal # ignore limit, use precision and scale
@@ -537,6 +526,45 @@ module ActiveRecord
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
end
+ def add_index_options(table_name, column_name, options = {})
+ column_names = Array.wrap(column_name)
+ index_name = index_name(table_name, :column => column_names)
+
+ if Hash === options # legacy support, since this param was a string
+ index_type = options[:unique] ? "UNIQUE" : ""
+ index_name = options[:name].to_s if options.key?(:name)
+ else
+ index_type = options
+ end
+
+ if index_name.length > index_name_length
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters"
+ end
+ if index_name_exists?(table_name, index_name, false)
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
+ end
+ index_columns = quoted_columns_for_index(column_names, options).join(", ")
+
+ [index_name, index_type, index_columns]
+ end
+
+ def index_name_for_remove(table_name, options = {})
+ index_name = index_name(table_name, options)
+
+ unless index_name_exists?(table_name, index_name, true)
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
+ end
+
+ index_name
+ end
+
+ def columns_for_remove(table_name, *column_names)
+ column_names = column_names.flatten
+
+ raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.blank?
+ column_names.map {|column_name| quote_column_name(column_name) }
+ end
+
private
def table_definition
TableDefinition.new(self)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 0282493219..0f44baa2fe 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -4,6 +4,7 @@ require 'bigdecimal/util'
require 'active_support/core_ext/benchmark'
# TODO: Autoload these files
+require 'active_record/connection_adapters/column'
require 'active_record/connection_adapters/abstract/schema_definitions'
require 'active_record/connection_adapters/abstract/schema_statements'
require 'active_record/connection_adapters/abstract/database_statements'
@@ -77,8 +78,12 @@ module ActiveRecord
false
end
- # Does this adapter support savepoints? PostgreSQL and MySQL do, SQLite
- # does not.
+ def supports_bulk_alter?
+ false
+ end
+
+ # Does this adapter support savepoints? PostgreSQL and MySQL do,
+ # SQLite < 3.6.8 does not.
def supports_savepoints?
false
end
@@ -204,11 +209,13 @@ module ActiveRecord
protected
- def log(sql, name = "SQL")
- @instrumenter.instrument("sql.active_record",
- :sql => sql, :name => name, :connection_id => object_id) do
- yield
- end
+ def log(sql, name = "SQL", binds = [])
+ @instrumenter.instrument(
+ "sql.active_record",
+ :sql => sql,
+ :name => name,
+ :connection_id => object_id,
+ :binds => binds) { yield }
rescue Exception => e
message = "#{e.class.name}: #{e.message}: #{sql}"
@logger.debug message if @logger
diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb
new file mode 100644
index 0000000000..4e3d8a096f
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/column.rb
@@ -0,0 +1,268 @@
+module ActiveRecord
+ # :stopdoc:
+ module ConnectionAdapters
+ # An abstract definition of a column in a table.
+ class Column
+ TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
+ FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
+
+ module Format
+ ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/
+ ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
+ end
+
+ attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
+ attr_accessor :primary, :coder
+
+ alias :encoded? :coder
+
+ # Instantiates a new column in the table.
+ #
+ # +name+ is the column's name, such as <tt>supplier_id</tt> in <tt>supplier_id int(11)</tt>.
+ # +default+ is the type-casted default value, such as +new+ in <tt>sales_stage varchar(20) default 'new'</tt>.
+ # +sql_type+ is used to extract the column's length, if necessary. For example +60+ in
+ # <tt>company_name varchar(60)</tt>.
+ # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
+ # +null+ determines if this column allows +NULL+ values.
+ def initialize(name, default, sql_type = nil, null = true)
+ @name = name
+ @sql_type = sql_type
+ @null = null
+ @limit = extract_limit(sql_type)
+ @precision = extract_precision(sql_type)
+ @scale = extract_scale(sql_type)
+ @type = simplified_type(sql_type)
+ @default = extract_default(default)
+ @primary = nil
+ @coder = nil
+ end
+
+ # Returns +true+ if the column is either of type string or text.
+ def text?
+ type == :string || type == :text
+ end
+
+ # Returns +true+ if the column is either of type integer, float or decimal.
+ def number?
+ type == :integer || type == :float || type == :decimal
+ end
+
+ def has_default?
+ !default.nil?
+ end
+
+ # Returns the Ruby class that corresponds to the abstract data type.
+ def klass
+ case type
+ when :integer then Fixnum
+ when :float then Float
+ when :decimal then BigDecimal
+ when :datetime, :timestamp, :time then Time
+ when :date then Date
+ when :text, :string, :binary then String
+ when :boolean then Object
+ end
+ end
+
+ # Casts value (which is a String) to an appropriate instance.
+ def type_cast(value)
+ return nil if value.nil?
+ return coder.load(value) if encoded?
+
+ klass = self.class
+
+ case type
+ when :string, :text then value
+ when :integer then value.to_i rescue value ? 1 : 0
+ when :float then value.to_f
+ when :decimal then klass.value_to_decimal(value)
+ when :datetime, :timestamp then klass.string_to_time(value)
+ when :time then klass.string_to_dummy_time(value)
+ when :date then klass.string_to_date(value)
+ when :binary then klass.binary_to_string(value)
+ when :boolean then klass.value_to_boolean(value)
+ else value
+ end
+ end
+
+ def type_cast_code(var_name)
+ klass = self.class.name
+
+ case type
+ when :string, :text then var_name
+ when :integer then "(#{var_name}.to_i rescue #{var_name} ? 1 : 0)"
+ when :float then "#{var_name}.to_f"
+ when :decimal then "#{klass}.value_to_decimal(#{var_name})"
+ when :datetime, :timestamp then "#{klass}.string_to_time(#{var_name})"
+ when :time then "#{klass}.string_to_dummy_time(#{var_name})"
+ when :date then "#{klass}.string_to_date(#{var_name})"
+ when :binary then "#{klass}.binary_to_string(#{var_name})"
+ when :boolean then "#{klass}.value_to_boolean(#{var_name})"
+ else var_name
+ end
+ end
+
+ # Returns the human name of the column name.
+ #
+ # ===== Examples
+ # Column.new('sales_stage', ...).human_name # => 'Sales stage'
+ def human_name
+ Base.human_attribute_name(@name)
+ end
+
+ def extract_default(default)
+ type_cast(default)
+ end
+
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ self.class.string_to_binary(value)
+ end
+
+ class << self
+ # Used to convert from Strings to BLOBs
+ def string_to_binary(value)
+ value
+ end
+
+ # Used to convert from BLOBs to Strings
+ def binary_to_string(value)
+ value
+ end
+
+ def string_to_date(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ fast_string_to_date(string) || fallback_string_to_date(string)
+ end
+
+ def string_to_time(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ fast_string_to_time(string) || fallback_string_to_time(string)
+ end
+
+ def string_to_dummy_time(string)
+ return string unless string.is_a?(String)
+ return nil if string.empty?
+
+ string_to_time "2000-01-01 #{string}"
+ end
+
+ # convert something to a boolean
+ def value_to_boolean(value)
+ if value.is_a?(String) && value.blank?
+ nil
+ else
+ TRUE_VALUES.include?(value)
+ end
+ end
+
+ # convert something to a BigDecimal
+ def value_to_decimal(value)
+ # Using .class is faster than .is_a? and
+ # subclasses of BigDecimal will be handled
+ # in the else clause
+ if value.class == BigDecimal
+ value
+ elsif value.respond_to?(:to_d)
+ value.to_d
+ else
+ value.to_s.to_d
+ end
+ end
+
+ protected
+ # '0.123456' -> 123456
+ # '1.123456' -> 123456
+ def microseconds(time)
+ ((time[:sec_fraction].to_f % 1) * 1_000_000).to_i
+ end
+
+ def new_date(year, mon, mday)
+ if year && year != 0
+ Date.new(year, mon, mday) rescue nil
+ end
+ end
+
+ def new_time(year, mon, mday, hour, min, sec, microsec)
+ # Treat 0000-00-00 00:00:00 as nil.
+ return nil if year.nil? || year == 0
+
+ Time.time_with_datetime_fallback(Base.default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil
+ end
+
+ def fast_string_to_date(string)
+ if string =~ Format::ISO_DATE
+ new_date $1.to_i, $2.to_i, $3.to_i
+ end
+ end
+
+ # 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
+ new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec
+ end
+ end
+
+ def fallback_string_to_date(string)
+ new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday))
+ end
+
+ def fallback_string_to_time(string)
+ time_hash = Date._parse(string)
+ time_hash[:sec_fraction] = microseconds(time_hash)
+
+ new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction))
+ end
+ end
+
+ private
+ def extract_limit(sql_type)
+ $1.to_i if sql_type =~ /\((.*)\)/
+ end
+
+ def extract_precision(sql_type)
+ $2.to_i if sql_type =~ /^(numeric|decimal|number)\((\d+)(,\d+)?\)/i
+ end
+
+ def extract_scale(sql_type)
+ case sql_type
+ when /^(numeric|decimal|number)\((\d+)\)/i then 0
+ when /^(numeric|decimal|number)\((\d+)(,(\d+))\)/i then $4.to_i
+ end
+ end
+
+ def simplified_type(field_type)
+ case field_type
+ when /int/i
+ :integer
+ when /float|double/i
+ :float
+ when /decimal|numeric|number/i
+ extract_scale(field_type) == 0 ? :integer : :decimal
+ when /datetime/i
+ :datetime
+ when /timestamp/i
+ :timestamp
+ when /time/i
+ :time
+ when /date/i
+ :date
+ when /clob/i, /text/i
+ :text
+ when /blob/i, /binary/i
+ :binary
+ when /char/i, /string/i
+ :string
+ when /boolean/i
+ :boolean
+ end
+ end
+ end
+ end
+ # :startdoc:
+end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
new file mode 100644
index 0000000000..7bad511c64
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -0,0 +1,610 @@
+# encoding: utf-8
+
+require 'mysql2'
+
+module ActiveRecord
+ class Base
+ def self.mysql2_connection(config)
+ config[:username] = 'root' if config[:username].nil?
+
+ if Mysql2::Client.const_defined? :FOUND_ROWS
+ config[:flags] = Mysql2::Client::FOUND_ROWS
+ end
+
+ client = Mysql2::Client.new(config.symbolize_keys)
+ options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
+ ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
+ end
+ end
+
+ module ConnectionAdapters
+ class Mysql2IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc:
+ end
+
+ class Mysql2Column < Column
+ BOOL = "tinyint(1)"
+ def extract_default(default)
+ if sql_type =~ /blob/i || type == :text
+ if default.blank?
+ return null ? nil : ''
+ else
+ raise ArgumentError, "#{type} columns cannot have a default value: #{default.inspect}"
+ end
+ elsif missing_default_forged_as_empty_string?(default)
+ nil
+ else
+ super
+ end
+ end
+
+ def has_default?
+ return false if sql_type =~ /blob/i || type == :text #mysql forbids defaults on blob and text columns
+ super
+ end
+
+ private
+ def simplified_type(field_type)
+ return :boolean if Mysql2Adapter.emulate_booleans && field_type.downcase.index(BOOL)
+
+ case field_type
+ when /enum/i, /set/i then :string
+ when /year/i then :integer
+ when /bit/i then :binary
+ else
+ super
+ end
+ end
+
+ def extract_limit(sql_type)
+ case sql_type
+ when /blob|text/i
+ case sql_type
+ when /tiny/i
+ 255
+ when /medium/i
+ 16777215
+ when /long/i
+ 2147483647 # mysql only allows 2^31-1, not 2^32-1, somewhat inconsistently with the tiny/medium/normal cases
+ else
+ super # we could return 65535 here, but we leave it undecorated by default
+ end
+ when /^bigint/i; 8
+ when /^int/i; 4
+ when /^mediumint/i; 3
+ when /^smallint/i; 2
+ when /^tinyint/i; 1
+ else
+ super
+ end
+ end
+
+ # MySQL misreports NOT NULL column default when none is given.
+ # We can't detect this for columns which may have a legitimate ''
+ # default (string) but we can for others (integer, datetime, boolean,
+ # and the rest).
+ #
+ # Test whether the column has default '', is not null, and is not
+ # a type allowing default ''.
+ def missing_default_forged_as_empty_string?(default)
+ type != :string && !null && default == ''
+ end
+ end
+
+ class Mysql2Adapter < AbstractAdapter
+ cattr_accessor :emulate_booleans
+ self.emulate_booleans = true
+
+ ADAPTER_NAME = 'Mysql2'
+ PRIMARY = "PRIMARY"
+
+ LOST_CONNECTION_ERROR_MESSAGES = [
+ "Server shutdown in progress",
+ "Broken pipe",
+ "Lost connection to MySQL server during query",
+ "MySQL server has gone away" ]
+
+ QUOTED_TRUE, QUOTED_FALSE = '1', '0'
+
+ NATIVE_DATABASE_TYPES = {
+ :primary_key => "int(11) DEFAULT NULL auto_increment PRIMARY KEY",
+ :string => { :name => "varchar", :limit => 255 },
+ :text => { :name => "text" },
+ :integer => { :name => "int", :limit => 4 },
+ :float => { :name => "float" },
+ :decimal => { :name => "decimal" },
+ :datetime => { :name => "datetime" },
+ :timestamp => { :name => "datetime" },
+ :time => { :name => "time" },
+ :date => { :name => "date" },
+ :binary => { :name => "blob" },
+ :boolean => { :name => "tinyint", :limit => 1 }
+ }
+
+ def initialize(connection, logger, connection_options, config)
+ super(connection, logger)
+ @connection_options, @config = connection_options, config
+ @quoted_column_names, @quoted_table_names = {}, {}
+ configure_connection
+ end
+
+ def adapter_name
+ ADAPTER_NAME
+ end
+
+ def supports_migrations?
+ true
+ end
+
+ def supports_primary_key?
+ true
+ end
+
+ def supports_savepoints?
+ true
+ end
+
+ def native_database_types
+ NATIVE_DATABASE_TYPES
+ end
+
+ # QUOTING ==================================================
+
+ def quote(value, column = nil)
+ if value.kind_of?(String) && column && column.type == :binary && column.class.respond_to?(:string_to_binary)
+ s = column.class.string_to_binary(value).unpack("H*")[0]
+ "x'#{s}'"
+ elsif value.kind_of?(BigDecimal)
+ value.to_s("F")
+ else
+ super
+ end
+ end
+
+ def quote_column_name(name) #:nodoc:
+ @quoted_column_names[name] ||= "`#{name}`"
+ end
+
+ def quote_table_name(name) #:nodoc:
+ @quoted_table_names[name] ||= quote_column_name(name).gsub('.', '`.`')
+ end
+
+ def quote_string(string)
+ @connection.escape(string)
+ end
+
+ def quoted_true
+ QUOTED_TRUE
+ end
+
+ def quoted_false
+ QUOTED_FALSE
+ end
+
+ # REFERENTIAL INTEGRITY ====================================
+
+ def disable_referential_integrity(&block) #:nodoc:
+ old = select_value("SELECT @@FOREIGN_KEY_CHECKS")
+
+ begin
+ update("SET FOREIGN_KEY_CHECKS = 0")
+ yield
+ ensure
+ update("SET FOREIGN_KEY_CHECKS = #{old}")
+ end
+ end
+
+ # CONNECTION MANAGEMENT ====================================
+
+ def active?
+ return false unless @connection
+ @connection.ping
+ end
+
+ def reconnect!
+ disconnect!
+ connect
+ end
+
+ # this is set to true in 2.3, but we don't want it to be
+ def requires_reloading?
+ false
+ end
+
+ def disconnect!
+ unless @connection.nil?
+ @connection.close
+ @connection = nil
+ end
+ end
+
+ def reset!
+ disconnect!
+ connect
+ end
+
+ # DATABASE STATEMENTS ======================================
+
+ # FIXME: re-enable the following once a "better" query_cache solution is in core
+ #
+ # The overrides below perform much better than the originals in AbstractAdapter
+ # because we're able to take advantage of mysql2's lazy-loading capabilities
+ #
+ # # Returns a record hash with the column names as keys and column values
+ # # as values.
+ # def select_one(sql, name = nil)
+ # result = execute(sql, name)
+ # result.each(:as => :hash) do |r|
+ # return r
+ # end
+ # end
+ #
+ # # Returns a single value from a record
+ # def select_value(sql, name = nil)
+ # result = execute(sql, name)
+ # if first = result.first
+ # first.first
+ # end
+ # end
+ #
+ # # Returns an array of the values of the first column in a select:
+ # # select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
+ # def select_values(sql, name = nil)
+ # execute(sql, name).map { |row| row.first }
+ # end
+
+ # Returns an array of arrays containing the field values.
+ # Order is the same as that returned by +columns+.
+ def select_rows(sql, name = nil)
+ execute(sql, name).to_a
+ end
+
+ # Executes the SQL statement in the context of this connection.
+ def execute(sql, name = nil)
+ # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
+ # made since we established the connection
+ @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
+ if name == :skip_logging
+ @connection.query(sql)
+ else
+ log(sql, name) { @connection.query(sql) }
+ end
+ rescue ActiveRecord::StatementInvalid => exception
+ if exception.message.split(":").first =~ /Packets out of order/
+ raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings."
+ else
+ raise
+ end
+ end
+
+ def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
+ super
+ id_value || @connection.last_id
+ end
+ alias :create :insert_sql
+
+ def update_sql(sql, name = nil)
+ super
+ @connection.affected_rows
+ end
+
+ def begin_db_transaction
+ execute "BEGIN"
+ rescue Exception
+ # Transactions aren't supported
+ end
+
+ def commit_db_transaction
+ execute "COMMIT"
+ rescue Exception
+ # Transactions aren't supported
+ end
+
+ def rollback_db_transaction
+ execute "ROLLBACK"
+ rescue Exception
+ # Transactions aren't supported
+ end
+
+ def create_savepoint
+ execute("SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def rollback_to_savepoint
+ execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def release_savepoint
+ execute("RELEASE SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def add_limit_offset!(sql, options)
+ limit, offset = options[:limit], options[:offset]
+ if limit && offset
+ sql << " LIMIT #{offset.to_i}, #{sanitize_limit(limit)}"
+ elsif limit
+ sql << " LIMIT #{sanitize_limit(limit)}"
+ elsif offset
+ sql << " OFFSET #{offset.to_i}"
+ end
+ sql
+ end
+ deprecate :add_limit_offset!
+
+ # SCHEMA STATEMENTS ========================================
+
+ def structure_dump
+ if supports_views?
+ sql = "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"
+ else
+ sql = "SHOW TABLES"
+ end
+
+ select_all(sql).inject("") do |structure, table|
+ table.delete('Table_type')
+ structure += select_one("SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}")["Create Table"] + ";\n\n"
+ end
+ end
+
+ def recreate_database(name, options = {})
+ drop_database(name)
+ create_database(name, options)
+ end
+
+ # Create a new MySQL database with optional <tt>:charset</tt> and <tt>:collation</tt>.
+ # Charset defaults to utf8.
+ #
+ # Example:
+ # create_database 'charset_test', :charset => 'latin1', :collation => 'latin1_bin'
+ # create_database 'matt_development'
+ # create_database 'matt_development', :charset => :big5
+ def create_database(name, options = {})
+ if options[:collation]
+ execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}` COLLATE `#{options[:collation]}`"
+ else
+ execute "CREATE DATABASE `#{name}` DEFAULT CHARACTER SET `#{options[:charset] || 'utf8'}`"
+ end
+ end
+
+ def drop_database(name) #:nodoc:
+ execute "DROP DATABASE IF EXISTS `#{name}`"
+ end
+
+ def current_database
+ select_value 'SELECT DATABASE() as db'
+ end
+
+ # Returns the database character set.
+ def charset
+ show_variable 'character_set_database'
+ end
+
+ # Returns the database collation strategy.
+ def collation
+ show_variable 'collation_database'
+ end
+
+ def tables(name = nil)
+ tables = []
+ execute("SHOW TABLES", name).each do |field|
+ tables << field.first
+ end
+ tables
+ end
+
+ def drop_table(table_name, options = {})
+ super(table_name, options)
+ end
+
+ def indexes(table_name, name = nil)
+ indexes = []
+ current_index = nil
+ result = execute("SHOW KEYS FROM #{quote_table_name(table_name)}", name)
+ result.each(:symbolize_keys => true, :as => :hash) do |row|
+ if current_index != row[:Key_name]
+ next if row[:Key_name] == PRIMARY # skip the primary key
+ current_index = row[:Key_name]
+ indexes << Mysql2IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique] == 0, [], [])
+ end
+
+ indexes.last.columns << row[:Column_name]
+ indexes.last.lengths << row[:Sub_part]
+ end
+ indexes
+ end
+
+ def columns(table_name, name = nil)
+ sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
+ columns = []
+ result = execute(sql)
+ result.each(:symbolize_keys => true, :as => :hash) { |field|
+ columns << Mysql2Column.new(field[:Field], field[:Default], field[:Type], field[:Null] == "YES")
+ }
+ columns
+ end
+
+ def create_table(table_name, options = {})
+ super(table_name, options.reverse_merge(:options => "ENGINE=InnoDB"))
+ end
+
+ def rename_table(table_name, new_name)
+ execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
+ end
+
+ def add_column(table_name, column_name, type, options = {})
+ add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(add_column_sql, options)
+ add_column_position!(add_column_sql, options)
+ execute(add_column_sql)
+ end
+
+ def change_column_default(table_name, column_name, default)
+ column = column_for(table_name, column_name)
+ change_column table_name, column_name, column.sql_type, :default => default
+ end
+
+ def change_column_null(table_name, column_name, null, default = nil)
+ column = column_for(table_name, column_name)
+
+ unless null || default.nil?
+ execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
+ end
+
+ change_column table_name, column_name, column.sql_type, :null => null
+ end
+
+ def change_column(table_name, column_name, type, options = {})
+ column = column_for(table_name, column_name)
+
+ unless options_include_default?(options)
+ options[:default] = column.default
+ end
+
+ unless options.has_key?(:null)
+ options[:null] = column.null
+ end
+
+ change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(change_column_sql, options)
+ add_column_position!(change_column_sql, options)
+ execute(change_column_sql)
+ end
+
+ def rename_column(table_name, column_name, new_column_name)
+ options = {}
+ if column = columns(table_name).find { |c| c.name == column_name.to_s }
+ options[:default] = column.default
+ options[:null] = column.null
+ else
+ raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
+ end
+ current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
+ rename_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
+ add_column_options!(rename_column_sql, options)
+ execute(rename_column_sql)
+ end
+
+ # Maps logical Rails types to MySQL-specific data types.
+ def type_to_sql(type, limit = nil, precision = nil, scale = nil)
+ return super unless type.to_s == 'integer'
+
+ case limit
+ when 1; 'tinyint'
+ when 2; 'smallint'
+ when 3; 'mediumint'
+ when nil, 4, 11; 'int(11)' # compatibility with MySQL default
+ when 5..8; 'bigint'
+ else raise(ActiveRecordError, "No integer type has byte size #{limit}")
+ end
+ end
+
+ def add_column_position!(sql, options)
+ if options[:first]
+ sql << " FIRST"
+ elsif options[:after]
+ sql << " AFTER #{quote_column_name(options[:after])}"
+ end
+ end
+
+ def show_variable(name)
+ variables = select_all("SHOW VARIABLES LIKE '#{name}'")
+ variables.first['Value'] unless variables.empty?
+ end
+
+ def pk_and_sequence_for(table)
+ keys = []
+ result = execute("describe #{quote_table_name(table)}")
+ result.each(:symbolize_keys => true, :as => :hash) do |row|
+ keys << row[:Field] if row[:Key] == "PRI"
+ end
+ keys.length == 1 ? [keys.first, nil] : nil
+ end
+
+ # Returns just a table's primary key
+ def primary_key(table)
+ pk_and_sequence = pk_and_sequence_for(table)
+ pk_and_sequence && pk_and_sequence.first
+ end
+
+ def case_sensitive_equality_operator
+ "= BINARY"
+ end
+
+ def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
+ where_sql
+ end
+
+ protected
+ def quoted_columns_for_index(column_names, options = {})
+ length = options[:length] if options.is_a?(Hash)
+
+ quoted_column_names = case length
+ when Hash
+ column_names.map {|name| length[name] ? "#{quote_column_name(name)}(#{length[name]})" : quote_column_name(name) }
+ when Fixnum
+ column_names.map {|name| "#{quote_column_name(name)}(#{length})"}
+ else
+ column_names.map {|name| quote_column_name(name) }
+ end
+ end
+
+ def translate_exception(exception, message)
+ return super unless exception.respond_to?(:error_number)
+
+ case exception.error_number
+ when 1062
+ RecordNotUnique.new(message, exception)
+ when 1452
+ InvalidForeignKey.new(message, exception)
+ else
+ super
+ end
+ end
+
+ private
+ def connect
+ @connection = Mysql2::Client.new(@config)
+ configure_connection
+ end
+
+ def configure_connection
+ @connection.query_options.merge!(:as => :array)
+
+ # By default, MySQL 'where id is null' selects the last inserted id.
+ # Turn this off. http://dev.rubyonrails.org/ticket/6778
+ variable_assignments = ['SQL_AUTO_IS_NULL=0']
+ encoding = @config[:encoding]
+
+ # make sure we set the encoding
+ variable_assignments << "NAMES '#{encoding}'" if encoding
+
+ # increase timeout so mysql server doesn't disconnect us
+ wait_timeout = @config[:wait_timeout]
+ wait_timeout = 2592000 unless wait_timeout.is_a?(Fixnum)
+ variable_assignments << "@@wait_timeout = #{wait_timeout}"
+
+ execute("SET #{variable_assignments.join(', ')}", :skip_logging)
+ end
+
+ # Returns an array of record hashes with the column names as keys and
+ # column values as values.
+ def select(sql, name = nil)
+ execute(sql, name).each(:as => :hash)
+ end
+
+ def supports_views?
+ version[0] >= 5
+ end
+
+ def version
+ @version ||= @connection.info[:version].scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
+ end
+
+ def column_for(table_name, column_name)
+ unless column = columns(table_name).find { |c| c.name == column_name.to_s }
+ raise "No such column: #{table_name}.#{column_name}"
+ end
+ column
+ end
+ end
+ 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 ce2352486b..368c5b2023 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -203,6 +203,10 @@ module ActiveRecord
ADAPTER_NAME
end
+ def supports_bulk_alter? #:nodoc:
+ true
+ end
+
# Returns +true+ when the connection adapter supports prepared statement
# caching, otherwise returns +false+
def supports_statement_cache?
@@ -327,7 +331,7 @@ module ActiveRecord
end
def exec_query(sql, name = 'SQL', binds = [])
- log(sql, name) do
+ log(sql, name, binds) do
result = nil
cache = {}
@@ -364,9 +368,14 @@ module ActiveRecord
# statement API. For those queries, we need to use this method. :'(
log(sql, name) do
result = @connection.query(sql)
- cols = result.fetch_fields.map { |field| field.name }
- rows = result.to_a
- result.free
+ cols = []
+ rows = []
+
+ if result
+ cols = result.fetch_fields.map { |field| field.name }
+ rows = result.to_a
+ result.free
+ end
ActiveRecord::Result.new(cols, rows)
end
end
@@ -400,7 +409,7 @@ module ActiveRecord
def begin_db_transaction #:nodoc:
exec_without_stmt "BEGIN"
- rescue Exception
+ rescue Mysql::Error
# Transactions aren't supported
end
@@ -439,6 +448,7 @@ module ActiveRecord
end
sql
end
+ deprecate :add_limit_offset!
# SCHEMA STATEMENTS ========================================
@@ -527,7 +537,7 @@ module ActiveRecord
def columns(table_name, name = nil)#:nodoc:
sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
columns = []
- result = execute(sql, :skip_logging)
+ result = execute(sql)
result.each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") }
result.free
columns
@@ -541,11 +551,23 @@ module ActiveRecord
execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}"
end
+ def bulk_change_table(table_name, operations) #:nodoc:
+ sqls = operations.map do |command, args|
+ table, arguments = args.shift, args
+ method = :"#{command}_sql"
+
+ if respond_to?(method)
+ send(method, table, *arguments)
+ else
+ raise "Unknown method called : #{method}(#{arguments.inspect})"
+ end
+ end.flatten.join(", ")
+
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{sqls}")
+ end
+
def add_column(table_name, column_name, type, options = {})
- add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
- add_column_options!(add_column_sql, options)
- add_column_position!(add_column_sql, options)
- execute(add_column_sql)
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{add_column_sql(table_name, column_name, type, options)}")
end
def change_column_default(table_name, column_name, default) #:nodoc:
@@ -564,34 +586,11 @@ module ActiveRecord
end
def change_column(table_name, column_name, type, options = {}) #:nodoc:
- column = column_for(table_name, column_name)
-
- unless options_include_default?(options)
- options[:default] = column.default
- end
-
- unless options.has_key?(:null)
- options[:null] = column.null
- end
-
- change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
- add_column_options!(change_column_sql, options)
- add_column_position!(change_column_sql, options)
- execute(change_column_sql)
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_sql(table_name, column_name, type, options)}")
end
def rename_column(table_name, column_name, new_column_name) #:nodoc:
- options = {}
- if column = columns(table_name).find { |c| c.name == column_name.to_s }
- options[:default] = column.default
- options[:null] = column.null
- else
- raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
- end
- current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
- rename_column_sql = "ALTER TABLE #{quote_table_name(table_name)} CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
- add_column_options!(rename_column_sql, options)
- execute(rename_column_sql)
+ execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name, new_column_name)}")
end
# Maps logical Rails types to MySQL-specific data types.
@@ -674,6 +673,69 @@ module ActiveRecord
end
end
+ def add_column_sql(table_name, column_name, type, options = {})
+ add_column_sql = "ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(add_column_sql, options)
+ add_column_position!(add_column_sql, options)
+ add_column_sql
+ end
+
+ def remove_column_sql(table_name, *column_names)
+ columns_for_remove(table_name, *column_names).map {|column_name| "DROP #{column_name}" }
+ end
+ alias :remove_columns_sql :remove_column
+
+ def change_column_sql(table_name, column_name, type, options = {})
+ column = column_for(table_name, column_name)
+
+ unless options_include_default?(options)
+ options[:default] = column.default
+ end
+
+ unless options.has_key?(:null)
+ options[:null] = column.null
+ end
+
+ change_column_sql = "CHANGE #{quote_column_name(column_name)} #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(change_column_sql, options)
+ add_column_position!(change_column_sql, options)
+ change_column_sql
+ end
+
+ def rename_column_sql(table_name, column_name, new_column_name)
+ options = {}
+
+ if column = columns(table_name).find { |c| c.name == column_name.to_s }
+ options[:default] = column.default
+ options[:null] = column.null
+ else
+ raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
+ end
+
+ current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'")["Type"]
+ rename_column_sql = "CHANGE #{quote_column_name(column_name)} #{quote_column_name(new_column_name)} #{current_type}"
+ add_column_options!(rename_column_sql, options)
+ rename_column_sql
+ end
+
+ def add_index_sql(table_name, column_name, options = {})
+ index_name, index_type, index_columns = add_index_options(table_name, column_name, options)
+ "ADD #{index_type} INDEX #{index_name} (#{index_columns})"
+ end
+
+ def remove_index_sql(table_name, options = {})
+ index_name = index_name_for_remove(table_name, options)
+ "DROP INDEX #{index_name}"
+ end
+
+ def add_timestamps_sql(table_name)
+ [add_column_sql(table_name, :created_at, :datetime), add_column_sql(table_name, :updated_at, :datetime)]
+ end
+
+ def remove_timestamps_sql(table_name)
+ [remove_column_sql(table_name, :updated_at), remove_column_sql(table_name, :created_at)]
+ end
+
private
def connect
encoding = @config[:encoding]
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index a4b1aa7154..576450bc3a 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -532,7 +532,7 @@ module ActiveRecord
def exec_query(sql, name = 'SQL', binds = [])
return exec_no_cache(sql, name) if binds.empty?
- log(sql, name) do
+ log(sql, name, binds) do
unless @statements.key? sql
nextkey = "a#{@statements.length + 1}"
@connection.prepare nextkey, sql
@@ -786,7 +786,7 @@ module ActiveRecord
def pk_and_sequence_for(table) #:nodoc:
# First try looking for a sequence with a dependency on the
# given table's primary key.
- result = query(<<-end_sql, 'PK and serial sequence')[0]
+ result = exec_query(<<-end_sql, 'PK and serial sequence').rows.first
SELECT attr.attname, seq.relname
FROM pg_class seq,
pg_attribute attr,
@@ -845,14 +845,18 @@ module ActiveRecord
# Adds a new column to the named table.
# See TableDefinition#column for details of the options you can use.
def add_column(table_name, column_name, type, options = {})
- default = options[:default]
- notnull = options[:null] == false
+ add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+ add_column_options!(add_column_sql, options)
- # Add the column.
- execute("ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}")
+ begin
+ execute add_column_sql
+ rescue ActiveRecord::StatementInvalid => e
+ raise e if postgresql_version > 80000
- change_column_default(table_name, column_name, default) if options_include_default?(options)
- change_column_null(table_name, column_name, false, default) if notnull
+ execute("ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}")
+ change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
+ change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
+ end
end
# Changes the column of a table.
@@ -1071,7 +1075,7 @@ module ActiveRecord
# - format_type includes the column size constraint, e.g. varchar(50)
# - ::regclass is a function that gives the id for a table name
def column_definitions(table_name) #:nodoc:
- query <<-end_sql
+ exec_query(<<-end_sql).rows
SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index d76fc4103e..9ee6b88ab6 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -62,6 +62,10 @@ module ActiveRecord
sqlite_version >= '2.0.0'
end
+ def supports_savepoints?
+ sqlite_version >= '3.6.8'
+ end
+
# Returns +true+ when the connection adapter supports prepared statement
# caching, otherwise returns +false+
def supports_statement_cache?
@@ -144,12 +148,15 @@ module ActiveRecord
# DATABASE STATEMENTS ======================================
def exec_query(sql, name = nil, binds = [])
- log(sql, name) do
+ log(sql, name, binds) do
# Don't cache statements without bind values
if binds.empty?
- stmt = @connection.prepare(sql)
- cols = stmt.columns
+ stmt = @connection.prepare(sql)
+ cols = stmt.columns
+ records = stmt.to_a
+ stmt.close
+ stmt = records
else
cache = @statements[sql] ||= {
:stmt => @connection.prepare(sql)
@@ -189,6 +196,18 @@ module ActiveRecord
exec_query(sql, name).rows
end
+ def create_savepoint
+ execute("SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def rollback_to_savepoint
+ execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
+ end
+
+ def release_savepoint
+ execute("RELEASE SAVEPOINT #{current_savepoint_name}")
+ end
+
def begin_db_transaction #:nodoc:
@connection.transaction
end
@@ -217,6 +236,15 @@ module ActiveRecord
def columns(table_name, name = nil) #:nodoc:
table_structure(table_name).map do |field|
+ case field["dflt_value"]
+ when /^null$/i
+ field["dflt_value"] = nil
+ when /^'(.*)'$/
+ field["dflt_value"] = $1.gsub(/''/, "'")
+ when /^"(.*)"$/
+ field["dflt_value"] = $1.gsub(/""/, '"')
+ end
+
SQLiteColumn.new(field['name'], field['dflt_value'], field['type'], field['notnull'].to_i == 0)
end
end
@@ -314,16 +342,11 @@ module ActiveRecord
protected
def select(sql, name = nil, binds = []) #:nodoc:
- result = exec_query(sql, name, binds)
- columns = result.columns.map { |column|
- column.sub(/^"?\w+"?\./, '')
- }
-
- result.rows.map { |row| Hash[columns.zip(row)] }
+ exec_query(sql, name, binds).to_a
end
def table_structure(table_name)
- structure = @connection.table_info(quote_table_name(table_name))
+ structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})").to_hash
raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
structure
end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index 8180bf0987..7839f03848 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -74,6 +74,8 @@ module ActiveRecord
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
end
+ IdentityMap.remove_by_id(symbolized_base_class, id) if IdentityMap.enabled?
+
update_all(updates.join(', '), primary_key => id )
end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 6fb723f2f5..d523c643ba 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -1,4 +1,10 @@
require 'erb'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'csv'
require 'zlib'
@@ -6,15 +12,7 @@ require 'active_support/dependencies'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/logger'
-
-if RUBY_VERSION < '1.9'
- module YAML #:nodoc:
- class Omap #:nodoc:
- def keys; map { |k, v| k } end
- def values; map { |k, v| v } end
- end
- end
-end
+require 'active_support/ordered_hash'
if defined? ActiveRecord
class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
@@ -446,20 +444,23 @@ class FixturesFileNotFound < StandardError; end
#
# Any fixture labeled "DEFAULTS" is safely ignored.
-class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
+class Fixtures
MAX_ID = 2 ** 30 - 1
- DEFAULT_FILTER_RE = /\.ya?ml$/
- @@all_cached_fixtures = {}
+ @@all_cached_fixtures = Hash.new { |h,k| h[k] = {} }
- def self.reset_cache(connection = nil)
- connection ||= ActiveRecord::Base.connection
- @@all_cached_fixtures[connection.object_id] = {}
+ def self.find_table_name(table_name) # :nodoc:
+ ActiveRecord::Base.pluralize_table_names ?
+ table_name.to_s.singularize.camelize :
+ table_name.to_s.camelize
+ end
+
+ def self.reset_cache
+ @@all_cached_fixtures.clear
end
def self.cache_for_connection(connection)
- @@all_cached_fixtures[connection.object_id] ||= {}
- @@all_cached_fixtures[connection.object_id]
+ @@all_cached_fixtures[connection]
end
def self.fixture_is_cached?(connection, table_name)
@@ -468,27 +469,23 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
def self.cached_fixtures(connection, keys_to_fetch = nil)
if keys_to_fetch
- fixtures = cache_for_connection(connection).values_at(*keys_to_fetch)
+ cache_for_connection(connection).values_at(*keys_to_fetch)
else
- fixtures = cache_for_connection(connection).values
+ cache_for_connection(connection).values
end
- fixtures.size > 1 ? fixtures : fixtures.first
end
def self.cache_fixtures(connection, fixtures_map)
cache_for_connection(connection).update(fixtures_map)
end
- def self.instantiate_fixtures(object, table_name, fixtures, load_instances = true)
- object.instance_variable_set "@#{table_name.to_s.gsub('.','_')}", fixtures
+ def self.instantiate_fixtures(object, fixture_name, fixtures, load_instances = true)
if load_instances
- ActiveRecord::Base.silence do
- fixtures.each do |name, fixture|
- begin
- object.instance_variable_set "@#{name}", fixture.find
- rescue FixtureClassNotFound
- nil
- end
+ fixtures.each do |name, fixture|
+ begin
+ object.instance_variable_set "@#{name}", fixture.find
+ rescue FixtureClassNotFound
+ nil
end
end
end
@@ -505,36 +502,56 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
def self.create_fixtures(fixtures_directory, table_names, class_names = {})
table_names = [table_names].flatten.map { |n| n.to_s }
- table_names.each { |n| class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/') }
- connection = block_given? ? yield : ActiveRecord::Base.connection
+ table_names.each { |n|
+ class_names[n.tr('/', '_').to_sym] = n.classify if n.include?('/')
+ }
- table_names_to_fetch = table_names.reject { |table_name| fixture_is_cached?(connection, table_name) }
+ # FIXME: Apparently JK uses this.
+ connection = block_given? ? yield : ActiveRecord::Base.connection
- unless table_names_to_fetch.empty?
- ActiveRecord::Base.silence do
- connection.disable_referential_integrity do
- fixtures_map = {}
+ files_to_read = table_names.reject { |table_name| fixture_is_cached?(connection, table_name) }
- fixtures = table_names_to_fetch.map do |table_name|
- fixtures_map[table_name] = Fixtures.new(connection, table_name.tr('/', '_'), class_names[table_name.tr('/', '_').to_sym], File.join(fixtures_directory, table_name))
- end
+ unless files_to_read.empty?
+ connection.disable_referential_integrity do
+ fixtures_map = {}
+
+ fixture_files = files_to_read.map do |path|
+ table_name = path.tr '/', '_'
+
+ fixtures_map[path] = Fixtures.new(
+ connection,
+ table_name,
+ class_names[table_name.to_sym],
+ File.join(fixtures_directory, path))
+ end
+
+ all_loaded_fixtures.update(fixtures_map)
- all_loaded_fixtures.update(fixtures_map)
+ connection.transaction(:requires_new => true) do
+ fixture_files.each do |ff|
+ conn = ff.model_class.respond_to?(:connection) ? ff.model_class.connection : connection
+ table_rows = ff.table_rows
- connection.transaction(:requires_new => true) do
- fixtures.reverse.each { |fixture| fixture.delete_existing_fixtures }
- fixtures.each { |fixture| fixture.insert_fixtures }
+ table_rows.keys.each do |table|
+ conn.delete "DELETE FROM #{conn.quote_table_name(table)}", 'Fixture Delete'
+ end
- # Cap primary key sequences to max(pk).
- if connection.respond_to?(:reset_pk_sequence!)
- table_names.each do |table_name|
- connection.reset_pk_sequence!(table_name.tr('/', '_'))
+ table_rows.each do |table_name,rows|
+ rows.each do |row|
+ conn.insert_fixture(row, table_name)
end
end
end
- cache_fixtures(connection, fixtures_map)
+ # Cap primary key sequences to max(pk).
+ if connection.respond_to?(:reset_pk_sequence!)
+ table_names.each do |table_name|
+ connection.reset_pk_sequence!(table_name.tr('/', '_'))
+ end
+ end
end
+
+ cache_fixtures(connection, fixtures_map)
end
end
cached_fixtures(connection, table_names)
@@ -546,40 +563,59 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
Zlib.crc32(label.to_s) % MAX_ID
end
- attr_reader :table_name, :name
+ attr_reader :table_name, :name, :fixtures, :model_class
+
+ def initialize(connection, table_name, class_name, fixture_path)
+ @connection = connection
+ @table_name = table_name
+ @fixture_path = fixture_path
+ @name = table_name # preserve fixture base name
+ @class_name = class_name
+
+ @fixtures = ActiveSupport::OrderedHash.new
+ @table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}"
+
+ # Should be an AR::Base type class
+ if class_name.is_a?(Class)
+ @table_name = class_name.table_name
+ @connection = class_name.connection
+ @model_class = class_name
+ else
+ @model_class = class_name.constantize rescue nil
+ end
- def initialize(connection, table_name, class_name, fixture_path, file_filter = DEFAULT_FILTER_RE)
- @connection, @table_name, @fixture_path, @file_filter = connection, table_name, fixture_path, file_filter
- @name = table_name # preserve fixture base name
- @class_name = class_name ||
- (ActiveRecord::Base.pluralize_table_names ? @table_name.singularize.camelize : @table_name.camelize)
- @table_name = "#{ActiveRecord::Base.table_name_prefix}#{@table_name}#{ActiveRecord::Base.table_name_suffix}"
- @table_name = class_name.table_name if class_name.respond_to?(:table_name)
- @connection = class_name.connection if class_name.respond_to?(:connection)
read_fixture_files
end
- def delete_existing_fixtures
- @connection.delete "DELETE FROM #{@connection.quote_table_name(table_name)}", 'Fixture Delete'
+ def [](x)
+ fixtures[x]
+ end
+
+ def []=(k,v)
+ fixtures[k] = v
+ end
+
+ def each(&block)
+ fixtures.each(&block)
+ end
+
+ def size
+ fixtures.size
end
- def insert_fixtures
+ # Return a hash of rows to be inserted. The key is the table, the value is
+ # a list of rows to insert to that table.
+ def table_rows
now = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
now = now.to_s(:db)
# allow a standard key to be used for doing defaults in YAML
- if is_a?(Hash)
- delete('DEFAULTS')
- else
- delete(assoc('DEFAULTS'))
- end
+ fixtures.delete('DEFAULTS')
# track any join tables we need to insert later
- habtm_fixtures = Hash.new do |h, habtm|
- h[habtm] = HabtmFixtures.new(@connection, habtm.options[:join_table], nil, nil)
- end
+ rows = Hash.new { |h,table| h[table] = [] }
- each do |label, fixture|
+ rows[table_name] = fixtures.map do |label, fixture|
row = fixture.to_hash
if model_class && model_class < ActiveRecord::Base
@@ -615,14 +651,9 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s
if association.name.to_s != fk_name && value = row.delete(association.name.to_s)
- if association.options[:polymorphic]
- if value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
- target_type = $1
- target_type_name = (association.options[:foreign_type] || "#{association.name}_type").to_s
-
- # support polymorphic belongs_to as "label (Type)"
- row[target_type_name] = target_type
- end
+ if association.options[:polymorphic] && value.sub!(/\s*\(([^\)]*)\)\s*$/, "")
+ # support polymorphic belongs_to as "label (Type)"
+ row[association.foreign_type] = $1
end
row[fk_name] = Fixtures.identify(value)
@@ -630,47 +661,22 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
when :has_and_belongs_to_many
if (targets = row.delete(association.name.to_s))
targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/)
- join_fixtures = habtm_fixtures[association]
-
- targets.each do |target|
- join_fixtures["#{label}_#{target}"] = Fixture.new(
- { association.primary_key_name => row[primary_key_name],
- association.association_foreign_key => Fixtures.identify(target) },
- nil, @connection)
- end
+ table_name = association.options[:join_table]
+ rows[table_name].concat targets.map { |target|
+ { association.foreign_key => row[primary_key_name],
+ association.association_foreign_key => Fixtures.identify(target) }
+ }
end
end
end
end
- @connection.insert_fixture(fixture, @table_name)
- end
-
- # insert any HABTM join tables we discovered
- habtm_fixtures.values.each do |fixture|
- fixture.delete_existing_fixtures
- fixture.insert_fixtures
+ row
end
+ rows
end
private
- class HabtmFixtures < ::Fixtures #:nodoc:
- def read_fixture_files; end
- end
-
- def model_class
- unless defined?(@model_class)
- @model_class =
- if @class_name.nil? || @class_name.is_a?(Class)
- @class_name
- else
- @class_name.constantize rescue nil
- end
- end
-
- @model_class
- end
-
def primary_key_name
@primary_key_name ||= model_class && model_class.primary_key
end
@@ -724,7 +730,7 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
raise Fixture::FormatError, "Bad data for #{@class_name} fixture named #{name} (nil)"
end
- self[name] = Fixture.new(data, model_class, @connection)
+ fixtures[name] = Fixture.new(data, model_class)
end
end
end
@@ -737,7 +743,7 @@ class Fixtures < (RUBY_VERSION < '1.9' ? YAML::Omap : Hash)
reader.each do |row|
data = {}
row.each_with_index { |cell, j| data[header[j].to_s.strip] = cell.to_s.strip }
- self["#{@class_name.to_s.underscore}_#{i+=1}"] = Fixture.new(data, model_class, @connection)
+ fixtures["#{@class_name.to_s.underscore}_#{i+=1}"] = Fixture.new(data, model_class)
end
end
@@ -773,44 +779,30 @@ class Fixture #:nodoc:
class FormatError < FixtureError #:nodoc:
end
- attr_reader :model_class
+ attr_reader :model_class, :fixture
- def initialize(fixture, model_class, connection = ActiveRecord::Base.connection)
- @connection = connection
- @fixture = fixture
- @model_class = model_class.is_a?(Class) ? model_class : model_class.constantize rescue nil
+ def initialize(fixture, model_class)
+ @fixture = fixture
+ @model_class = model_class
end
def class_name
- @model_class.name if @model_class
+ model_class.name if model_class
end
def each
- @fixture.each { |item| yield item }
+ fixture.each { |item| yield item }
end
def [](key)
- @fixture[key]
- end
-
- def to_hash
- @fixture
+ fixture[key]
end
- def key_list
- @fixture.keys.map { |column_name| @connection.quote_column_name(column_name) }.join(', ')
- end
-
- def value_list
- cols = (model_class && model_class < ActiveRecord::Base) ? model_class.columns_hash : {}
- @fixture.map do |key, value|
- @connection.quote(value, cols[key]).gsub('[^\]\\n', "\n").gsub('[^\]\\r', "\r")
- end.join(', ')
- end
+ alias :to_hash :fixture
def find
if model_class
- model_class.find(self[model_class.primary_key])
+ model_class.find(fixture[model_class.primary_key])
else
raise FixtureClassNotFound, "No class attached to find."
end
@@ -837,7 +829,9 @@ module ActiveRecord
self.use_instantiated_fixtures = false
self.pre_loaded_fixtures = false
- self.fixture_class_names = {}
+ self.fixture_class_names = Hash.new do |h, table_name|
+ h[table_name] = Fixtures.find_table_name(table_name)
+ end
end
module ClassMethods
@@ -845,17 +839,17 @@ module ActiveRecord
self.fixture_class_names = self.fixture_class_names.merge(class_names)
end
- def fixtures(*table_names)
- if table_names.first == :all
- table_names = Dir["#{fixture_path}/**/*.{yml,csv}"]
- table_names.map! { |f| f[(fixture_path.size + 1)..-5] }
+ def fixtures(*fixture_names)
+ if fixture_names.first == :all
+ fixture_names = Dir["#{fixture_path}/**/*.{yml,csv}"]
+ fixture_names.map! { |f| f[(fixture_path.size + 1)..-5] }
else
- table_names = table_names.flatten.map { |n| n.to_s }
+ fixture_names = fixture_names.flatten.map { |n| n.to_s }
end
- self.fixture_table_names |= table_names
- require_fixture_classes(table_names)
- setup_fixture_accessors(table_names)
+ self.fixture_table_names |= fixture_names
+ require_fixture_classes(fixture_names)
+ setup_fixture_accessors(fixture_names)
end
def try_to_load_dependency(file_name)
@@ -870,38 +864,43 @@ module ActiveRecord
end
end
- def require_fixture_classes(table_names = nil)
- (table_names || fixture_table_names).each do |table_name|
- file_name = table_name.to_s
+ def require_fixture_classes(fixture_names = nil)
+ (fixture_names || fixture_table_names).each do |fixture_name|
+ file_name = fixture_name.to_s
file_name = file_name.singularize if ActiveRecord::Base.pluralize_table_names
try_to_load_dependency(file_name)
end
end
- def setup_fixture_accessors(table_names = nil)
- table_names = Array.wrap(table_names || fixture_table_names)
- table_names.each do |table_name|
- table_name = table_name.to_s.tr('./', '_')
+ def setup_fixture_accessors(fixture_names = nil)
+ fixture_names = Array.wrap(fixture_names || fixture_table_names)
+ methods = Module.new do
+ fixture_names.each do |fixture_name|
+ fixture_name = fixture_name.to_s.tr('./', '_')
- redefine_method(table_name) do |*fixtures|
- force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
+ define_method(fixture_name) do |*fixtures|
+ force_reload = fixtures.pop if fixtures.last == true || fixtures.last == :reload
- @fixture_cache[table_name] ||= {}
+ @fixture_cache[fixture_name] ||= {}
- instances = fixtures.map do |fixture|
- @fixture_cache[table_name].delete(fixture) if force_reload
+ instances = fixtures.map do |fixture|
+ @fixture_cache[fixture_name].delete(fixture) if force_reload
- if @loaded_fixtures[table_name][fixture.to_s]
- @fixture_cache[table_name][fixture] ||= @loaded_fixtures[table_name][fixture.to_s].find
- else
- raise StandardError, "No fixture with name '#{fixture}' found for table '#{table_name}'"
+ if @loaded_fixtures[fixture_name][fixture.to_s]
+ ActiveRecord::IdentityMap.without do
+ @fixture_cache[fixture_name][fixture] ||= @loaded_fixtures[fixture_name][fixture.to_s].find
+ end
+ else
+ raise StandardError, "No fixture with name '#{fixture}' found for table '#{fixture_name}'"
+ end
end
- end
- instances.size == 1 ? instances.first : instances
+ instances.size == 1 ? instances.first : instances
+ end
+ private fixture_name
end
- private table_name
end
+ include methods
end
def uses_transaction(*methods)
@@ -921,7 +920,7 @@ module ActiveRecord
end
def setup_fixtures
- return unless defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
+ return unless !ActiveRecord::Base.configurations.blank?
if pre_loaded_fixtures && !use_transactional_fixtures
raise RuntimeError, 'pre_loaded_fixtures requires use_transactional_fixtures'
@@ -935,7 +934,7 @@ module ActiveRecord
if @@already_loaded_fixtures[self.class]
@loaded_fixtures = @@already_loaded_fixtures[self.class]
else
- load_fixtures
+ @loaded_fixtures = load_fixtures
@@already_loaded_fixtures[self.class] = @loaded_fixtures
end
ActiveRecord::Base.connection.increment_open_transactions
@@ -945,7 +944,7 @@ module ActiveRecord
else
Fixtures.reset_cache
@@already_loaded_fixtures[self.class] = nil
- load_fixtures
+ @loaded_fixtures = load_fixtures
end
# Instantiate fixtures for every test if requested.
@@ -969,15 +968,8 @@ module ActiveRecord
private
def load_fixtures
- @loaded_fixtures = {}
fixtures = Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
- unless fixtures.nil?
- if fixtures.instance_of?(Fixtures)
- @loaded_fixtures[fixtures.name] = fixtures
- else
- fixtures.each { |f| @loaded_fixtures[f.name] = f }
- end
- end
+ Hash[fixtures.map { |f| [f.name, f] }]
end
# for pre_loaded_fixtures, only require the classes once. huge speed improvement
@@ -993,8 +985,8 @@ module ActiveRecord
Fixtures.instantiate_all_loaded_fixtures(self, load_instances?)
else
raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil?
- @loaded_fixtures.each do |table_name, fixtures|
- Fixtures.instantiate_fixtures(self, table_name, fixtures, load_instances?)
+ @loaded_fixtures.each do |fixture_name, fixtures|
+ Fixtures.instantiate_fixtures(self, fixture_name, fixtures, load_instances?)
end
end
end
diff --git a/activerecord/lib/active_record/identity_map.rb b/activerecord/lib/active_record/identity_map.rb
new file mode 100644
index 0000000000..d18b2b0a54
--- /dev/null
+++ b/activerecord/lib/active_record/identity_map.rb
@@ -0,0 +1,102 @@
+module ActiveRecord
+ # = Active Record Identity Map
+ #
+ # Ensures that each object gets loaded only once by keeping every loaded
+ # object in a map. Looks up objects using the map when referring to them.
+ #
+ # More information on Identity Map pattern:
+ # http://www.martinfowler.com/eaaCatalog/identityMap.html
+ #
+ # == Configuration
+ #
+ # In order to enable IdentityMap, set <tt>config.active_record.identity_map = true</tt>
+ # in your <tt>config/application.rb</tt> file.
+ #
+ # IdentityMap is disabled by default.
+ #
+ module IdentityMap
+ extend ActiveSupport::Concern
+
+ class << self
+ def enabled=(flag)
+ Thread.current[:identity_map_enabled] = flag
+ end
+
+ def enabled
+ Thread.current[:identity_map_enabled]
+ end
+ alias enabled? enabled
+
+ def repository
+ Thread.current[:identity_map] ||= Hash.new { |h,k| h[k] = {} }
+ end
+
+ def use
+ old, self.enabled = enabled, true
+
+ yield if block_given?
+ ensure
+ self.enabled = old
+ clear
+ end
+
+ def without
+ old, self.enabled = enabled, false
+
+ yield if block_given?
+ ensure
+ self.enabled = old
+ end
+
+ def get(klass, primary_key)
+ obj = repository[klass.symbolized_base_class][primary_key]
+ obj.is_a?(klass) ? obj : nil
+ end
+
+ def add(record)
+ repository[record.class.symbolized_base_class][record.id] = record
+ end
+
+ def remove(record)
+ repository[record.class.symbolized_base_class].delete(record.id)
+ end
+
+ def remove_by_id(symbolized_base_class, id)
+ repository[symbolized_base_class].delete(id)
+ end
+
+ def clear
+ repository.clear
+ end
+ end
+
+ # Reinitialize an Identity Map model object from +coder+.
+ # +coder+ must contain the attributes necessary for initializing an empty
+ # model object.
+ def reinit_with(coder)
+ @attributes_cache = {}
+ dirty = @changed_attributes.keys
+ @attributes.update(coder['attributes'].except(*dirty))
+ @changed_attributes.update(coder['attributes'].slice(*dirty))
+ @changed_attributes.delete_if{|k,v| v.eql? @attributes[k]}
+
+ set_serialized_attributes
+
+ run_callbacks :find
+
+ self
+ end
+
+ class Middleware
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ ActiveRecord::IdentityMap.use do
+ @app.call(env)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index e5065de7fb..6b2b1ebafe 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -58,6 +58,12 @@ module ActiveRecord
end
private
+ def increment_lock
+ lock_col = self.class.locking_column
+ previous_lock_value = send(lock_col).to_i
+ send(lock_col + '=', previous_lock_value + 1)
+ end
+
def attributes_from_column_definition
result = super
@@ -78,8 +84,8 @@ module ActiveRecord
return 0 if attribute_names.empty?
lock_col = self.class.locking_column
- previous_value = send(lock_col).to_i
- send(lock_col + '=', previous_value + 1)
+ previous_lock_value = send(lock_col).to_i
+ increment_lock
attribute_names += [lock_col]
attribute_names.uniq!
@@ -89,7 +95,7 @@ module ActiveRecord
stmt = relation.where(
relation.table[self.class.primary_key].eq(quoted_id).and(
- relation.table[lock_col].eq(quote_value(previous_value))
+ relation.table[lock_col].eq(quote_value(previous_lock_value))
)
).arel.compile_update(arel_attributes_values(false, false, attribute_names))
@@ -103,7 +109,7 @@ module ActiveRecord
# If something went wrong, revert the version.
rescue Exception
- send(lock_col + '=', previous_value)
+ send(lock_col + '=', previous_lock_value)
raise
end
end
diff --git a/activerecord/lib/active_record/locking/pessimistic.rb b/activerecord/lib/active_record/locking/pessimistic.rb
index d900831e13..557b277d6b 100644
--- a/activerecord/lib/active_record/locking/pessimistic.rb
+++ b/activerecord/lib/active_record/locking/pessimistic.rb
@@ -40,7 +40,7 @@ module ActiveRecord
#
# Database-specific information on row locking:
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
- # PostgreSQL: http://www.postgresql.org/docs/8.1/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
+ # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
module Pessimistic
# Obtain a row lock on this record. Reloads the record to obtain the requested
# lock. Pass an SQL locking clause to append the end of the SELECT statement
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
index c7ae12977a..afadbf03ef 100644
--- a/activerecord/lib/active_record/log_subscriber.rb
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -22,8 +22,16 @@ module ActiveRecord
self.class.runtime += event.duration
return unless logger.debug?
- name = '%s (%.1fms)' % [event.payload[:name], event.duration]
- sql = event.payload[:sql].squeeze(' ')
+ payload = event.payload
+ name = '%s (%.1fms)' % [payload[:name], event.duration]
+ sql = payload[:sql].squeeze(' ')
+ binds = nil
+
+ unless (payload[:binds] || []).empty?
+ binds = " " + payload[:binds].map { |col,v|
+ [col.name, v]
+ }.inspect
+ end
if odd?
name = color(name, CYAN, true)
@@ -32,7 +40,7 @@ module ActiveRecord
name = color(name, MAGENTA, true)
end
- debug " #{name} #{sql}"
+ debug " #{name} #{sql}#{binds}"
end
def odd?
@@ -45,4 +53,4 @@ module ActiveRecord
end
end
-ActiveRecord::LogSubscriber.attach_to :active_record \ No newline at end of file
+ActiveRecord::LogSubscriber.attach_to :active_record
diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb
index d7e481905a..c9d57ce812 100644
--- a/activerecord/lib/active_record/migration/command_recorder.rb
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -40,7 +40,7 @@ module ActiveRecord
@commands.reverse.map { |name, args|
method = :"invert_#{name}"
raise IrreversibleMigration unless respond_to?(method, true)
- __send__(method, args)
+ send(method, args)
}
end
@@ -48,12 +48,16 @@ module ActiveRecord
super || delegate.respond_to?(*args)
end
- def send(method, *args) # :nodoc:
- return super unless respond_to?(method)
- record(method, args)
+ [:create_table, :rename_table, :add_column, :remove_column, :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, :change_column, :change_column_default].each do |method|
+ class_eval <<-EOV, __FILE__, __LINE__ + 1
+ def #{method}(*args)
+ record(:"#{method}", args)
+ end
+ EOV
end
private
+
def invert_create_table(args)
[:drop_table, args]
end
@@ -86,6 +90,14 @@ module ActiveRecord
def invert_add_timestamps(args)
[:remove_timestamps, args]
end
+
+ # Forwards any missing method call to the \target.
+ def method_missing(method, *args, &block)
+ @delegate.send(method, *args, &block)
+ rescue NoMethodError => e
+ raise e, e.message.sub(/ for #<.*$/, " via proxy for #{@delegate}")
+ end
+
end
end
end
diff --git a/activerecord/lib/active_record/named_scope.rb b/activerecord/lib/active_record/named_scope.rb
index 0f421560f0..d291632260 100644
--- a/activerecord/lib/active_record/named_scope.rb
+++ b/activerecord/lib/active_record/named_scope.rb
@@ -102,10 +102,9 @@ module ActiveRecord
def scope(name, scope_options = {})
name = name.to_sym
valid_scope_name?(name)
-
extension = Module.new(&Proc.new) if block_given?
- scopes[name] = lambda do |*args|
+ scope_proc = lambda do |*args|
options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options
relation = if options.is_a?(Hash)
@@ -119,6 +118,8 @@ module ActiveRecord
extension ? relation.extending(extension) : relation
end
+ self.scopes = self.scopes.merge name => scope_proc
+
singleton_class.send(:redefine_method, name, &scopes[name])
end
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 050b521b6a..522c0cfc9f 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -387,13 +387,13 @@ module ActiveRecord
end
end
- association = send(association_name)
+ association = association(association_name)
existing_records = if association.loaded?
- association.to_a
+ association.target
else
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
- attribute_ids.empty? ? [] : association.all(:conditions => {association.primary_key => attribute_ids})
+ attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
end
attributes_collection.each do |attributes|
@@ -403,11 +403,29 @@ module ActiveRecord
unless reject_new_record?(association_name, attributes)
association.build(attributes.except(*UNASSIGNABLE_KEYS))
end
-
+ elsif existing_records.count == 0 #Existing record but not yet associated
+ existing_record = self.class.reflect_on_association(association_name).klass.find(attributes['id'])
+ if !call_reject_if(association_name, attributes)
+ association.send(:add_record_to_target_with_callbacks, existing_record) if !association.loaded?
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ end
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
- association.send(:add_record_to_target_with_callbacks, existing_record) if !association.loaded? && !call_reject_if(association_name, attributes)
- assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ unless association.loaded? || call_reject_if(association_name, attributes)
+ # Make sure we are operating on the actual object which is in the association's
+ # proxy_target array (either by finding it, or adding it if not found)
+ target_record = association.target.detect { |record| record == existing_record }
+
+ if target_record
+ existing_record = target_record
+ else
+ association.add_to_target(existing_record)
+ end
+ end
+
+ if !call_reject_if(association_name, attributes)
+ assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
+ end
else
raise_nested_attributes_record_not_found(association_name, attributes['id'])
end
diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb
index 8b011ad9af..0893d7e337 100644
--- a/activerecord/lib/active_record/observer.rb
+++ b/activerecord/lib/active_record/observer.rb
@@ -104,10 +104,17 @@ module ActiveRecord
def define_callbacks(klass)
observer = self
+ observer_name = observer.class.name.underscore.gsub('/', '__')
ActiveRecord::Callbacks::CALLBACKS.each do |callback|
next unless respond_to?(callback)
- klass.send(callback){|record| observer.send(callback, record)}
+ callback_meth = :"_notify_#{observer_name}_for_#{callback}"
+ unless klass.respond_to?(callback_meth)
+ klass.send(:define_method, callback_meth) do
+ observer.send(callback, self)
+ end
+ klass.send(callback, callback_meth)
+ end
end
end
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 9ac8fcb176..df7b22080c 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -64,7 +64,10 @@ module ActiveRecord
# callbacks, Observer methods, or any <tt>:dependent</tt> association
# options, use <tt>#destroy</tt>.
def delete
- self.class.delete(id) if persisted?
+ if persisted?
+ self.class.delete(id)
+ IdentityMap.remove(self) if IdentityMap.enabled?
+ end
@destroyed = true
freeze
end
@@ -73,6 +76,7 @@ module ActiveRecord
# that no changes should be made (since they can't be persisted).
def destroy
if persisted?
+ IdentityMap.remove(self) if IdentityMap.enabled?
self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).delete_all
end
@@ -196,7 +200,12 @@ module ActiveRecord
def reload(options = nil)
clear_aggregation_cache
clear_association_cache
- @attributes.update(self.class.unscoped { self.class.find(self.id, options) }.instance_variable_get('@attributes'))
+
+ IdentityMap.without do
+ fresh_object = self.class.unscoped { self.class.find(self.id, options) }
+ @attributes.update(fresh_object.instance_variable_get('@attributes'))
+ end
+
@attributes_cache = {}
self
end
@@ -224,6 +233,7 @@ module ActiveRecord
def touch(name = nil)
attributes = timestamp_attributes_for_update_in_model
attributes << name if name
+
unless attributes.empty?
current_time = current_time_from_proper_timezone
changes = {}
@@ -232,6 +242,8 @@ module ActiveRecord
changes[column.to_s] = write_attribute(column.to_s, current_time)
end
+ changes[self.class.locking_column] = increment_lock if locking_enabled?
+
@changed_attributes.except!(*changes.keys)
primary_key = self.class.primary_key
self.class.update_all(changes, { primary_key => self[primary_key] }) == 1
@@ -258,11 +270,11 @@ module ActiveRecord
# Creates a record with values matching those of the instance attributes
# and returns its id.
def create
- if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
+ if id.nil? && connection.prefetch_primary_key?(self.class.table_name)
self.id = connection.next_sequence_value(self.class.sequence_name)
end
- attributes_values = arel_attributes_values
+ attributes_values = arel_attributes_values(!id.nil?)
new_id = if attributes_values.empty?
self.class.unscoped.insert connection.empty_insert_statement_value
@@ -272,6 +284,7 @@ module ActiveRecord
self.id ||= new_id
+ IdentityMap.add(self) if IdentityMap.enabled?
@new_record = false
id
end
@@ -282,7 +295,7 @@ module ActiveRecord
# that instances loaded from the database would.
def attributes_from_column_definition
Hash[self.class.columns.map do |column|
- [column.name, column.default] unless column.name == self.class.primary_key
+ [column.name, column.default]
end]
end
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index dfe255ad7c..cace6f0cc0 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -43,6 +43,11 @@ module ActiveRecord
ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger }
end
+ initializer "active_record.identity_map" do |app|
+ config.app_middleware.insert_after "::ActionDispatch::Callbacks",
+ "ActiveRecord::IdentityMap::Middleware" if config.active_record.delete(:identity_map)
+ end
+
initializer "active_record.set_configs" do |app|
ActiveSupport.on_load(:active_record) do
app.config.active_record.each do |k,v|
@@ -69,11 +74,10 @@ module ActiveRecord
end
initializer "active_record.set_dispatch_hooks", :before => :set_clear_dependencies_hook do |app|
- unless app.config.cache_classes
- ActiveSupport.on_load(:active_record) do
- ActionDispatch::Callbacks.after do
- ActiveRecord::Base.clear_reloadable_connections!
- end
+ ActiveSupport.on_load(:active_record) do
+ ActionDispatch::Reloader.to_cleanup do
+ ActiveRecord::Base.clear_reloadable_connections!
+ ActiveRecord::Base.clear_cache!
end
end
end
@@ -82,7 +86,7 @@ module ActiveRecord
ActiveSupport.on_load(:active_record) do
instantiate_observers
- ActionDispatch::Callbacks.to_prepare(:activerecord_instantiate_observers) do
+ ActionDispatch::Reloader.to_prepare do
ActiveRecord::Base.instantiate_observers
end
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index a4fc18148e..ff36814684 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -193,7 +193,7 @@ db_namespace = namespace :db do
file_list = []
Dir.foreach(File.join(Rails.root, 'db', 'migrate')) do |file|
# only files matching "20091231235959_some_name.rb" pattern
- if match_data = /(\d{14})_(.+)\.rb/.match(file)
+ if match_data = /^(\d{14})_(.+)\.rb$/.match(file)
status = db_list.delete(match_data[1]) ? 'up' : 'down'
file_list << [status, match_data[1], match_data[2]]
end
@@ -296,8 +296,8 @@ db_namespace = namespace :db do
base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
- (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir["#{fixtures_dir}/**/*.{yml,csv}"]).each do |fixture_file|
- Fixtures.create_fixtures(fixtures_dir, fixture_file[(fixtures_dir.size + 1)..-5])
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.{yml,csv}"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
+ Fixtures.create_fixtures(fixtures_dir, fixture_file)
end
end
@@ -409,7 +409,7 @@ db_namespace = namespace :db do
ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
- `psql -U "#{abcs["test"]["username"]}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs["test"]["database"]}`
+ `psql -U "#{abcs["test"]["username"]}" -f #{Rails.root}/db/#{Rails.env}_structure.sql #{abcs["test"]["database"]} #{abcs["test"]["template"]}`
when "sqlite", "sqlite3"
dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
`#{abcs["test"]["adapter"]} #{dbfile} < #{Rails.root}/db/#{Rails.env}_structure.sql`
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 0ec8da0088..e3e2cac042 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/class/attribute'
+require 'active_support/core_ext/module/deprecation'
module ActiveRecord
# = Active Record Reflection
@@ -196,8 +197,21 @@ module ActiveRecord
@quoted_table_name ||= klass.quoted_table_name
end
+ def foreign_key
+ @foreign_key ||= options[:foreign_key] || derive_foreign_key
+ end
+
def primary_key_name
- @primary_key_name ||= options[:foreign_key] || derive_primary_key_name
+ foreign_key
+ end
+ deprecate :primary_key_name => :foreign_key
+
+ def foreign_type
+ @foreign_type ||= options[:foreign_type] || "#{name}_type"
+ end
+
+ def type
+ @type ||= "#{options[:as]}_type"
end
def primary_key_column
@@ -205,15 +219,18 @@ module ActiveRecord
end
def association_foreign_key
- @association_foreign_key ||= @options[:association_foreign_key] || class_name.foreign_key
+ @association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
end
def association_primary_key
- @association_primary_key ||= @options[:primary_key] || klass.primary_key
+ @association_primary_key ||=
+ options[:primary_key] ||
+ !options[:polymorphic] && klass.primary_key ||
+ 'id'
end
def active_record_primary_key
- @active_record_primary_key ||= @options[:primary_key] || active_record.primary_key
+ @active_record_primary_key ||= options[:primary_key] || active_record.primary_key
end
def counter_cache_column
@@ -300,22 +317,36 @@ module ActiveRecord
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
end
- def dependent_conditions(record, base_class, extra_conditions)
- dependent_conditions = []
- dependent_conditions << "#{primary_key_name} = #{record.send(name).send(:owner_quoted_id)}"
- dependent_conditions << "#{options[:as]}_type = '#{base_class.name}'" if options[:as]
- dependent_conditions << klass.send(:sanitize_sql, options[:conditions]) if options[:conditions]
- dependent_conditions << extra_conditions if extra_conditions
- dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ")
- dependent_conditions = dependent_conditions.gsub('@', '\@')
- dependent_conditions
- end
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
def belongs_to?
macro == :belongs_to
end
+ def association_class
+ case macro
+ when :belongs_to
+ if options[:polymorphic]
+ Associations::BelongsToPolymorphicAssociation
+ else
+ Associations::BelongsToAssociation
+ end
+ when :has_and_belongs_to_many
+ Associations::HasAndBelongsToManyAssociation
+ when :has_many
+ if options[:through]
+ Associations::HasManyThroughAssociation
+ else
+ Associations::HasManyAssociation
+ end
+ when :has_one
+ if options[:through]
+ Associations::HasOneThroughAssociation
+ else
+ Associations::HasOneAssociation
+ end
+ end
+ end
+
private
def derive_class_name
class_name = name.to_s.camelize
@@ -323,7 +354,7 @@ module ActiveRecord
class_name
end
- def derive_primary_key_name
+ def derive_foreign_key
if belongs_to?
"#{name}_id"
elsif options[:as]
@@ -337,7 +368,7 @@ module ActiveRecord
# Holds all the meta-data about a :through association as it was specified
# in the Active Record class.
class ThroughReflection < AssociationReflection #:nodoc:
- delegate :primary_key_name, :association_foreign_key, :to => :source_reflection
+ delegate :foreign_key, :foreign_type, :association_foreign_key, :to => :source_reflection
# Gets the source of the through reflection. It checks both a singularized
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
@@ -469,11 +500,23 @@ module ActiveRecord
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
end
+ def source_options
+ source_reflection.options
+ end
+
+ def through_options
+ through_reflection.options
+ end
+
def check_validity!
if through_reflection.nil?
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
end
+ if through_reflection.options[:polymorphic]
+ raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
+ end
+
if source_reflection.nil?
raise HasManyThroughSourceAssociationNotFoundError.new(self)
end
@@ -483,7 +526,11 @@ module ActiveRecord
end
if source_reflection.options[:polymorphic] && options[:source_type].nil?
- raise HasManyThroughAssociationPolymorphicError.new(active_record.name, self, source_reflection)
+ raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
+ end
+
+ if macro == :has_one && through_reflection.collection?
+ raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
end
check_validity_of_inverse!
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 3009bb70c1..f939bedc81 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -10,8 +10,9 @@ module ActiveRecord
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches
+ # These are explicitly delegated to improve performance (avoids method_missing)
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to => :to_a
- delegate :insert, :to => :arel
+ delegate :table_name, :primary_key, :to => :klass
attr_reader :table, :klass, :loaded
attr_accessor :extensions
@@ -28,6 +29,25 @@ module ActiveRecord
@extensions = []
end
+ def insert(values)
+ im = arel.compile_insert values
+ im.into @table
+
+ primary_key_value = nil
+
+ if primary_key && Hash === values
+ primary_key_value = values[values.keys.find { |k|
+ k.name == primary_key
+ }]
+ end
+
+ @klass.connection.insert(
+ im.to_sql,
+ 'SQL',
+ primary_key,
+ primary_key_value)
+ end
+
def new(*args, &block)
scoping { @klass.new(*args, &block) }
end
@@ -47,25 +67,28 @@ module ActiveRecord
end
def respond_to?(method, include_private = false)
- return true if arel.respond_to?(method, include_private) || Array.method_defined?(method) || @klass.respond_to?(method, include_private)
-
- if match = DynamicFinderMatch.match(method)
- return true if @klass.send(:all_attributes_exists?, match.attribute_names)
- elsif match = DynamicScopeMatch.match(method)
- return true if @klass.send(:all_attributes_exists?, match.attribute_names)
- else
+ arel.respond_to?(method, include_private) ||
+ Array.method_defined?(method) ||
+ @klass.respond_to?(method, include_private) ||
super
- end
end
def to_a
return @records if loaded?
- @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ @records = if @readonly_value.nil? && !@klass.locking_enabled?
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ else
+ IdentityMap.without do
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ end
+ end
preload = @preload_values
preload += @includes_values unless eager_loading?
- preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
+ 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.
@@ -150,17 +173,29 @@ module ActiveRecord
#
# # Update all books that match conditions, but limit it to 5 ordered by date
# Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
+ #
+ # # Conditions from the current relation also works
+ # Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
+ #
+ # # The same idea applies to limit and order
+ # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
def update_all(updates, conditions = nil, options = {})
if conditions || options.present?
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
else
+ limit = nil
+ order = []
# Apply limit and order only if they're both present
if @limit_value.present? == @order_values.present?
- stmt = arel.compile_update(Arel::SqlLiteral.new(@klass.send(:sanitize_sql_for_assignment, updates)))
- @klass.connection.update stmt.to_sql
- else
- except(:limit, :order).update_all(updates)
+ limit = arel.limit
+ order = arel.orders
end
+
+ stmt = arel.compile_update(Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)))
+ stmt.take limit if limit
+ stmt.order(*order)
+ stmt.key = table[primary_key]
+ @klass.connection.update stmt.to_sql
end
end
@@ -217,6 +252,7 @@ module ActiveRecord
#
# Person.destroy_all("last_login < '2004-04-04'")
# Person.destroy_all(:status => "inactive")
+ # Person.where(:age => 0..18).destroy_all
def destroy_all(conditions = nil)
if conditions
where(conditions).destroy_all
@@ -266,6 +302,7 @@ module ActiveRecord
#
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
+ # Post.where(:person_id => 5).where(:category => ['Something', 'Else']).delete_all
#
# Both calls delete the affected posts all at once with a single DELETE statement.
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
@@ -302,7 +339,7 @@ module ActiveRecord
# # Delete multiple rows
# Todo.delete([2,3,4])
def delete(id_or_array)
- where(@klass.primary_key => id_or_array).delete_all
+ where(primary_key => id_or_array).delete_all
end
def reload
@@ -318,10 +355,6 @@ module ActiveRecord
self
end
- def primary_key
- @primary_key ||= table[@klass.primary_key]
- end
-
def to_sql
@to_sql ||= arel.to_sql
end
@@ -355,10 +388,6 @@ module ActiveRecord
to_a.inspect
end
- def table_name
- @klass.table_name
- end
-
protected
def method_missing(method, *args, &block)
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index b41e935ed5..bf5a60f458 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -39,7 +39,7 @@ module ActiveRecord
# ascending on the primary key ("id ASC") to make the batch ordering
# work. This also mean that this method only works with integer-based
# primary keys. You can't set the limit either, that's used to control
- # the the batch sizes.
+ # the batch sizes.
#
# Example:
#
@@ -65,7 +65,7 @@ module ActiveRecord
batch_size = options.delete(:batch_size) || 1000
relation = relation.except(:order).order(batch_order).limit(batch_size)
- records = relation.where(primary_key.gteq(start)).all
+ records = relation.where(table[primary_key].gteq(start)).all
while records.any?
yield records
@@ -73,7 +73,7 @@ module ActiveRecord
break if records.size < batch_size
if primary_key_offset = records.last.id
- records = relation.where(primary_key.gt(primary_key_offset)).to_a
+ records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
else
raise "Primary key not included in the custom select clause"
end
@@ -83,7 +83,7 @@ module ActiveRecord
private
def batch_order
- "#{@klass.table_name}.#{@klass.primary_key} ASC"
+ "#{table_name}.#{primary_key} ASC"
end
end
end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index fd45bb24dd..c1842b1a96 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -168,7 +168,7 @@ module ActiveRecord
unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
distinct = true
- column_name = @klass.primary_key if column_name == :all
+ column_name = primary_key if column_name == :all
end
distinct = nil if column_name =~ /\s*DISTINCT\s+/i
@@ -204,14 +204,26 @@ module ActiveRecord
relation.select_values = [select_value]
- type_cast_calculated_value(@klass.connection.select_value(relation.to_sql), column_for(column_name), operation)
+ query_builder = relation.arel
+
+ if operation == "count"
+ limit = relation.limit_value
+ offset = relation.offset_value
+
+ unless limit && offset
+ query_builder.limit = nil
+ query_builder.offset = nil
+ end
+ end
+
+ type_cast_calculated_value(@klass.connection.select_value(query_builder.to_sql), column_for(column_name), operation)
end
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
group_attr = @group_values
association = @klass.reflect_on_association(group_attr.first.to_sym)
associated = group_attr.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
- group_fields = Array(associated ? association.primary_key_name : group_attr)
+ group_fields = Array(associated ? association.foreign_key : group_attr)
group_aliases = group_fields.map { |field| column_alias_for(field) }
group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
[aliaz, column_for(field)]
@@ -282,15 +294,11 @@ module ActiveRecord
end
def type_cast_calculated_value(value, column, operation = nil)
- if value.is_a?(String) || value.nil?
- case operation
- when 'count' then value.to_i
- when 'sum' then type_cast_using_column(value || '0', column)
- when 'average' then value.try(:to_d)
- else type_cast_using_column(value, column)
- end
- else
- type_cast_using_column(value, column)
+ case operation
+ when 'count' then value.to_i
+ when 'sum' then type_cast_using_column(value || '0', column)
+ when 'average' then value.respond_to?(:to_d) ? value.to_d : value
+ else type_cast_using_column(value, column)
end
end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 906ad7699c..426000fde1 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -19,7 +19,7 @@ module ActiveRecord
#
# All approaches accept an options hash as their last parameter.
#
- # ==== Parameters
+ # ==== Options
#
# * <tt>:conditions</tt> - An SQL fragment like "administrator = 1", <tt>["user_name = ?", username]</tt>,
# or <tt>["user_name = :user_name", { :user_name => user_name }]</tt>. See conditions in the intro.
@@ -171,13 +171,13 @@ module ActiveRecord
def exists?(id = nil)
id = id.id if ActiveRecord::Base === id
- relation = select(primary_key).limit(1)
+ relation = select("1").limit(1)
case id
when Array, Hash
relation = relation.where(id)
else
- relation = relation.where(primary_key.eq(id)) if id
+ relation = relation.where(table[primary_key].eq(id)) if id
end
relation.first ? true : false
@@ -187,8 +187,9 @@ module ActiveRecord
def find_with_associations
including = (@eager_load_values + @includes_values).uniq
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, including, nil)
- rows = construct_relation_for_association_find(join_dependency).to_a
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
+ relation = construct_relation_for_association_find(join_dependency)
+ rows = connection.select_all(relation.to_sql, 'SQL', relation.bind_values)
join_dependency.instantiate(rows)
rescue ThrowResult
[]
@@ -196,7 +197,7 @@ module ActiveRecord
def construct_relation_for_association_calculations
including = (@eager_load_values + @includes_values).uniq
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, including, arel.froms.first)
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
relation = except(:includes, :eager_load, :preload)
apply_join_dependency(relation, join_dependency)
end
@@ -225,10 +226,10 @@ module ActiveRecord
def construct_limited_ids_condition(relation)
orders = relation.order_values
- values = @klass.connection.distinct("#{@klass.connection.quote_table_name @klass.table_name}.#{@klass.primary_key}", orders)
+ values = @klass.connection.distinct("#{@klass.connection.quote_table_name table_name}.#{primary_key}", orders)
- ids_array = relation.select(values).collect {|row| row[@klass.primary_key]}
- ids_array.empty? ? raise(ThrowResult) : primary_key.in(ids_array)
+ ids_array = relation.select(values).collect {|row| row[primary_key]}
+ ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
end
def find_by_attributes(match, attributes, *args)
@@ -290,24 +291,24 @@ module ActiveRecord
def find_one(id)
id = id.id if ActiveRecord::Base === id
- column = columns_hash[primary_key.name.to_s]
+ column = columns_hash[primary_key]
substitute = connection.substitute_for(column, @bind_values)
- relation = where(primary_key.eq(substitute))
+ relation = where(table[primary_key].eq(substitute))
relation.bind_values = [[column, id]]
record = relation.first
unless record
conditions = arel.where_sql
conditions = " [#{conditions}]" if conditions
- raise RecordNotFound, "Couldn't find #{@klass.name} with #{@klass.primary_key}=#{id}#{conditions}"
+ raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
end
record
end
def find_some(ids)
- result = where(primary_key.in(ids)).all
+ result = where(table[primary_key].in(ids)).all
expected_size =
if @limit_value && ids.size > @limit_value
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 70d84619a1..9633fd3d82 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -15,18 +15,21 @@ module ActiveRecord
table = Arel::Table.new(table_name, :engine => engine)
end
- attribute = table[column] || Arel::Attribute.new(table, column)
+ attribute = table[column.to_sym]
case value
- when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::Relation
+ when ActiveRecord::Relation
+ value.select_values = [value.klass.arel_table['id']] if value.select_values.empty?
+ attribute.in(value.arel.ast)
+ when Array, ActiveRecord::Associations::CollectionProxy
values = value.to_a.map { |x|
- x.respond_to?(:quoted_id) ? x.quoted_id : x
+ x.is_a?(ActiveRecord::Base) ? x.id : x
}
attribute.in(values)
when Range, Arel::Relation
attribute.in(value)
when ActiveRecord::Base
- attribute.eq(Arel.sql(value.quoted_id))
+ attribute.eq(value.id)
when Class
# FIXME: I think we need to deprecate this behavior
attribute.eq(value.name)
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 51a39be065..0c7a9ec56d 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -63,7 +63,7 @@ module ActiveRecord
end
def joins(*args)
- return self if args.blank?
+ return self if args.compact.blank?
relation = clone
@@ -128,7 +128,7 @@ module ActiveRecord
def create_with(value)
relation = clone
- relation.create_with_value = value
+ relation.create_with_value = value && (@create_with_value || {}).merge(value)
relation
end
@@ -152,7 +152,7 @@ module ActiveRecord
order_clause = arel.order_clauses
order = order_clause.empty? ?
- "#{@klass.table_name}.#{@klass.primary_key} DESC" :
+ "#{table_name}.#{primary_key} DESC" :
reverse_sql_order(order_clause).join(', ')
except(:order).order(Arel.sql(order))
@@ -171,7 +171,7 @@ module ActiveRecord
arel.having(*@having_values.uniq.reject{|h| h.blank?}) unless @having_values.empty?
- arel.take(@limit_value) if @limit_value
+ arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
arel.skip(@offset_value) if @offset_value
arel.group(*@group_values.uniq.reject{|g| g.blank?}) unless @group_values.empty?
@@ -191,42 +191,25 @@ module ActiveRecord
def custom_join_ast(table, joins)
joins = joins.reject { |join| join.blank? }
- return if joins.empty?
+ return [] if joins.empty?
@implicit_readonly = true
- joins.map! do |join|
+ joins.map do |join|
case join
when Array
join = Arel.sql(join.join(' ')) if array_of_strings?(join)
when String
join = Arel.sql(join)
end
- join
- end
-
- head = table.create_string_join(table, joins.shift)
-
- joins.inject(head) do |ast, join|
- ast.right = table.create_string_join(ast.right, join)
+ table.create_string_join(join)
end
-
- head
end
def collapse_wheres(arel, wheres)
equalities = wheres.grep(Arel::Nodes::Equality)
- groups = equalities.group_by do |equality|
- equality.left
- end
-
- groups.each do |_, eqls|
- test = eqls.inject(eqls.shift) do |memo, expr|
- memo.or(expr)
- end
- arel.where(test)
- end
+ arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
(wheres - equalities).each do |where|
where = Arel.sql(where) if String === where
@@ -247,18 +230,40 @@ module ActiveRecord
end
def build_joins(manager, joins)
- joins = joins.map {|j| j.respond_to?(:strip) ? j.strip : j}.uniq
-
- association_joins = joins.find_all do |join|
- [Hash, Array, Symbol].include?(join.class) && !array_of_strings?(join)
+ buckets = joins.group_by do |join|
+ case join
+ when String
+ 'string_join'
+ when Hash, Symbol, Array
+ 'association_join'
+ when ActiveRecord::Associations::JoinDependency::JoinAssociation
+ 'stashed_join'
+ when Arel::Nodes::Join
+ 'join_node'
+ else
+ raise 'unknown class: %s' % join.class.name
+ end
end
- stashed_association_joins = joins.grep(ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation)
+ association_joins = buckets['association_join'] || []
+ stashed_association_joins = buckets['stashed_join'] || []
+ join_nodes = buckets['join_node'] || []
+ string_joins = (buckets['string_join'] || []).map { |x|
+ x.strip
+ }.uniq
+
+ join_list = custom_join_ast(manager, string_joins)
- non_association_joins = (joins - association_joins - stashed_association_joins)
- join_ast = custom_join_ast(manager.froms.first, non_association_joins)
+ join_dependency = ActiveRecord::Associations::JoinDependency.new(
+ @klass,
+ association_joins,
+ join_list
+ )
- join_dependency = ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, association_joins, join_ast)
+ # TODO: Necessary?
+ join_nodes.each do |join|
+ join_dependency.alias_tracker.aliased_name_for(join.left.name.downcase)
+ end
join_dependency.graft(*stashed_association_joins)
@@ -269,10 +274,9 @@ module ActiveRecord
association.join_to(manager)
end
- return manager unless join_ast
+ manager.join_sources.concat join_nodes.uniq
+ manager.join_sources.concat join_list
- join_ast.left = manager.froms.first
- manager.from join_ast
manager
end
@@ -281,7 +285,7 @@ module ActiveRecord
@implicit_readonly = false
arel.project(*selects)
else
- arel.project(Arel.sql(@klass.quoted_table_name + '.*'))
+ arel.project(@klass.arel_table[Arel.star])
end
end
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
index 5acf3ec83a..4150e36a9a 100644
--- a/activerecord/lib/active_record/relation/spawn_methods.rb
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -46,21 +46,28 @@ module ActiveRecord
merged_relation.where_values = merged_wheres
- (Relation::SINGLE_VALUE_METHODS - [:lock]).each do |method|
+ (Relation::SINGLE_VALUE_METHODS - [:lock, :create_with]).each do |method|
value = r.send(:"#{method}_value")
merged_relation.send(:"#{method}_value=", value) unless value.nil?
end
merged_relation.lock_value = r.lock_value unless merged_relation.lock_value
+ merged_relation = merged_relation.create_with(r.create_with_value) if r.create_with_value
+
# Apply scope extension modules
merged_relation.send :apply_modules, r.extensions
merged_relation
end
- alias :& :merge
-
+ # Removes from the query the condition(s) specified in +skips+.
+ #
+ # Example:
+ #
+ # Post.order('id asc').except(:order) # discards the order condition
+ # Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
+ #
def except(*skips)
result = self.class.new(@klass, table)
@@ -75,6 +82,13 @@ module ActiveRecord
result
end
+ # Removes any condition from the query other than the one(s) specified in +onlies+.
+ #
+ # Example:
+ #
+ # Post.order('id asc').only(:where) # discards the order condition
+ # Post.order('id asc').only(:where, :order) # uses the specified order
+ #
def only(*onlies)
result = self.class.new(@klass, table)
@@ -98,7 +112,7 @@ module ActiveRecord
options.assert_valid_keys(VALID_FIND_OPTIONS)
finders = options.dup
- finders.delete_if { |key, value| value.nil? }
+ finders.delete_if { |key, value| value.nil? && key != :limit }
([:joins, :select, :group, :order, :having, :limit, :offset, :from, :lock, :readonly] & finders.keys).each do |finder|
relation = relation.send(finder, finders[finder])
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb
index 8deff1478f..0465b21e88 100644
--- a/activerecord/lib/active_record/result.rb
+++ b/activerecord/lib/active_record/result.rb
@@ -20,10 +20,14 @@ module ActiveRecord
hash_rows.each { |row| yield row }
end
+ def to_hash
+ hash_rows
+ end
+
private
def hash_rows
@hash_rows ||= @rows.map { |row|
- ActiveSupport::OrderedHash[@columns.zip(row)]
+ Hash[@columns.zip(row)]
}
end
end
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index e30b481fe1..a893c0ad85 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -83,7 +83,7 @@ HEADER
# first dump primary key column
if @connection.respond_to?(:pk_and_sequence_for)
- pk, pk_seq = @connection.pk_and_sequence_for(table)
+ pk, _ = @connection.pk_and_sequence_for(table)
elsif @connection.respond_to?(:primary_key)
pk = @connection.primary_key(table)
end
diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb
index 15abf8bac7..8c4adf7116 100644
--- a/activerecord/lib/active_record/serializers/xml_serializer.rb
+++ b/activerecord/lib/active_record/serializers/xml_serializer.rb
@@ -226,17 +226,17 @@ module ActiveRecord #:nodoc:
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
def compute_type
- type = @serializable.class.serialized_attributes.has_key?(name) ?
- super : @serializable.class.columns_hash[name].type
+ klass = @serializable.class
+ type = if klass.serialized_attributes.key?(name)
+ super
+ elsif klass.columns_hash.key?(name)
+ klass.columns_hash[name].type
+ else
+ NilClass
+ end
- case type
- when :text
- :string
- when :time
- :datetime
- else
- type
- end
+ { :text => :string,
+ :time => :datetime }[type] || type
end
protected :compute_type
end
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
index 3400fd6ade..7e77aefb21 100644
--- a/activerecord/lib/active_record/session_store.rb
+++ b/activerecord/lib/active_record/session_store.rb
@@ -59,10 +59,12 @@ module ActiveRecord
end
def drop_table!
+ connection_pool.clear_table_cache!(table_name)
connection.drop_table table_name
end
def create_table!
+ connection_pool.clear_table_cache!(table_name)
connection.create_table(table_name) do |t|
t.string session_id_column, :limit => 255
t.text data_column_name
diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb
index 014a900c71..29efbbcb8c 100644
--- a/activerecord/lib/active_record/test_case.rb
+++ b/activerecord/lib/active_record/test_case.rb
@@ -3,6 +3,16 @@ module ActiveRecord
#
# Defines some test assertions to test against SQL queries.
class TestCase < ActiveSupport::TestCase #:nodoc:
+ setup :cleanup_identity_map
+
+ def setup
+ cleanup_identity_map
+ end
+
+ def cleanup_identity_map
+ ActiveRecord::IdentityMap.clear
+ end
+
def assert_date_from_db(expected, actual, message = nil)
# SybaseAdapter doesn't have a separate column type just for dates,
# so the time is in the string and incorrectly formatted
@@ -16,6 +26,7 @@ module ActiveRecord
def assert_sql(*patterns_to_match)
$queries_executed = []
yield
+ $queries_executed
ensure
failed_patterns = []
patterns_to_match.each do |pattern|
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
index 2ecbd906bd..1511c71ffc 100644
--- a/activerecord/lib/active_record/timestamp.rb
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -9,24 +9,26 @@ module ActiveRecord
#
# Timestamping can be turned off by setting:
#
- # <tt>ActiveRecord::Base.record_timestamps = false</tt>
+ # config.active_record.record_timestamps = false
#
# Timestamps are in the local timezone by default but you can use UTC by setting:
#
- # <tt>ActiveRecord::Base.default_timezone = :utc</tt>
+ # config.active_record.default_timezone = :utc
#
# == Time Zone aware attributes
#
# By default, ActiveRecord::Base keeps all the datetime columns time zone aware by executing following code.
#
- # ActiveRecord::Base.time_zone_aware_attributes = true
+ # config.active_record.time_zone_aware_attributes = true
#
# This feature can easily be turned off by assigning value <tt>false</tt> .
#
- # If your attributes are time zone aware and you desire to skip time zone conversion for certain
- # attributes then you can do following:
+ # If your attributes are time zone aware and you desire to skip time zone conversion to the current Time.zone
+ # when reading certain attributes then you can do following:
#
- # Topic.skip_time_zone_conversion_for_attributes = [:written_on]
+ # class Topic < ActiveRecord::Base
+ # self.skip_time_zone_conversion_for_attributes = [:written_on]
+ # end
module Timestamp
extend ActiveSupport::Concern
@@ -66,8 +68,16 @@ module ActiveRecord
self.record_timestamps && (!partial_updates? || changed? || (attributes.keys & self.class.serialized_attributes.keys).present?)
end
+ def timestamp_attributes_for_create_in_model
+ timestamp_attributes_for_create.select { |c| self.class.column_names.include?(c.to_s) }
+ end
+
def timestamp_attributes_for_update_in_model
- timestamp_attributes_for_update.select { |c| respond_to?(c) }
+ timestamp_attributes_for_update.select { |c| self.class.column_names.include?(c.to_s) }
+ end
+
+ def all_timestamp_attributes_in_model
+ timestamp_attributes_for_create_in_model + timestamp_attributes_for_update_in_model
end
def timestamp_attributes_for_update #:nodoc:
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index 443f318067..60d4c256c4 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -251,6 +251,7 @@ module ActiveRecord
remember_transaction_record_state
yield
rescue Exception
+ IdentityMap.remove(self) if IdentityMap.enabled?
restore_transaction_record_state
raise
ensure
@@ -259,7 +260,7 @@ module ActiveRecord
# Call the after_commit callbacks
def committed! #:nodoc:
- _run_commit_callbacks
+ run_callbacks :commit
ensure
clear_transaction_record_state
end
@@ -267,7 +268,7 @@ module ActiveRecord
# Call the after rollback callbacks. The restore_state argument indicates if the record
# state should be rolled back to the beginning or just to the last savepoint.
def rolledback!(force_restore_state = false) #:nodoc:
- _run_rollback_callbacks
+ run_callbacks :rollback
ensure
restore_transaction_record_state(force_restore_state)
end
@@ -301,8 +302,8 @@ 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)
unless @_start_transaction_state.include?(:new_record)
- @_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
@_start_transaction_state[:new_record] = @new_record
end
unless @_start_transaction_state.include?(:destroyed)
@@ -325,16 +326,14 @@ module ActiveRecord
@_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 restore_state
- @attributes = @attributes.dup if @attributes.frozen?
- @new_record = restore_state[:new_record]
- @destroyed = restore_state[:destroyed]
- if restore_state[:id]
- self.id = restore_state[:id]
- else
- @attributes.delete(self.class.primary_key)
- @attributes_cache.delete(self.class.primary_key)
- end
+ @attributes = @attributes.dup if @attributes.frozen?
+ @new_record = restore_state[:new_record]
+ @destroyed = restore_state[:destroyed]
+ if restore_state.has_key?(:id)
+ self.id = restore_state[:id]
+ else
+ @attributes.delete(self.class.primary_key)
+ @attributes_cache.delete(self.class.primary_key)
end
end
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index f367315b22..d73fce9fd0 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -1,5 +1,5 @@
module ActiveRecord
- # = Active Record Validations
+ # = Active Record RecordInvalid
#
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
# +record+ method to retrieve the record which did not validate.
@@ -18,6 +18,13 @@ module ActiveRecord
end
end
+ # = Active Record Validations
+ #
+ # Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
+ # all of which accept the <tt>:on</tt> argument to define the context where the
+ # validations are active. Active Record will always supply either the context of
+ # <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
+ # <tt>new_record?</tt>.
module Validations
extend ActiveSupport::Concern
include ActiveModel::Validations
@@ -37,7 +44,7 @@ module ActiveRecord
end
end
- # The validation process on save can be skipped by passing false. The regular Base#save method is
+ # The validation process on save can be skipped by passing :validate => false. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
perform_validations(options) ? super : false
@@ -49,7 +56,14 @@ module ActiveRecord
perform_validations(options) ? super : raise(RecordInvalid.new(self))
end
- # Runs all the specified validations and returns true if no errors were added otherwise false.
+ # Runs all the validations within the specified context. Returns true if no errors are found,
+ # false otherwise.
+ #
+ # If the argument is false (default is +nil+), the context is set to <tt>:create</tt> if
+ # <tt>new_record?</tt> is true, and to <tt>:update</tt> if it is not.
+ #
+ # Validations with no <tt>:on</tt> option will run no matter the context. Validations with
+ # some <tt>:on</tt> option will only run in the specified context.
def valid?(context = nil)
context ||= (new_record? ? :create : :update)
output = super(context)
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index 183acd73b8..3a783aeb00 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -33,7 +33,9 @@ module ActiveRecord
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
- # * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
+ # * <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.
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 853808eebf..a96796f9ff 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -15,8 +15,10 @@ module ActiveRecord
def validate_each(record, attribute, value)
finder_class = find_finder_class_for(record)
- if value && record.class.serialized_attributes.key?(attribute.to_s)
- value = YAML.dump value
+ coder = record.class.serialized_attributes[attribute.to_s]
+
+ if value && coder
+ value = coder.dump value
end
sql, params = mount_sql_and_params(finder_class, record.class.quoted_table_name, attribute, value)
@@ -85,11 +87,16 @@ module ActiveRecord
# can be named "davidhh".
#
# class Person < ActiveRecord::Base
- # validates_uniqueness_of :user_name, :scope => :account_id
+ # validates_uniqueness_of :user_name
# end
#
- # It can also validate whether the value of the specified attributes are unique based on multiple
- # scope parameters. For example, making sure that a teacher can only be on the schedule once
+ # It can also validate whether the value of the specified attributes are unique based on a scope parameter:
+ #
+ # class Person < ActiveRecord::Base
+ # 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.
#
# class TeacherSchedule < ActiveRecord::Base
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 126b6f434b..ce8d7eed42 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
@@ -1,4 +1,11 @@
class <%= migration_class_name %> < ActiveRecord::Migration
+<%- if migration_action == 'add' -%>
+ def change
+<% attributes.each do |attribute| -%>
+ add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %>
+<%- end -%>
+ end
+<%- else -%>
def up
<% attributes.each do |attribute| -%>
<%- if migration_action -%>
@@ -14,4 +21,5 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<%- end -%>
<%- end -%>
end
+<%- end -%>
end
diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
index c75abd043c..f7caa43ac8 100644
--- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
@@ -10,6 +10,7 @@ module ActiveRecord
class_option :migration, :type => :boolean
class_option :timestamps, :type => :boolean
class_option :parent, :type => :string, :desc => "The parent class for the generated model"
+ class_option :indexes, :type => :boolean, :default => true, :desc => "Add indexes for references and belongs_to columns"
def create_migration_file
return unless options[:migration] && options[:parent].nil?
diff --git a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb
index 70e064be21..4f81a52fd0 100644
--- a/activerecord/lib/rails/generators/active_record/model/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/model/templates/migration.rb
@@ -1,5 +1,5 @@
class <%= migration_class_name %> < ActiveRecord::Migration
- def up
+ def change
create_table :<%= table_name %> do |t|
<% for attribute in attributes -%>
t.<%= attribute.type %> :<%= attribute.name %>
@@ -8,9 +8,10 @@ class <%= migration_class_name %> < ActiveRecord::Migration
t.timestamps
<% end -%>
end
- end
-
- def down
- drop_table :<%= table_name %>
+<% if options[:indexes] -%>
+<% attributes.select {|attr| attr.reference? }.each do |attribute| -%>
+ add_index :<%= table_name %>, :<%= attribute.name %>_id
+<% end -%>
+<% end -%>
end
end
diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
new file mode 100644
index 0000000000..1c2942170e
--- /dev/null
+++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
@@ -0,0 +1,36 @@
+module ActiveRecord
+ class Base
+ def self.fake_connection(config)
+ ConnectionAdapters::FakeAdapter.new nil, logger
+ end
+ end
+
+ module ConnectionAdapters
+ class FakeAdapter < AbstractAdapter
+ attr_accessor :tables, :primary_keys
+
+ def initialize(connection, logger)
+ super
+ @tables = []
+ @primary_keys = {}
+ @columns = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def primary_key(table)
+ @primary_keys[table]
+ end
+
+ def merge_column(table_name, name, sql_type = nil, options = {})
+ @columns[table_name] << ActiveRecord::ConnectionAdapters::Column.new(
+ name.to_s,
+ options[:default],
+ sql_type.to_s,
+ options[:null])
+ end
+
+ def columns(table_name, message)
+ @columns[table_name]
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb
index 646aa88d80..49b2e945c3 100644
--- a/activerecord/test/cases/adapter_test.rb
+++ b/activerecord/test/cases/adapter_test.rb
@@ -141,16 +141,4 @@ class AdapterTest < ActiveRecord::TestCase
end
end
end
-
- def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas
- sql_inject = "1 select * from schema"
- assert_no_match(/schema/, @connection.add_limit_offset!("", :limit=>sql_inject))
- assert_no_match(/schema/, @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7))
- end
-
- def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas
- sql_inject = "1, 7 procedure help()"
- assert_no_match(/procedure/, @connection.add_limit_offset!("", :limit=>sql_inject))
- assert_no_match(/procedure/, @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7))
- end
end
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
index 62ffde558f..eb3f8143e7 100644
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -102,7 +102,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase
end
# Test that MySQL allows multiple results for stored procedures
- if Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
+ if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
def test_multi_results
rows = ActiveRecord::Base.connection.select_rows('CALL ten();')
assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
index 90d8b0d923..43015098c9 100644
--- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
@@ -78,24 +78,6 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
- #fixtures :group
-
- def test_fixtures
- f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
-
- assert_nothing_raised {
- f.each do |x|
- x.delete_existing_fixtures
- end
- }
-
- assert_nothing_raised {
- f.each do |x|
- x.insert_fixtures
- end
- }
- end
-
#activerecord model class with reserved-word table name
def test_activerecord_model
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
@@ -105,9 +87,9 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
assert_nothing_raised { x.save }
x.order = 'y'
assert_nothing_raised { x.save }
- assert_nothing_raised { y = Group.find_by_order('y') }
- assert_nothing_raised { y = Group.find(1) }
- x = Group.find(1)
+ assert_nothing_raised { Group.find_by_order('y') }
+ assert_nothing_raised { Group.find(1) }
+ Group.find(1)
end
# has_one association with reserved-word table name
diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
index 90d8b0d923..1efa7deaeb 100644
--- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
@@ -78,24 +78,6 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
- #fixtures :group
-
- def test_fixtures
- f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
-
- assert_nothing_raised {
- f.each do |x|
- x.delete_existing_fixtures
- end
- }
-
- assert_nothing_raised {
- f.each do |x|
- x.insert_fixtures
- end
- }
- end
-
#activerecord model class with reserved-word table name
def test_activerecord_model
create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 234696adeb..b8abdface4 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -9,6 +9,11 @@ module ActiveRecord
:timeout => 100
end
+ def test_primary_key_returns_nil_for_no_pk
+ @conn.exec_query('create table ex(id int, data string)')
+ assert_nil @conn.primary_key('ex')
+ end
+
def test_connection_no_db
assert_raises(ArgumentError) do
Base.sqlite3_connection {}
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 1820f95261..9006914508 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -17,7 +17,7 @@ require 'models/essay'
class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
:developers_projects, :computers, :authors, :author_addresses,
- :posts, :tags, :taggings, :comments
+ :posts, :tags, :taggings, :comments, :sponsors, :members
def test_belongs_to
Client.find(3).firm.name
@@ -50,11 +50,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { account.firm = account.firm }
end
- def test_triple_equality
- assert Client.find(3).firm === Firm
- assert Firm === Client.find(3).firm
- end
-
def test_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 }
assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) }
@@ -78,27 +73,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key)
- assert_not_nil citibank_result.instance_variable_get("@firm_with_primary_key")
+ 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.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key_symbols)
- assert_not_nil citibank_result.instance_variable_get("@firm_with_primary_key_symbols")
- end
-
- def test_no_unexpected_aliasing
- first_firm = companies(:first_firm)
- another_firm = companies(:another_firm)
-
- citibank = Account.create("credit_limit" => 10)
- citibank.firm = first_firm
- original_proxy = citibank.firm
- citibank.firm = another_firm
-
- assert_equal first_firm.object_id, original_proxy.target.object_id
- assert_equal another_firm.object_id, citibank.firm.target.object_id
+ assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols)
end
def test_creating_the_belonging_object
@@ -133,6 +115,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal apple.name, client.firm_name
end
+ def test_create!
+ client = Client.create!(:name => "Jimmy")
+ account = client.create_account!(:credit_limit => 10)
+ assert_equal account, client.account
+ assert account.persisted?
+ client.save
+ client.reload
+ assert_equal account, client.account
+ end
+
+ def test_failing_create!
+ client = Client.create!(:name => "Jimmy")
+ assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
+ assert_not_nil client.account
+ assert client.account.new_record?
+ end
+
def test_natural_assignment_to_nil
client = Client.find(3)
client.firm = nil
@@ -159,6 +158,15 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm"
end
+ def test_with_polymorphic_and_condition
+ sponsor = Sponsor.create
+ member = Member.create :name => "Bert"
+ sponsor.sponsorable = member
+
+ assert_equal member, sponsor.sponsorable
+ assert_nil sponsor.sponsorable_with_conditions
+ end
+
def test_with_select
assert_equal Company.find(2).firm_with_select.attributes.size, 1
assert_equal Company.find(2, :include => :firm_with_select ).firm_with_select.attributes.size, 1
@@ -175,17 +183,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
end
- def test_belongs_to_with_primary_key_counter
- debate = Topic.create("title" => "debate")
- assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet"
-
- trash = debate.replies_with_primary_key.create("title" => "blah!", "content" => "world around!")
- assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply created"
-
- trash.destroy
- assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted"
- end
-
def test_belongs_to_counter_with_assigning_nil
p = Post.find(1)
c = Comment.find(1)
@@ -198,16 +195,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal 1, Post.find(p.id).comments.size
end
- def test_belongs_to_with_primary_key_counter_with_assigning_nil
- debate = Topic.create("title" => "debate")
- reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")
+ def test_belongs_to_with_primary_key_counter
+ debate = Topic.create("title" => "debate")
+ debate2 = Topic.create("title" => "debate2")
+ reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate")
+
+ assert_equal 1, debate.reload.replies_count
+ assert_equal 0, debate2.reload.replies_count
- assert_equal debate.title, reply.parent_title
- assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count")
+ reply.topic_with_primary_key = debate2
+
+ assert_equal 0, debate.reload.replies_count
+ assert_equal 1, debate2.reload.replies_count
reply.topic_with_primary_key = nil
- assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count")
+ assert_equal 0, debate.reload.replies_count
+ assert_equal 0, debate2.reload.replies_count
end
def test_belongs_to_counter_with_reassigning
@@ -311,13 +315,21 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id
end
- def test_forgetting_the_load_when_foreign_key_enters_late
- c = Client.new
- assert_nil c.firm_with_basic_id
+ def test_setting_foreign_key_after_nil_target_loaded
+ client = Client.new
+ client.firm_with_basic_id
+ client.firm_id = 1
- c.firm_id = 1
- # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id
+ assert_equal companies(:first_firm), client.firm_with_basic_id
+ end
+
+ def test_polymorphic_setting_foreign_key_after_nil_target_loaded
+ sponsor = Sponsor.new
+ sponsor.sponsorable
+ sponsor.sponsorable_id = 1
+ sponsor.sponsorable_type = "Member"
+
+ assert_equal members(:groucho), sponsor.sponsorable
end
def test_field_name_same_as_foreign_key
@@ -419,6 +431,18 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_nil sponsor.sponsorable_id
end
+ def test_assignment_updates_foreign_id_field_for_new_and_saved_records
+ client = Client.new
+ saved_firm = Firm.create :name => "Saved"
+ new_firm = Firm.new
+
+ client.firm = saved_firm
+ assert_equal saved_firm.id, client.client_of
+
+ client.firm = new_firm
+ assert_nil client.client_of
+ end
+
def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
essay = Essay.new
saved_writer = Author.create(:name => "David")
@@ -488,39 +512,118 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
end
def test_reassigning_the_parent_id_updates_the_object
- original_parent = Firm.create! :name => "original"
- updated_parent = Firm.create! :name => "updated"
+ client = companies(:second_client)
+
+ client.firm
+ client.firm_with_condition
+ firm_proxy = client.send(:association_instance_get, :firm)
+ firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition)
- client = Client.new("client_of" => original_parent.id)
- assert_equal original_parent, client.firm
- assert_equal original_parent, client.firm_with_condition
- assert_equal original_parent, client.firm_with_other_name
+ assert !firm_proxy.stale_target?
+ assert !firm_with_condition_proxy.stale_target?
+ assert_equal companies(:first_firm), client.firm
+ assert_equal companies(:first_firm), client.firm_with_condition
- client.client_of = updated_parent.id
- assert_equal updated_parent, client.firm
- assert_equal updated_parent, client.firm_with_condition
- assert_equal updated_parent, client.firm_with_other_name
+ client.client_of = companies(:another_firm).id
+
+ assert firm_proxy.stale_target?
+ assert firm_with_condition_proxy.stale_target?
+ assert_equal companies(:another_firm), client.firm
+ assert_equal companies(:another_firm), client.firm_with_condition
end
def test_polymorphic_reassignment_of_associated_id_updates_the_object
- member1 = Member.create!
- member2 = Member.create!
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+
+ sponsor.sponsorable
+ proxy = sponsor.send(:association_instance_get, :sponsorable)
- sponsor = Sponsor.new("sponsorable_type" => "Member", "sponsorable_id" => member1.id)
- assert_equal member1, sponsor.sponsorable
+ assert !proxy.stale_target?
+ assert_equal members(:groucho), sponsor.sponsorable
- sponsor.sponsorable_id = member2.id
- assert_equal member2, sponsor.sponsorable
+ sponsor.sponsorable_id = members(:some_other_guy).id
+
+ assert proxy.stale_target?
+ assert_equal members(:some_other_guy), sponsor.sponsorable
end
def test_polymorphic_reassignment_of_associated_type_updates_the_object
- member1 = Member.create!
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+
+ sponsor.sponsorable
+ proxy = sponsor.send(:association_instance_get, :sponsorable)
+
+ assert !proxy.stale_target?
+ assert_equal members(:groucho), sponsor.sponsorable
- sponsor = Sponsor.new("sponsorable_type" => "Member", "sponsorable_id" => member1.id)
- assert_equal member1, sponsor.sponsorable
+ sponsor.sponsorable_type = 'Firm'
- sponsor.sponsorable_type = "Firm"
- assert_not_equal member1, sponsor.sponsorable
+ assert proxy.stale_target?
+ assert_equal companies(:first_firm), sponsor.sponsorable
end
+ def test_reloading_association_with_key_change
+ client = companies(:second_client)
+ firm = client.association(:firm)
+
+ client.firm = companies(:another_firm)
+ firm.reload
+ assert_equal companies(:another_firm), firm.target
+
+ client.client_of = companies(:first_firm).id
+ firm.reload
+ assert_equal companies(:first_firm), firm.target
+ end
+
+ def test_polymorphic_counter_cache
+ tagging = taggings(:welcome_general)
+ post = posts(:welcome)
+ comment = comments(:greetings)
+
+ assert_difference 'post.reload.taggings_count', -1 do
+ assert_difference 'comment.reload.taggings_count', +1 do
+ tagging.taggable = comment
+ end
+ end
+ end
+
+ def test_polymorphic_with_custom_foreign_type
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ groucho = members(:groucho)
+ other = members(:some_other_guy)
+
+ assert_equal groucho, sponsor.sponsorable
+ assert_equal groucho, sponsor.thing
+
+ sponsor.thing = other
+
+ assert_equal other, sponsor.sponsorable
+ assert_equal other, sponsor.thing
+
+ sponsor.sponsorable = groucho
+
+ assert_equal groucho, sponsor.sponsorable
+ assert_equal groucho, sponsor.thing
+ end
+
+ def test_build_with_conditions
+ client = companies(:second_client)
+ firm = client.build_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_bang_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm!
+
+ assert_equal "Bob", firm.name
+ end
end
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb
index 6a30e2905b..2d0d4541b4 100644
--- a/activerecord/test/cases/associations/callbacks_test.rb
+++ b/activerecord/test/cases/associations/callbacks_test.rb
@@ -3,6 +3,7 @@ require 'models/post'
require 'models/author'
require 'models/project'
require 'models/developer'
+require 'models/company'
class AssociationCallbacksTest < ActiveRecord::TestCase
fixtures :posts, :authors, :projects, :developers
@@ -81,6 +82,14 @@ class AssociationCallbacksTest < ActiveRecord::TestCase
assert_equal callback_log, jack.post_log
end
+ def test_has_many_callbacks_for_destroy_on_parent
+ firm = Firm.create! :name => "Firm"
+ client = firm.clients.create! :name => "Client"
+ firm.destroy
+
+ assert_equal ["before_remove#{client.id}", "after_remove#{client.id}"], firm.log
+ end
+
def test_has_and_belongs_to_many_add_callback
david = developers(:david)
ar = projects(:active_record)
diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
index fb59f63f91..d75791cab9 100644
--- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
+++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb
@@ -27,6 +27,7 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase
post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging )
assert_nil post.tagging
+ ActiveRecord::IdentityMap.clear
ActiveRecord::Base.store_full_sti_class = true
post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging )
assert_instance_of Tagging, post.tagging
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 c7671a8c22..2cf9f89c3c 100644
--- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -1,9 +1,11 @@
require 'cases/helper'
require 'models/post'
+require 'models/tag'
require 'models/author'
require 'models/comment'
require 'models/category'
require 'models/categorization'
+require 'models/tagging'
require 'active_support/core_ext/array/random_access'
module Remembered
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 949fbb9300..ed6337b596 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -17,18 +17,28 @@ require 'models/subscription'
require 'models/book'
require 'models/developer'
require 'models/project'
+require 'models/member'
+require 'models/membership'
+require 'models/club'
+require 'models/categorization'
+require 'models/sponsor'
class EagerAssociationTest < ActiveRecord::TestCase
fixtures :posts, :comments, :authors, :author_addresses, :categories, :categories_posts,
- :companies, :accounts, :tags, :taggings, :people, :readers,
+ :companies, :accounts, :tags, :taggings, :people, :readers, :categorizations,
:owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books,
- :developers, :projects, :developers_projects
+ :developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
def setup
# preheat table existence caches
Comment.find_by_id(1)
end
+ def test_eager_with_has_one_through_join_model_with_conditions_on_the_through
+ member = Member.find(members(:some_other_guy).id, :include => :favourite_club)
+ assert_nil member.favourite_club
+ end
+
def test_loading_with_one_association
posts = Post.find(:all, :include => :comments)
post = posts.find { |p| p.id == 1 }
@@ -110,30 +120,29 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_load_associated_records_in_one_query_when_adapter_has_no_limit
Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
- Post.expects(:i_was_called).with([1,2,3,4,5,6,7]).returns([1])
- associated_records = Post.send(:associated_records, [1,2,3,4,5,6,7]) do |some_ids|
- Post.i_was_called(some_ids)
+
+ post = posts(:welcome)
+ assert_queries(2) do
+ Post.includes(:comments).where(:id => post.id).to_a
end
- assert_equal [1], associated_records
end
def test_load_associated_records_in_several_queries_when_many_ids_passed
- Post.connection.expects(:in_clause_length).at_least_once.returns(5)
- Post.expects(:i_was_called).with([1,2,3,4,5]).returns([1])
- Post.expects(:i_was_called).with([6,7]).returns([6])
- associated_records = Post.send(:associated_records, [1,2,3,4,5,6,7]) do |some_ids|
- Post.i_was_called(some_ids)
+ Post.connection.expects(:in_clause_length).at_least_once.returns(1)
+
+ post1, post2 = posts(:welcome), posts(:thinking)
+ assert_queries(3) do
+ Post.includes(:comments).where(:id => [post1.id, post2.id]).to_a
end
- assert_equal [1,6], associated_records
end
def test_load_associated_records_in_one_query_when_a_few_ids_passed
- Post.connection.expects(:in_clause_length).at_least_once.returns(5)
- Post.expects(:i_was_called).with([1,2,3]).returns([1])
- associated_records = Post.send(:associated_records, [1,2,3]) do |some_ids|
- Post.i_was_called(some_ids)
+ Post.connection.expects(:in_clause_length).at_least_once.returns(3)
+
+ post = posts(:welcome)
+ assert_queries(2) do
+ Post.includes(:comments).where(:id => post.id).to_a
end
- assert_equal [1], associated_records
end
def test_including_duplicate_objects_from_belongs_to
@@ -175,7 +184,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.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments
+ author = assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # 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
@@ -186,7 +195,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
post = posts(:welcome)
author = post.author
author_address = author.author_address
- post = assert_queries(3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address
+ post = assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # 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
@@ -202,6 +211,15 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
+ 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.find(sponsor.id, :include => :sponsorable) }
+ assert_no_queries do
+ assert_equal nil, sponsor.sponsorable
+ end
+ end
+
def test_loading_from_an_association
posts = authors(:david).posts.find(:all, :include => :comments, :order => "posts.id")
assert_equal 2, posts.first.comments.size
@@ -650,7 +668,11 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_preload_with_interpolation
- assert_equal [comments(:greetings)], Post.find(posts(:welcome).id, :include => :comments_with_interpolated_conditions).comments_with_interpolated_conditions
+ post = Post.includes(:comments_with_interpolated_conditions).find(posts(:welcome).id)
+ assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions
+
+ post = Post.joins(:comments_with_interpolated_conditions).find(posts(:welcome).id)
+ assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions
end
def test_polymorphic_type_condition
@@ -794,18 +816,18 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id')
end
assert_equal posts(:welcome, :thinking), posts
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id')
end
assert_equal posts(:welcome, :thinking), posts
@@ -819,7 +841,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
- posts = assert_queries(2) do
+ posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
end
assert_equal [posts(:welcome)], posts
@@ -836,6 +858,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_loading_with_conditions_on_join_model_preloads
+ Author.columns
+
authors = assert_queries(2) do
Author.find(:all, :include => :author_address, :joins => :comments, :conditions => "posts.title like 'Welcome%'")
end
@@ -881,25 +905,55 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_preload_has_one_using_primary_key
- expected = Firm.find(:first).account_using_primary_key
- firm = Firm.find :first, :include => :account_using_primary_key
+ expected = accounts(:signals37)
+ firm = Firm.find :first, :include => :account_using_primary_key, :order => 'companies.id'
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
end
def test_include_has_one_using_primary_key
- expected = Firm.find(1).account_using_primary_key
+ expected = accounts(:signals37)
firm = Firm.find(:all, :include => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1}
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
end
- def test_preloading_empty_polymorphic_parent
+ def test_preloading_empty_belongs_to
+ c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1)
+
+ client = assert_queries(2) { Client.preload(:firm).find(c.id) }
+ assert_no_queries { assert_nil client.firm }
+ end
+
+ def test_preloading_empty_belongs_to_polymorphic
t = Tagging.create!(:taggable_type => 'Post', :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general))
- assert_queries(2) { @tagging = Tagging.preload(:taggable).find(t.id) }
- assert_no_queries { assert ! @tagging.taggable }
+ tagging = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) { Tagging.preload(:taggable).find(t.id) }
+ assert_no_queries { assert_nil tagging.taggable }
+ end
+
+ def test_preloading_through_empty_belongs_to
+ c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1)
+
+ client = assert_queries(2) { Client.preload(:accounts).find(c.id) }
+ assert_no_queries { assert client.accounts.empty? }
+ end
+
+ def test_preloading_has_many_through_with_uniq
+ mary = Author.includes(:unique_categorized_posts).where(:id => authors(:mary).id).first
+ assert_equal 1, mary.unique_categorized_posts.length
+ assert_equal 1, mary.unique_categorized_post_ids.length
+ end
+
+ def test_preloading_polymorphic_with_custom_foreign_type
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ groucho = members(:groucho)
+
+ sponsor = assert_queries(2) {
+ Sponsor.includes(:thing).where(:id => sponsor.id).first
+ }
+ assert_no_queries { assert_equal groucho, sponsor.thing }
end
end
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index efaab8569e..24830a661a 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -30,6 +30,11 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
assert_equal projects(:active_record), developers(:david).projects_extended_by_name_and_block.find_least_recent
end
+ def test_extension_with_scopes
+ assert_equal comments(:greetings), posts(:welcome).comments.offset(1).find_most_recent
+ assert_equal comments(:greetings), posts(:welcome).comments.not_again.find_most_recent
+ end
+
def test_marshalling_extensions
david = developers(:david)
assert_equal projects(:action_controller), david.projects.find_most_recent
@@ -47,12 +52,16 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
end
def test_extension_name
- extension = Proc.new {}
- name = :association_name
-
- assert_equal 'DeveloperAssociationNameAssociationExtension', Developer.send(:create_extension_modules, name, extension, []).first.name
- assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name
- assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name
- assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name
+ assert_equal 'DeveloperAssociationNameAssociationExtension', extension_name(Developer)
+ assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer)
+ assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer)
end
+
+ private
+
+ def extension_name(model)
+ builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, {}) { }
+ builder.send(:wrap_block_extension)
+ builder.options[:extend].first.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 513f76255c..73d02c9676 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
@@ -72,7 +72,7 @@ class DeveloperWithCounterSQL < ActiveRecord::Base
:join_table => "developers_projects",
:association_foreign_key => "project_id",
:foreign_key => "developer_id",
- :counter_sql => 'SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{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
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
@@ -101,38 +101,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 't1', record[1]
end
- def test_should_record_timestamp_for_join_table
- setup_data_for_habtm_case
-
- con = ActiveRecord::Base.connection
- sql = 'select * from countries_treaties'
- record = con.select_rows(sql).last
- assert_not_nil record[2]
- assert_not_nil record[3]
- if current_adapter?(:Mysql2Adapter, :OracleAdapter)
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[2].to_s(:db)
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[3].to_s(:db)
- else
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[2]
- assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[3]
- end
- end
-
- def test_should_record_timestamp_for_join_table_only_if_timestamp_should_be_recorded
- begin
- Treaty.record_timestamps = false
- setup_data_for_habtm_case
-
- con = ActiveRecord::Base.connection
- sql = 'select * from countries_treaties'
- record = con.select_rows(sql).last
- assert_nil record[2]
- assert_nil record[3]
- ensure
- Treaty.record_timestamps = true
- end
- end
-
def test_has_and_belongs_to_many
david = Developer.find(1)
@@ -218,34 +186,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal 2, aredridel.projects(true).size
end
- def test_adding_uses_default_values_on_join_table
- ac = projects(:action_controller)
- assert !developers(:jamis).projects.include?(ac)
- developers(:jamis).projects << ac
-
- assert developers(:jamis, :reload).projects.include?(ac)
- project = developers(:jamis).projects.detect { |p| p == ac }
- assert_equal 1, project.access_level.to_i
- end
-
- def test_habtm_attribute_access_and_respond_to
- project = developers(:jamis).projects[0]
- assert project.has_attribute?("name")
- assert project.has_attribute?("joined_on")
- assert project.has_attribute?("access_level")
- assert project.respond_to?("name")
- assert project.respond_to?("name=")
- assert project.respond_to?("name?")
- assert project.respond_to?("joined_on")
- # given that the 'join attribute' won't be persisted, I don't
- # think we should define the mutators
- #assert project.respond_to?("joined_on=")
- assert project.respond_to?("joined_on?")
- assert project.respond_to?("access_level")
- #assert project.respond_to?("access_level=")
- assert project.respond_to?("access_level?")
- end
-
def test_habtm_adding_before_save
no_of_devels = Developer.count
no_of_projects = Project.count
@@ -425,38 +365,41 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_removing_associations_on_destroy
david = DeveloperWithBeforeDestroyRaise.find(1)
assert !david.projects.empty?
- assert_raise(RuntimeError) { david.destroy }
+ david.destroy
assert david.projects.empty?
assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty?
end
- def test_additional_columns_from_join_table
- assert_date_from_db Date.new(2004, 10, 10), Developer.find(1).projects.first.joined_on.to_date
- end
-
def test_destroying
david = Developer.find(1)
- active_record = Project.find(1)
+ project = Project.find(1)
david.projects.reload
assert_equal 2, david.projects.size
- assert_equal 3, active_record.developers.size
+ assert_equal 3, project.developers.size
- assert_difference "Project.count", -1 do
- david.projects.destroy(active_record)
+ assert_no_difference "Project.count" do
+ david.projects.destroy(project)
end
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}")
+ assert join_records.empty?
+
assert_equal 1, david.reload.projects.size
assert_equal 1, david.projects(true).size
end
- def test_destroying_array
+ def test_destroying_many
david = Developer.find(1)
david.projects.reload
+ projects = Project.all
- assert_difference "Project.count", -Project.count do
- david.projects.destroy(Project.find(:all))
+ assert_no_difference "Project.count" do
+ david.projects.destroy(*projects)
end
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
+ assert join_records.empty?
+
assert_equal 0, david.reload.projects.size
assert_equal 0, david.projects(true).size
end
@@ -465,7 +408,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
david = Developer.find(1)
david.projects.reload
assert !david.projects.empty?
- david.projects.destroy_all
+
+ assert_no_difference "Project.count" do
+ david.projects.destroy_all
+ end
+
+ join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}")
+ assert join_records.empty?
+
assert david.projects.empty?
assert david.projects(true).empty?
end
@@ -675,25 +625,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_respond_to categories(:technology).select_testing_posts.find(:first), :correctness_marker
end
- def test_updating_attributes_on_rich_associations
- david = projects(:action_controller).developers.first
- david.name = "DHH"
- assert_raise(ActiveRecord::ReadOnlyRecord) { david.save! }
- end
-
- def test_updating_attributes_on_rich_associations_with_limited_find_from_reflection
- david = projects(:action_controller).selected_developers.first
- david.name = "DHH"
- assert_nothing_raised { david.save! }
- end
-
-
- def test_updating_attributes_on_rich_associations_with_limited_find
- david = projects(:action_controller).developers.find(:all, :select => "developers.*").first
- david.name = "DHH"
- assert david.save!
- end
-
def test_join_table_alias
assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size
end
@@ -840,10 +771,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
david = Developer.find(1)
# clear cache possibly created by other tests
david.projects.reset_column_information
- assert_queries(0) { david.projects.columns; david.projects.columns }
- # and again to verify that reset_column_information clears the cache correctly
+
+ # One query for columns, one for primary key
+ assert_queries(2) { david.projects.columns; david.projects.columns }
+
+ ## and again to verify that reset_column_information clears the cache correctly
david.projects.reset_column_information
- assert_queries(0) { david.projects.columns; david.projects.columns }
+ assert_queries(2) { david.projects.columns; david.projects.columns }
end
def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index fb772bb8e6..ad774eb9ce 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -43,7 +43,7 @@ end
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :comments,
- :people, :posts, :readers, :taggings
+ :people, :posts, :readers, :taggings, :cars
def setup
Client.destroyed_client_ids.clear
@@ -66,14 +66,36 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 'exotic', bulb.name
end
+ # When creating objects on the association, we must not do it within a scope (even though it
+ # 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)
+ original_scoped_methods = Bulb.scoped_methods
+
+ bulb = car.bulbs.build
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = car.bulbs.create
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = car.bulbs.create!
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+ end
+
def test_no_sql_should_be_fired_if_association_already_loaded
Car.create(:name => 'honda')
bulbs = Car.first.bulbs
bulbs.inspect # to load all instances of bulbs
+
assert_no_queries do
bulbs.first()
bulbs.first({})
end
+
+ assert_no_queries do
+ bulbs.last()
+ bulbs.last({})
+ end
end
def test_create_resets_cached_counters
@@ -257,7 +279,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_counting_using_finder_sql
assert_equal 2, Firm.find(4).clients_using_sql.count
- assert_equal 2, Firm.find(4).clients_using_multiline_sql.count
end
def test_belongs_to_sanity
@@ -608,7 +629,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal topic.replies.to_a.size, topic.replies_count
end
- def test_deleting_updates_counter_cache_without_dependent_destroy
+ def test_deleting_updates_counter_cache_without_dependent_option
post = posts(:welcome)
assert_difference "post.reload.taggings_count", -1 do
@@ -616,6 +637,24 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_deleting_updates_counter_cache_with_dependent_delete_all
+ post = posts(:welcome)
+ post.update_attribute(: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)
+ end
+ end
+
+ def test_deleting_updates_counter_cache_with_dependent_destroy
+ post = posts(:welcome)
+ post.update_attribute(: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)
+ end
+ end
+
def test_deleting_a_collection
force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
@@ -628,8 +667,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_delete_all
force_signal37_to_load_all_clients_of_firm
companies(:first_firm).clients_of_firm.create("name" => "Another Client")
- assert_equal 2, companies(:first_firm).clients_of_firm.size
- companies(:first_firm).clients_of_firm.delete_all
+ clients = companies(:first_firm).clients_of_firm.to_a
+ assert_equal 2, clients.count
+ deleted = companies(:first_firm).clients_of_firm.delete_all
+ assert_equal clients.sort_by(&:id), deleted.sort_by(&:id)
assert_equal 0, companies(:first_firm).clients_of_firm.size
assert_equal 0, companies(:first_firm).clients_of_firm(true).size
end
@@ -649,11 +690,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
client_id = firm.clients_of_firm.first.id
assert_equal 1, firm.clients_of_firm.size
- firm.clients_of_firm.clear
+ cleared = firm.clients_of_firm.clear
assert_equal 0, firm.clients_of_firm.size
assert_equal 0, firm.clients_of_firm(true).size
assert_equal [], Client.destroyed_client_ids[firm.id]
+ assert_equal firm.clients_of_firm.object_id, cleared.object_id
# Should not be destroyed since the association is not dependent.
assert_nothing_raised do
@@ -664,9 +706,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_clearing_updates_counter_cache
topic = Topic.first
- topic.replies.clear
- topic.reload
- assert_equal 0, topic.replies_count
+ assert_difference 'topic.reload.replies_count', -1 do
+ topic.replies.clear
+ end
end
def test_clearing_a_dependent_association_collection
@@ -963,6 +1005,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !firm.clients.include?(:first_client)
end
+ def test_replace_failure
+ firm = companies(:first_firm)
+ account = Account.new
+ orig_accounts = firm.accounts.to_a
+
+ assert !account.valid?
+ assert !orig_accounts.empty?
+ assert_raise ActiveRecord::RecordNotSaved do
+ firm.accounts = [account]
+ end
+ assert_equal orig_accounts, firm.accounts
+ end
+
def test_get_ids
assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids
end
@@ -1302,4 +1357,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal reply.id, first.id
assert_equal true, first.approved?
end
+
+ def test_to_a_should_dup_target
+ ary = topics(:first).replies.to_a
+ target = topics(:first).replies.target
+
+ assert_not_equal target.object_id, ary.object_id
+ 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 5fac52257c..9adaebe924 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -20,12 +20,15 @@ require 'models/subscription'
require 'models/essay'
require 'models/category'
require 'models/owner'
+require 'models/categorization'
+require 'models/member'
+require 'models/membership'
+require 'models/club'
class HasManyThroughAssociationsTest < ActiveRecord::TestCase
- fixtures :posts, :readers, :people, :comments, :authors,
- :owners, :pets, :toys, :jobs, :references, :companies,
- :subscribers, :books, :subscriptions, :developers,
- :essays, :categories, :owners
+ fixtures :posts, :readers, :people, :comments, :authors, :categories, :taggings, :tags,
+ :owners, :pets, :toys, :jobs, :references, :companies, :members, :author_addresses,
+ :subscribers, :books, :subscriptions, :developers, :categorizations, :essays
# Dummies to force column loads so query counts are clean.
def setup
@@ -33,6 +36,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
Reader.create :person_id => 0, :post_id => 0
end
+ def test_include?
+ person = Person.new
+ post = Post.new
+ person.posts << post
+ assert person.posts.include?(post)
+ end
+
def test_associate_existing
assert_queries(2) { posts(:thinking); people(:david) }
@@ -47,6 +57,16 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert posts(:thinking).reload.people(true).include?(people(:david))
end
+ def test_associate_existing_record_twice_should_add_to_target_twice
+ post = posts(:thinking)
+ person = people(:david)
+
+ assert_difference 'post.people.to_a.count', 2 do
+ post.people << person
+ post.people << person
+ end
+ end
+
def test_associating_new
assert_queries(1) { posts(:thinking) }
new_person = nil # so block binding catches it
@@ -94,6 +114,24 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Ted")
end
+ def test_build_then_save_with_has_many_inverse
+ post = posts(:thinking)
+ person = post.people.build(:first_name => "Bob")
+ person.save
+ post.reload
+
+ assert post.people.include?(person)
+ end
+
+ def test_build_then_save_with_has_one_inverse
+ post = posts(:thinking)
+ person = post.single_people.build(:first_name => "Bob")
+ person.save
+ post.reload
+
+ assert post.single_people.include?(person)
+ end
+
def test_delete_association
assert_queries(2){posts(:welcome);people(:michael); }
@@ -109,8 +147,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_destroy_association
- assert_difference ["Person.count", "Reader.count"], -1 do
- posts(:welcome).people.destroy(people(:michael))
+ assert_no_difference "Person.count" do
+ assert_difference "Reader.count", -1 do
+ posts(:welcome).people.destroy(people(:michael))
+ end
end
assert posts(:welcome).reload.people.empty?
@@ -118,8 +158,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_destroy_all
- assert_difference ["Person.count", "Reader.count"], -1 do
- posts(:welcome).people.destroy_all
+ assert_no_difference "Person.count" do
+ assert_difference "Reader.count", -1 do
+ posts(:welcome).people.destroy_all
+ end
end
assert posts(:welcome).reload.people.empty?
@@ -132,6 +174,137 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_delete_through_belongs_to_with_dependent_nullify
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+ reference = Reference.where(:job_id => job.id, :person_id => person.id).first
+
+ assert_no_difference ['Job.count', 'Reference.count'] do
+ assert_difference 'person.jobs.count', -1 do
+ person.jobs_with_dependent_nullify.delete(job)
+ end
+ end
+
+ assert_equal nil, reference.reload.job_id
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_delete_through_belongs_to_with_dependent_delete_all
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+
+ # Make sure we're not deleting everything
+ assert person.jobs.count >= 2
+
+ assert_no_difference 'Job.count' do
+ assert_difference ['person.jobs.count', 'Reference.count'], -1 do
+ person.jobs_with_dependent_delete_all.delete(job)
+ end
+ end
+
+ # Check that the destroy callback on Reference did not run
+ assert_equal nil, person.reload.comments
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_delete_through_belongs_to_with_dependent_destroy
+ Reference.make_comments = true
+
+ person = people(:michael)
+ job = jobs(:magician)
+
+ # Make sure we're not deleting everything
+ assert person.jobs.count >= 2
+
+ assert_no_difference 'Job.count' do
+ assert_difference ['person.jobs.count', 'Reference.count'], -1 do
+ person.jobs_with_dependent_destroy.delete(job)
+ end
+ end
+
+ # Check that the destroy callback on Reference ran
+ assert_equal "Reference destroyed", person.reload.comments
+ ensure
+ Reference.make_comments = false
+ end
+
+ def test_belongs_to_with_dependent_destroy
+ person = PersonWithDependentDestroyJobs.find(1)
+
+ # Create a reference which is not linked to a job. This should not be destroyed.
+ person.references.create!
+
+ assert_no_difference 'Job.count' do
+ assert_difference 'Reference.count', -person.jobs.count do
+ person.destroy
+ end
+ end
+ end
+
+ def test_belongs_to_with_dependent_delete_all
+ person = PersonWithDependentDeleteAllJobs.find(1)
+
+ # Create a reference which is not linked to a job. This should not be destroyed.
+ person.references.create!
+
+ assert_no_difference 'Job.count' do
+ assert_difference 'Reference.count', -person.jobs.count do
+ person.destroy
+ end
+ end
+ end
+
+ def test_belongs_to_with_dependent_nullify
+ person = PersonWithDependentNullifyJobs.find(1)
+
+ references = person.references.to_a
+
+ assert_no_difference ['Reference.count', 'Job.count'] do
+ person.destroy
+ end
+
+ references.each do |reference|
+ assert_equal nil, reference.reload.job_id
+ end
+ end
+
+ def test_update_counter_caches_on_delete
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+
+ assert_difference ['post.reload.taggings_count', 'post.reload.tags_count'], -1 do
+ posts(:welcome).tags.delete(tag)
+ end
+ end
+
+ def test_update_counter_caches_on_delete_with_dependent_destroy
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ post.update_attribute(: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)
+ end
+ end
+
+ def test_update_counter_caches_on_delete_with_dependent_nullify
+ post = posts(:welcome)
+ tag = post.tags.create!(:name => 'doomed')
+ post.update_attribute(: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
+ posts(:welcome).tags_with_nullify.delete(tag)
+ end
+ end
+ end
+
def test_replace_association
assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)}
@@ -326,12 +499,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert_equal 2, people(:michael).jobs.size
end
- def test_get_ids_for_belongs_to_source
- assert_sql(/DISTINCT/) { assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort }
- end
-
- def test_get_ids_for_has_many_source
- assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids
+ def test_get_ids
+ assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort
end
def test_get_ids_for_loaded_associations
@@ -392,6 +561,41 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
+ def test_has_many_association_through_a_has_many_association_to_self
+ sarah = Person.create!(:first_name => 'Sarah', :primary_contact_id => people(:susan).id, :gender => 'F', :number1_fan_id => 1)
+ john = Person.create!(:first_name => 'John', :primary_contact_id => sarah.id, :gender => 'M', :number1_fan_id => 1)
+ assert_equal sarah.agents, [john]
+ assert_equal people(:susan).agents.map(&:agents).flatten, people(:susan).agents_of_agents
+ end
+
+ def test_associate_existing_with_nonstandard_primary_key_on_belongs_to
+ Categorization.create(:author => authors(:mary), :named_category_name => categories(:general).name)
+ assert_equal categories(:general), authors(:mary).named_categories.first
+ end
+
+ def test_collection_build_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.build(:name => "Primary")
+ author.save
+ assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).include?(category)
+ end
+
+ def test_collection_create_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.create(:name => "Primary")
+ assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).include?(category)
+ end
+
+ def test_collection_delete_with_nonstandard_primary_key_on_belongs_to
+ author = authors(:mary)
+ category = author.named_categories.create(:name => "Primary")
+ author.named_categories.delete(category)
+ assert !Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
+ assert author.named_categories(true).empty?
+ end
+
def test_collection_singular_ids_getter_with_string_primary_keys
book = books(:awdr)
assert_equal 2, book.subscriber_ids.size
@@ -478,4 +682,88 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
post.people << people(:michael)
assert_equal readers + 1, post.readers.size
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
+ end
+
+ def test_create_has_many_through_with_default_scope_on_join_model
+ category = authors(:david).special_categories.create(:name => "Foo")
+ assert_equal 1, category.categorizations.where(:special => true).count
+ end
+
+ def test_joining_has_many_through_with_uniq
+ mary = Author.joins(:unique_categorized_posts).where(:id => authors(:mary).id).first
+ assert_equal 1, mary.unique_categorized_posts.length
+ assert_equal 1, mary.unique_categorized_post_ids.length
+ end
+
+ def test_joining_has_many_through_belongs_to
+ posts = Post.joins(:author_categorizations).order('posts.id').
+ where('categorizations.id' => categorizations(:mary_thinking_sti).id)
+
+ assert_equal [posts(:eager_other), posts(:misc_by_mary), posts(:other_by_mary)], posts
+ end
+
+ def test_select_chosen_fields_only
+ author = authors(:david)
+ assert_equal ['body'], author.comments.select('comments.body').first.attributes.keys
+ end
+
+ def test_get_has_many_through_belongs_to_ids_with_conditions
+ assert_equal [categories(:general).id], authors(:mary).categories_like_general_ids
+ end
+
+ def test_count_has_many_through_with_named_scope
+ assert_equal 2, authors(:mary).categories.count
+ assert_equal 1, authors(:mary).categories.general.count
+ end
+
+ def test_has_many_through_belongs_to_should_update_when_the_through_foreign_key_changes
+ post = posts(:eager_other)
+
+ post.author_categorizations
+ proxy = post.send(:association_instance_get, :author_categorizations)
+
+ assert !proxy.stale_target?
+ assert_equal authors(:mary).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
+
+ post.author_id = authors(:david).id
+
+ assert proxy.stale_target?
+ assert_equal authors(:david).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id)
+ end
+
+ def test_create_with_conditions_hash_on_through_association
+ member = members(:groucho)
+ club = member.clubs.create!
+
+ assert_equal true, club.reload.membership.favourite
+ end
+
+ def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_counter
+ post = posts(:welcome)
+ address = author_addresses(:david_address)
+
+ assert post.author_addresses.include?(address)
+ post.author_addresses.delete(address)
+ 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)
+ categorization = Categorization.create!(:post_id => post.id, :named_category_name => category.name)
+
+ assert_equal [category], post.named_categories
+ assert_equal [category.name], post.named_category_ids # checks when target loaded
+ assert_equal [category.name], post.reload.named_category_ids # checks when target no loaded
+ end
end
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index 64449df8f5..c1dad5e246 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -2,9 +2,13 @@ require "cases/helper"
require 'models/developer'
require 'models/project'
require 'models/company'
+require 'models/ship'
+require 'models/pirate'
+require 'models/bulb'
class HasOneAssociationsTest < ActiveRecord::TestCase
- fixtures :accounts, :companies, :developers, :projects, :developers_projects
+ self.use_transactional_fixtures = false unless supports_savepoints?
+ fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates
def setup
Account.destroyed_account_ids.clear
@@ -62,11 +66,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { company.account = company.account }
end
- def test_triple_equality
- assert Account === companies(:first_firm).account
- assert companies(:first_firm).account === Account
- end
-
def test_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 }
assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) }
@@ -91,18 +90,18 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_nullification_on_association_change
firm = companies(:rails_core)
old_account_id = firm.account.id
- firm.account = Account.new
+ firm.account = Account.new(:credit_limit => 5)
# account is dependent with nullify, therefore its firm_id should be nil
assert_nil Account.find(old_account_id).firm_id
end
def test_association_change_calls_delete
- companies(:first_firm).deletable_account = Account.new
+ companies(:first_firm).deletable_account = Account.new(:credit_limit => 5)
assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id]
end
def test_association_change_calls_destroy
- companies(:first_firm).account = Account.new
+ companies(:first_firm).account = Account.new(:credit_limit => 5)
assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id]
end
@@ -116,35 +115,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal company.account, account
end
- def test_assignment_without_replacement
- apple = Firm.create("name" => "Apple")
- citibank = Account.create("credit_limit" => 10)
- apple.account = citibank
- assert_equal apple.id, citibank.firm_id
-
- hsbc = apple.build_account({ :credit_limit => 20}, false)
- assert_equal apple.id, hsbc.firm_id
- hsbc.save
- assert_equal apple.id, citibank.firm_id
-
- nykredit = apple.create_account({ :credit_limit => 30}, false)
- assert_equal apple.id, nykredit.firm_id
- assert_equal apple.id, citibank.firm_id
- assert_equal apple.id, hsbc.firm_id
- end
-
- def test_assignment_without_replacement_on_create
- apple = Firm.create("name" => "Apple")
- citibank = Account.create("credit_limit" => 10)
- apple.account = citibank
- assert_equal apple.id, citibank.firm_id
-
- hsbc = apple.create_account({:credit_limit => 10}, false)
- assert_equal apple.id, hsbc.firm_id
- hsbc.save
- assert_equal apple.id, citibank.firm_id
- end
-
def test_dependence
num_accounts = Account.count
@@ -193,13 +163,18 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal account, firm.account
end
- def test_build_association_twice_without_saving_affects_nothing
- count_of_account = Account.count
- firm = Firm.find(:first)
- firm.build_account("credit_limit" => 1000)
- firm.build_account("credit_limit" => 2000)
+ def test_build_and_create_should_not_happen_within_scope
+ pirate = pirates(:blackbeard)
+ original_scoped_methods = Bulb.scoped_methods.dup
- assert_equal count_of_account, Account.count
+ bulb = pirate.build_bulb
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = pirate.create_bulb
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
+
+ bulb = pirate.create_bulb!
+ assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize
end
def test_create_association
@@ -208,25 +183,32 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal account, firm.reload.account
end
- def test_build
- firm = Firm.new("name" => "GlobalMegaCorp")
- firm.save
+ def test_create_association_with_bang
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ account = firm.create_account!(:credit_limit => 1000)
+ assert_equal account, firm.reload.account
+ end
- firm.account = account = Account.new("credit_limit" => 1000)
- assert_equal account, firm.account
- assert account.save
- assert_equal account, firm.account
+ def test_create_association_with_bang_failing
+ firm = Firm.create(:name => "GlobalMegaCorp")
+ assert_raise ActiveRecord::RecordInvalid do
+ firm.create_account!
+ end
+ account = firm.account
+ assert_not_nil account
+ account.credit_limit = 5
+ account.save
+ assert_equal account, firm.reload.account
end
- def test_failing_build_association
+ def test_build
firm = Firm.new("name" => "GlobalMegaCorp")
firm.save
- firm.account = account = Account.new
+ firm.account = account = Account.new("credit_limit" => 1000)
assert_equal account, firm.account
- assert !account.save
+ assert account.save
assert_equal account, firm.account
- assert_equal ["can't be empty"], account.errors["credit_limit"]
end
def test_create
@@ -330,4 +312,51 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
new_account = companies(:first_firm).build_account(:firm_name => 'Account')
assert_equal new_account.firm_name, "Account"
end
+
+ def test_creation_failure_without_dependent_option
+ pirate = pirates(:blackbeard)
+ orig_ship = pirate.ship
+
+ assert_equal ships(:black_pearl), orig_ship
+ new_ship = pirate.create_ship
+ assert_not_equal ships(:black_pearl), new_ship
+ assert_equal new_ship, pirate.ship
+ assert new_ship.new_record?
+ assert_nil orig_ship.pirate_id
+ assert !orig_ship.changed? # check it was saved
+ end
+
+ def test_creation_failure_with_dependent_option
+ pirate = pirates(:blackbeard).becomes(DestructivePirate)
+ orig_ship = pirate.dependent_ship
+
+ new_ship = pirate.create_dependent_ship
+ assert new_ship.new_record?
+ assert orig_ship.destroyed?
+ end
+
+ def test_replacement_failure_due_to_existing_record_should_raise_error
+ pirate = pirates(:blackbeard)
+ pirate.ship.name = nil
+
+ assert !pirate.ship.valid?
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = ships(:interceptor)
+ end
+ assert_equal ships(:black_pearl), pirate.ship
+ assert_equal pirate.id, pirate.ship.pirate_id
+ end
+
+ def test_replacement_failure_due_to_new_record_should_raise_error
+ pirate = pirates(:blackbeard)
+ new_ship = Ship.new
+
+ assert_raise(ActiveRecord::RecordNotSaved) do
+ pirate.ship = new_ship
+ end
+ assert_equal ships(:black_pearl), pirate.ship
+ assert_equal pirate.id, pirate.ship.pirate_id
+ assert_equal pirate.id, ships(:black_pearl).reload.pirate_id
+ assert_nil new_ship.pirate_id
+ 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 fc56233ba8..9ba5549277 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -13,10 +13,12 @@ require 'models/category'
require 'models/author'
require 'models/essay'
require 'models/owner'
+require 'models/post'
+require 'models/comment'
class HasOneThroughAssociationsTest < ActiveRecord::TestCase
fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
- :dashboards, :speedometers, :categories, :authors, :essays, :owners
+ :dashboards, :speedometers, :authors, :posts, :comments, :categories, :essays, :owners
def setup
@member = members(:groucho)
@@ -26,10 +28,6 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
assert_equal clubs(:boring_club), @member.club
end
- def test_has_one_through_with_has_many
- assert_equal clubs(:moustache_club), @member.favourite_club
- end
-
def test_creating_association_creates_through_record
new_member = Member.create(:name => "Chris")
new_member.club = Club.create(:name => "LRUG")
@@ -89,6 +87,18 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
assert_not_nil assert_no_queries {members[0].sponsor_club}
end
+ def test_has_one_through_with_conditions_eager_loading
+ # conditions on the through table
+ assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :favourite_club).favourite_club
+ memberships(:membership_of_favourite_club).update_attribute(:favourite, false)
+ assert_equal nil, Member.find(@member.id, :include => :favourite_club).reload.favourite_club
+
+ # conditions on the source table
+ assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :hairy_club).hairy_club
+ clubs(:moustache_club).update_attribute(:name, "Association of Clean-Shaven Persons")
+ assert_equal nil, Member.find(@member.id, :include => :hairy_club).reload.hairy_club
+ end
+
def test_has_one_through_polymorphic_with_source_type
assert_equal members(:groucho), clubs(:moustache_club).sponsored_member
end
@@ -132,7 +142,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_assigning_association_correctly_assigns_target
new_member = Member.create(:name => "Chris")
new_member.club = new_club = Club.create(:name => "LRUG")
- assert_equal new_club, new_member.club.target
+ assert_equal new_club, new_member.association(:club).target
end
def test_has_one_through_proxy_should_not_respond_to_private_methods
@@ -190,7 +200,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
MemberDetail.find(:all, :include => :member_type)
end
@new_detail = @member_details[0]
- assert @new_detail.loaded_member_type?
+ assert @new_detail.send(:association, :member_type).loaded?
assert_not_nil assert_no_queries { @new_detail.member_type }
end
@@ -253,4 +263,51 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
authors = Author.joins(:essay_category_2).where('categories.id' => categories(:general).id)
assert_equal authors(:david), authors.first
end
+
+ def test_has_one_through_with_default_scope_on_join_model
+ assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_post
+ end
+
+ def test_has_one_through_many_raises_exception
+ assert_raise(ActiveRecord::HasOneThroughCantAssociateThroughCollection) do
+ members(:groucho).club_through_many
+ end
+ end
+
+ def test_has_one_through_belongs_to_should_update_when_the_through_foreign_key_changes
+ minivan = minivans(:cool_first)
+
+ minivan.dashboard
+ proxy = minivan.send(:association_instance_get, :dashboard)
+
+ assert !proxy.stale_target?
+ assert_equal dashboards(:cool_first), minivan.dashboard
+
+ minivan.speedometer_id = speedometers(:second).id
+
+ assert proxy.stale_target?
+ assert_equal dashboards(:second), minivan.dashboard
+ end
+
+ def test_has_one_through_belongs_to_setting_belongs_to_foreign_key_after_nil_target_loaded
+ minivan = Minivan.new
+
+ minivan.dashboard
+ proxy = minivan.send(:association_instance_get, :dashboard)
+
+ minivan.speedometer_id = speedometers(:second).id
+
+ assert proxy.stale_target?
+ assert_equal dashboards(:second), minivan.dashboard
+ end
+
+ def test_assigning_has_one_through_belongs_to_with_new_record_owner
+ minivan = Minivan.new
+ dashboard = dashboards(:cool_first)
+
+ minivan.dashboard = dashboard
+
+ assert_equal dashboard, minivan.dashboard
+ assert_equal dashboard, minivan.speedometer.dashboard
+ end
end
diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb
new file mode 100644
index 0000000000..9b8635774c
--- /dev/null
+++ b/activerecord/test/cases/associations/identity_map_test.rb
@@ -0,0 +1,137 @@
+require "cases/helper"
+require 'models/author'
+require 'models/post'
+
+if ActiveRecord::IdentityMap.enabled?
+class InverseHasManyIdentityMapTest < ActiveRecord::TestCase
+ fixtures :authors, :posts
+
+ def test_parent_instance_should_be_shared_with_every_child_on_find
+ m = Author.first
+ is = m.posts
+ is.each do |i|
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance"
+ end
+ end
+
+ def test_parent_instance_should_be_shared_with_eager_loaded_children
+ m = Author.find(:first, :include => :posts)
+ is = m.posts
+ is.each do |i|
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance"
+ end
+
+ m = Author.find(:first, :include => :posts, :order => 'posts.id')
+ is = m.posts
+ is.each do |i|
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance"
+ end
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_built_child
+ m = Author.first
+ i = m.posts.build(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_built_child
+ m = Author.first
+ i = m.posts.build {|ii| ii.title = 'Industrial Revolution Re-enactment'; ii.body = 'Lorem ipsum'}
+ assert_not_nil i.title, "Child attributes supplied to build via blocks should be populated"
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to just-built-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_child
+ m = Author.first
+ i = m.posts.create(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child
+ m = Author.first
+ i = m.posts.create!(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_newly_block_style_created_child
+ m = Author.first
+ i = m.posts.create {|ii| ii.title = 'Industrial Revolution Re-enactment'; ii.body = 'Lorem ipsum'}
+ assert_not_nil i.title, "Child attributes supplied to create via blocks should be populated"
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_poked_in_child
+ m = Author.first
+ i = Post.create(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ m.posts << i
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_accessor_children
+ m = Author.first
+ i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ m.posts = [i]
+ assert_same m, i.author
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+
+ def test_parent_instance_should_be_shared_with_replaced_via_method_children
+ m = Author.first
+ i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum')
+ m.posts = [i]
+ assert_not_nil i.author
+ assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance"
+ m.name = 'Bongo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance"
+ i.author.name = 'Mungo'
+ assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance"
+ end
+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 780eabc443..e2228228a3 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -4,6 +4,7 @@ require 'models/comment'
require 'models/author'
require 'models/category'
require 'models/categorization'
+require 'models/person'
require 'models/tagging'
require 'models/tag'
@@ -16,6 +17,13 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
assert_equal authors(:david), result.first
end
+ def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations
+ assert_nothing_raised do
+ sql = Person.joins(:agents => {:agents => :agents}).joins(:agents => {:agents => {:primary_contact => :agents}}).to_sql
+ assert_match(/agents_people_4/i, sql)
+ end
+ end
+
def test_construct_finder_sql_ignores_empty_joins_hash
sql = Author.joins({}).to_sql
assert_no_match(/JOIN/i, sql)
@@ -65,21 +73,21 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
authors_with_welcoming_post_titles = Author.calculate(:count, 'authors.id', :joins => :posts, :distinct => true, :conditions => "posts.title like 'Welcome%'")
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
-
+
def test_find_with_sti_join
scope = Post.joins(:special_comments).where(:id => posts(:sti_comments).id)
-
+
# The join should match SpecialComment and its subclasses only
assert scope.where("comments.type" => "Comment").empty?
assert !scope.where("comments.type" => "SpecialComment").empty?
assert !scope.where("comments.type" => "SubSpecialComment").empty?
end
-
+
def test_find_with_conditions_on_reflection
assert !posts(:welcome).comments.empty?
assert Post.joins(:nonexistant_comments).where(:id => posts(:welcome).id).empty? # [sic!]
end
-
+
def test_find_with_conditions_on_through_reflection
assert !posts(:welcome).tags.empty?
assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty?
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index 0491b2d1fa..76282213d8 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -114,7 +114,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_newly_built_child
- m = men(:gordon)
+ m = Man.find(:first)
f = m.build_face(:description => 'haunted')
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
@@ -125,7 +125,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_newly_created_child
- m = men(:gordon)
+ m = Man.find(:first)
f = m.create_face(:description => 'haunted')
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
@@ -137,40 +137,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method
m = Man.find(:first)
- f = m.face.create!(:description => 'haunted')
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_newly_built_child_when_we_dont_replace_existing
- m = Man.find(:first)
- f = m.build_face({:description => 'haunted'}, false)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_newly_created_child_when_we_dont_replace_existing
- m = Man.find(:first)
- f = m.create_face({:description => 'haunted'}, false)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
- end
-
- def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method_when_we_dont_replace_existing
- m = Man.find(:first)
- f = m.face.create!({:description => 'haunted'}, false)
+ f = m.create_face!(:description => 'haunted')
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -191,30 +158,6 @@ class InverseHasOneTests < ActiveRecord::TestCase
assert_equal m.name, f.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_replaced_via_method_child
- m = Man.find(:first)
- f = Face.new(:description => 'haunted')
- m.face.replace(f)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.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_replaced_via_method_child_when_we_dont_replace_existing
- m = Man.find(:first)
- f = Face.new(:description => 'haunted')
- m.face.replace(f, false)
- assert_not_nil f.man
- assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
- f.man.name = 'Mungo'
- assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
- end
-
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).dirty_face }
end
@@ -257,17 +200,6 @@ class InverseHasManyTests < ActiveRecord::TestCase
end
end
- def test_parent_instance_should_be_shared_with_newly_built_child
- m = men(:gordon)
- i = m.interests.build(:topic => 'Industrial Revolution Re-enactment')
- assert_not_nil i.man
- assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
- i.man.name = 'Mungo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
- end
-
def test_parent_instance_should_be_shared_with_newly_block_style_built_child
m = Man.find(:first)
i = m.interests.build {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
@@ -280,17 +212,6 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
end
- def test_parent_instance_should_be_shared_with_newly_created_child
- m = men(:gordon)
- i = m.interests.create(:topic => 'Industrial Revolution Re-enactment')
- assert_not_nil i.man
- assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
- i.man.name = 'Mungo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
- end
-
def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child
m = Man.find(:first)
i = m.interests.create!(:topic => 'Industrial Revolution Re-enactment')
@@ -338,18 +259,6 @@ 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_replaced_via_method_children
- m = Man.find(:first)
- i = Interest.new(:topic => 'Industrial Revolution Re-enactment')
- m.interests.replace([i])
- assert_not_nil i.man
- assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
- m.name = 'Bongo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
- i.man.name = 'Mungo'
- assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
- end
-
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).secret_interests }
end
@@ -433,19 +342,6 @@ class InverseBelongsToTests < ActiveRecord::TestCase
assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end
- def test_child_instance_should_be_shared_with_replaced_via_method_parent
- f = faces(:trusting)
- assert_not_nil f.man
- m = Man.new(:name => 'Charles')
- f.man.replace(m)
- assert_not_nil m.face
- assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
- f.description = 'gormless'
- assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
- m.face.description = 'pleasing'
- assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
- end
-
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).horrible_man }
end
@@ -501,7 +397,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
new_man = Man.new
assert_not_nil face.polymorphic_man
- face.polymorphic_man.replace(new_man)
+ face.polymorphic_man = new_man
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
face.description = 'Bongo'
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 2aac95a25d..543eff7d8b 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -13,7 +13,8 @@ require 'models/book'
require 'models/citation'
class AssociationsJoinModelTest < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
+
fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books,
# Reload edges table from fixtures as otherwise repeated test was failing
:edges
@@ -85,16 +86,9 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
end
- def test_polymorphic_has_many_going_through_join_model_with_disabled_include
- assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
- assert_queries 1 do
- tag.tagging
- end
- end
-
def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
- tag.author_id
+ assert_nothing_raised(NoMethodError) { tag.author_id }
end
def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
@@ -159,7 +153,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_create_polymorphic_has_one_with_scope
old_count = Tagging.count
- tagging = posts(:welcome).tagging.create(:tag => tags(:misc))
+ tagging = posts(:welcome).create_tagging(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, Tagging.count
end
@@ -220,7 +214,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_with_piggyback
- assert_equal "2", categories(:sti_test).authors.first.post_id.to_s
+ assert_equal "2", categories(:sti_test).authors_with_select.first.post_id.to_s
end
def test_include_has_many_through
@@ -298,6 +292,22 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert_equal [authors(:mary)], posts(:authorless).authors
end
+ def test_has_many_going_through_join_model_with_custom_primary_key
+ assert_equal [authors(:david)], posts(:thinking).authors_using_author_id
+ end
+
+ def test_has_many_going_through_polymorphic_join_model_with_custom_primary_key
+ assert_equal [tags(:general)], posts(:eager_other).tags_using_author_id
+ end
+
+ def test_has_many_through_with_custom_primary_key_on_belongs_to_source
+ assert_equal [authors(:david), authors(:david)], posts(:thinking).author_using_custom_pk
+ end
+
+ def test_has_many_through_with_custom_primary_key_on_has_many_source
+ assert_equal [authors(:david), authors(:bob)], posts(:thinking).authors_using_custom_pk.order(:id)
+ end
+
def test_both_scoped_and_explicit_joins_should_be_respected
assert_nothing_raised do
Post.send(:with_scope, :find => {:joins => "left outer join comments on comments.id = posts.id"}) do
@@ -324,11 +334,16 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_polymorphic
- assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicError do
- assert_equal posts(:welcome, :thinking), tags(:general).taggables
+ assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicSourceError do
+ tags(:general).taggables
+ end
+
+ assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicThroughError do
+ taggings(:welcome_general).things
end
+
assert_raise ActiveRecord::EagerLoadPolymorphicError do
- assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1')
+ tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1')
end
end
@@ -488,6 +503,10 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
end
+ def test_add_to_join_table_with_no_id
+ assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
+ end
+
def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
author = authors(:david)
assert_equal 10, author.comments.size
@@ -496,7 +515,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
author = authors(:david)
- author.stubs(:read_attribute).with('comments_count').returns(100)
+ author.stubs(:_read_attribute).with('comments_count').returns(100)
assert_equal 100, author.comments.size
assert !author.comments.loaded?
end
diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb
index db7c8b6c45..a4ac69782a 100644
--- a/activerecord/test/cases/associations/nested_through_associations_test.rb
+++ b/activerecord/test/cases/associations/nested_through_associations_test.rb
@@ -51,9 +51,19 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
# Through: has_many
def test_has_many_through_has_many_with_has_many_through_source_reflection
general = tags(:general)
-
assert_equal [general, general], authors(:david).tags
+ end
+
+ def test_has_many_through_has_many_with_has_many_through_source_reflection_preload
+ authors = assert_queries(5) { Author.includes(:tags).to_a }
+ general = tags(:general)
+
+ assert_no_queries do
+ assert_equal [general, general], authors.first.tags
+ end
+ end
+ def test_has_many_through_has_many_with_has_many_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Author.where('tags.id' => tags(:general).id),
[authors(:david)], :tags
@@ -62,11 +72,6 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
# This ensures that the polymorphism of taggings is being observed correctly
authors = Author.joins(:tags).where('taggings.taggable_type' => 'FakeModel')
assert authors.empty?
-
- authors = assert_queries(5) { Author.includes(:tags).to_a }
- assert_no_queries do
- assert_equal [general, general], authors.first.tags
- end
end
# has_many through
@@ -74,60 +79,69 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
# Through: has_many through
def test_has_many_through_has_many_through_with_has_many_source_reflection
luke, david = subscribers(:first), subscribers(:second)
+ assert_equal [luke, david, david], authors(:david).subscribers.order('subscribers.nick')
+ end
- author = authors(:david)
- assert_equal [luke, david, david], author.subscribers.order('subscribers.nick')
+ def test_has_many_through_has_many_through_with_has_many_source_reflection_preload
+ luke, david = subscribers(:first), subscribers(:second)
+ authors = assert_queries(4) { Author.includes(:subscribers).to_a }
+ assert_no_queries do
+ assert_equal [luke, david, david], authors.first.subscribers.sort_by(&:nick)
+ end
+ end
+ def test_has_many_through_has_many_through_with_has_many_source_reflection_preload_via_joins
# All authors with subscribers where one of the subscribers' nick is 'alterself'
assert_includes_and_joins_equal(
Author.where('subscribers.nick' => 'alterself'),
[authors(:david)], :subscribers
)
-
- authors = assert_queries(4) { Author.includes(:subscribers).to_a }
- assert_no_queries do
- assert_equal [luke, david, david], authors.first.subscribers.sort_by(&:nick)
- end
end
# has_many through
# Source: has_one through
# Through: has_one
def test_has_many_through_has_one_with_has_one_through_source_reflection
- founding = member_types(:founding)
-
- assert_equal [founding], members(:groucho).nested_member_types
-
- assert_includes_and_joins_equal(
- Member.where('member_types.id' => founding.id),
- [members(:groucho)], :nested_member_types
- )
+ assert_equal [member_types(:founding)], members(:groucho).nested_member_types
+ end
+ def test_has_many_through_has_one_with_has_one_through_source_reflection_preload
members = assert_queries(4) { Member.includes(:nested_member_types).to_a }
+ founding = member_types(:founding)
assert_no_queries do
assert_equal [founding], members.first.nested_member_types
end
end
+ def test_has_many_through_has_one_with_has_one_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('member_types.id' => member_types(:founding).id),
+ [members(:groucho)], :nested_member_types
+ )
+ end
+
# has_many through
# Source: has_one
# Through: has_one through
def test_has_many_through_has_one_through_with_has_one_source_reflection
- mustache = sponsors(:moustache_club_sponsor_for_groucho)
-
- assert_equal [mustache], members(:groucho).nested_sponsors
-
- assert_includes_and_joins_equal(
- Member.where('sponsors.id' => mustache.id),
- [members(:groucho)], :nested_sponsors
- )
+ assert_equal [sponsors(:moustache_club_sponsor_for_groucho)], members(:groucho).nested_sponsors
+ end
+ def test_has_many_through_has_one_through_with_has_one_source_reflection_preload
members = assert_queries(4) { Member.includes(:nested_sponsors).to_a }
+ mustache = sponsors(:moustache_club_sponsor_for_groucho)
assert_no_queries do
assert_equal [mustache], members.first.nested_sponsors
end
end
+ def test_has_many_through_has_one_through_with_has_one_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Member.where('sponsors.id' => sponsors(:moustache_club_sponsor_for_groucho).id),
+ [members(:groucho)], :nested_sponsors
+ )
+ end
+
# has_many through
# Source: has_many through
# Through: has_one
@@ -136,7 +150,18 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
assert_equal [groucho_details, other_details],
members(:groucho).organization_member_details.order('member_details.id')
+ end
+
+ def test_has_many_through_has_one_with_has_many_through_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:organization_member_details).to_a.sort_by(&:id) }
+ groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
+
+ assert_no_queries do
+ assert_equal [groucho_details, other_details], members.first.organization_member_details.sort_by(&:id)
+ end
+ end
+ def test_has_many_through_has_one_with_has_many_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('member_details.id' => member_details(:groucho).id).order('member_details.id'),
[members(:groucho), members(:some_other_guy)], :organization_member_details
@@ -145,11 +170,6 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
members = Member.joins(:organization_member_details).
where('member_details.id' => 9)
assert members.empty?
-
- members = assert_queries(4) { Member.includes(:organization_member_details).to_a.sort_by(&:id) }
- assert_no_queries do
- assert_equal [groucho_details, other_details], members.first.organization_member_details.sort_by(&:id)
- end
end
# has_many through
@@ -160,20 +180,26 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
assert_equal [groucho_details, other_details],
members(:groucho).organization_member_details_2.order('member_details.id')
+ end
+
+ def test_has_many_through_has_one_through_with_has_many_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:organization_member_details_2).to_a.sort_by(&:id) }
+ groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
+ assert_no_queries do
+ assert_equal [groucho_details, other_details], members.first.organization_member_details_2.sort_by(&:id)
+ end
+ end
+
+ def test_has_many_through_has_one_through_with_has_many_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
- Member.where('member_details.id' => groucho_details.id).order('member_details.id'),
+ Member.where('member_details.id' => member_details(:groucho).id).order('member_details.id'),
[members(:groucho), members(:some_other_guy)], :organization_member_details_2
)
members = Member.joins(:organization_member_details_2).
where('member_details.id' => 9)
assert members.empty?
-
- members = assert_queries(4) { Member.includes(:organization_member_details_2).to_a.sort_by(&:id) }
- assert_no_queries do
- assert_equal [groucho_details, other_details], members.first.organization_member_details_2.sort_by(&:id)
- end
end
# has_many through
@@ -183,18 +209,24 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
general, cooking = categories(:general), categories(:cooking)
assert_equal [general, cooking], authors(:bob).post_categories.order('categories.id')
+ end
- assert_includes_and_joins_equal(
- Author.where('categories.id' => cooking.id),
- [authors(:bob)], :post_categories
- )
-
+ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection_preload
authors = assert_queries(3) { Author.includes(:post_categories).to_a.sort_by(&:id) }
+ general, cooking = categories(:general), categories(:cooking)
+
assert_no_queries do
assert_equal [general, cooking], authors[2].post_categories.sort_by(&:id)
end
end
+ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Author.where('categories.id' => categories(:cooking).id),
+ [authors(:bob)], :post_categories
+ )
+ end
+
# has_many through
# Source: has_many
# Through: has_and_belongs_to_many
@@ -202,18 +234,24 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
greetings, more = comments(:greetings), comments(:more_greetings)
assert_equal [greetings, more], categories(:technology).post_comments.order('comments.id')
+ end
- assert_includes_and_joins_equal(
- Category.where('comments.id' => more.id).order('comments.id'),
- [categories(:general), categories(:technology)], :post_comments
- )
-
+ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload
categories = assert_queries(3) { Category.includes(:post_comments).to_a.sort_by(&:id) }
+ greetings, more = comments(:greetings), comments(:more_greetings)
+
assert_no_queries do
assert_equal [greetings, more], categories[1].post_comments.sort_by(&:id)
end
end
+ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Category.where('comments.id' => comments(:more_greetings).id).order('comments.id'),
+ [categories(:general), categories(:technology)], :post_comments
+ )
+ end
+
# has_many through
# Source: has_many through a habtm
# Through: has_many through
@@ -221,35 +259,45 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
greetings, more = comments(:greetings), comments(:more_greetings)
assert_equal [greetings, more], authors(:bob).category_post_comments.order('comments.id')
+ end
- assert_includes_and_joins_equal(
- Author.where('comments.id' => comments(:does_it_hurt).id).order('comments.id'),
- [authors(:david), authors(:mary)], :category_post_comments
- )
-
+ def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload
authors = assert_queries(5) { Author.includes(:category_post_comments).to_a.sort_by(&:id) }
+ greetings, more = comments(:greetings), comments(:more_greetings)
+
assert_no_queries do
assert_equal [greetings, more], authors[2].category_post_comments.sort_by(&:id)
end
end
+ def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Author.where('comments.id' => comments(:does_it_hurt).id).order('comments.id'),
+ [authors(:david), authors(:mary)], :category_post_comments
+ )
+ end
+
# has_many through
# Source: belongs_to
# Through: has_many through
def test_has_many_through_has_many_through_with_belongs_to_source_reflection
+ assert_equal [tags(:general), tags(:general)], authors(:david).tagging_tags
+ end
+
+ def test_has_many_through_has_many_through_with_belongs_to_source_reflection_preload
+ authors = assert_queries(5) { Author.includes(:tagging_tags).to_a }
general = tags(:general)
- assert_equal [general, general], authors(:david).tagging_tags
+ assert_no_queries do
+ assert_equal [general, general], authors.first.tagging_tags
+ end
+ end
+ def test_has_many_through_has_many_through_with_belongs_to_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Author.where('tags.id' => tags(:general).id),
[authors(:david)], :tagging_tags
)
-
- authors = assert_queries(5) { Author.includes(:tagging_tags).to_a }
- assert_no_queries do
- assert_equal [general, general], authors.first.tagging_tags
- end
end
# has_many through
@@ -260,54 +308,68 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
assert_equal [welcome_general, thinking_general],
categorizations(:david_welcome_general).post_taggings.order('taggings.id')
+ end
- assert_includes_and_joins_equal(
- Categorization.where('taggings.id' => welcome_general.id).order('taggings.id'),
- [categorizations(:david_welcome_general)], :post_taggings
- )
-
+ def test_has_many_through_belongs_to_with_has_many_through_source_reflection_preload
categorizations = assert_queries(4) { Categorization.includes(:post_taggings).to_a.sort_by(&:id) }
+ welcome_general, thinking_general = taggings(:welcome_general), taggings(:thinking_general)
+
assert_no_queries do
assert_equal [welcome_general, thinking_general], categorizations.first.post_taggings.sort_by(&:id)
end
end
+ def test_has_many_through_belongs_to_with_has_many_through_source_reflection_preload_via_joins
+ assert_includes_and_joins_equal(
+ Categorization.where('taggings.id' => taggings(:welcome_general).id).order('taggings.id'),
+ [categorizations(:david_welcome_general)], :post_taggings
+ )
+ end
+
# has_one through
# Source: has_one through
# Through: has_one
def test_has_one_through_has_one_with_has_one_through_source_reflection
+ assert_equal member_types(:founding), members(:groucho).nested_member_type
+ end
+
+ def test_has_one_through_has_one_with_has_one_through_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:nested_member_type).to_a.sort_by(&:id) }
founding = member_types(:founding)
- assert_equal founding, members(:groucho).nested_member_type
+ assert_no_queries do
+ assert_equal founding, members.first.nested_member_type
+ end
+ end
+ def test_has_one_through_has_one_with_has_one_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
- Member.where('member_types.id' => founding.id),
+ Member.where('member_types.id' => member_types(:founding).id),
[members(:groucho)], :nested_member_type
)
-
- members = assert_queries(4) { Member.includes(:nested_member_type).to_a.sort_by(&:id) }
- assert_no_queries do
- assert_equal founding, members.first.nested_member_type
- end
end
# has_one through
# Source: belongs_to
# Through: has_one through
def test_has_one_through_has_one_through_with_belongs_to_source_reflection
+ assert_equal categories(:general), members(:groucho).club_category
+ end
+
+ def test_has_one_through_has_one_through_with_belongs_to_source_reflection_preload
+ members = assert_queries(4) { Member.includes(:club_category).to_a.sort_by(&:id) }
general = categories(:general)
- assert_equal general, members(:groucho).club_category
+ assert_no_queries do
+ assert_equal general, members.first.club_category
+ end
+ end
+ def test_has_one_through_has_one_through_with_belongs_to_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('categories.id' => categories(:technology).id),
[members(:blarpy_winkup)], :club_category
)
-
- members = assert_queries(4) { Member.includes(:club_category).to_a.sort_by(&:id) }
- assert_no_queries do
- assert_equal general, members.first.club_category
- end
end
def test_distinct_has_many_through_a_has_many_through_association_on_source_reflection
@@ -406,41 +468,49 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
end
def test_nested_has_many_through_with_conditions_on_through_associations
- blue, bob = tags(:blue), authors(:bob)
-
- assert_equal [blue], bob.misc_post_first_blue_tags
-
- # Pointless condition to force single-query loading
- assert_includes_and_joins_equal(
- Author.where('tags.id = tags.id'),
- [bob], :misc_post_first_blue_tags
- )
+ assert_equal [tags(:blue)], authors(:bob).misc_post_first_blue_tags
+ end
+ def test_nested_has_many_through_with_conditions_on_through_associations_preload
assert Author.where('tags.id' => 100).joins(:misc_post_first_blue_tags).empty?
authors = assert_queries(3) { Author.includes(:misc_post_first_blue_tags).to_a.sort_by(&:id) }
+ blue = tags(:blue)
+
assert_no_queries do
assert_equal [blue], authors[2].misc_post_first_blue_tags
end
end
- def test_nested_has_many_through_with_conditions_on_source_associations
- blue, bob = tags(:blue), authors(:bob)
-
- assert_equal [blue], bob.misc_post_first_blue_tags_2
-
+ def test_nested_has_many_through_with_conditions_on_through_associations_preload_via_joins
# Pointless condition to force single-query loading
assert_includes_and_joins_equal(
Author.where('tags.id = tags.id'),
- [bob], :misc_post_first_blue_tags_2
+ [authors(:bob)], :misc_post_first_blue_tags
)
+ end
+
+ def test_nested_has_many_through_with_conditions_on_source_associations
+ assert_equal [tags(:blue)], authors(:bob).misc_post_first_blue_tags_2
+ end
+ def test_nested_has_many_through_with_conditions_on_source_associations_preload
authors = assert_queries(4) { Author.includes(:misc_post_first_blue_tags_2).to_a.sort_by(&:id) }
+ blue = tags(:blue)
+
assert_no_queries do
assert_equal [blue], authors[2].misc_post_first_blue_tags_2
end
end
+ def test_nested_has_many_through_with_conditions_on_source_associations_preload_via_joins
+ # Pointless condition to force single-query loading
+ assert_includes_and_joins_equal(
+ Author.where('tags.id = tags.id'),
+ [authors(:bob)], :misc_post_first_blue_tags_2
+ )
+ end
+
def test_nested_has_many_through_with_foreign_key_option_on_the_source_reflection_through_reflection
assert_equal [categories(:general)], organizations(:nsa).author_essay_categories
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 83c605d2bb..47b8e48582 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -133,25 +133,6 @@ end
class AssociationProxyTest < ActiveRecord::TestCase
fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects
- def test_proxy_accessors
- welcome = posts(:welcome)
- assert_equal welcome, welcome.author.proxy_owner
- assert_equal welcome.class.reflect_on_association(:author), welcome.author.proxy_reflection
- welcome.author.class # force load target
- assert_equal welcome.author, welcome.author.proxy_target
-
- david = authors(:david)
- assert_equal david, david.posts.proxy_owner
- assert_equal david.class.reflect_on_association(:posts), david.posts.proxy_reflection
- david.posts.class # force load target
- assert_equal david.posts, david.posts.proxy_target
-
- assert_equal david, david.posts_with_extension.testing_proxy_owner
- assert_equal david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection
- david.posts_with_extension.class # force load target
- assert_equal david.posts_with_extension, david.posts_with_extension.testing_proxy_target
- end
-
def test_push_does_not_load_target
david = authors(:david)
@@ -216,37 +197,12 @@ class AssociationProxyTest < ActiveRecord::TestCase
assert_equal post.body, "More cool stuff!"
end
- def test_failed_reload_returns_nil
- p = setup_dangling_association
- assert_nil p.author.reload
- end
-
- def test_failed_reset_returns_nil
- p = setup_dangling_association
- assert_nil p.author.reset
- end
-
def test_reload_returns_assocition
david = developers(:david)
assert_nothing_raised do
assert_equal david.projects, david.projects.reload.reload
end
end
-
- if RUBY_VERSION < '1.9'
- def test_splat_does_not_invoke_to_a_on_singular_targets
- author = posts(:welcome).author
- author.reload.target.expects(:to_a).never
- [*author]
- end
- end
-
- def setup_dangling_association
- josh = Author.create(:name => "Josh")
- p = Post.create(:title => "New on Edge", :body => "More cool stuff!", :author => josh)
- josh.destroy
- p
- end
end
class OverridingAssociationsTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb
new file mode 100644
index 0000000000..d0a9028264
--- /dev/null
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -0,0 +1,61 @@
+require "cases/helper"
+
+module ActiveRecord
+ module AttributeMethods
+ class ReadTest < ActiveRecord::TestCase
+ class FakeColumn < Struct.new(:name)
+ def type_cast_code(var)
+ var
+ end
+
+ def type; :integer; end
+ end
+
+ def setup
+ @klass = Class.new do
+ include ActiveRecord::AttributeMethods
+ include ActiveRecord::AttributeMethods::Read
+
+ def self.column_names
+ %w{ one two three }
+ end
+
+ def self.primary_key
+ end
+
+ def self.columns
+ column_names.map { FakeColumn.new(name) }
+ end
+
+ def self.columns_hash
+ Hash[column_names.map { |name|
+ [name, FakeColumn.new(name)]
+ }]
+ end
+
+ def self.serialized_attributes; {}; end
+ end
+ end
+
+ def test_define_attribute_methods
+ instance = @klass.new
+
+ @klass.column_names.each do |name|
+ assert ! instance.methods.map(&:to_s).include?(name)
+ end
+
+ @klass.define_attribute_methods
+
+ @klass.column_names.each do |name|
+ assert(instance.methods.map(&:to_s).include?(name), "#{name} is not defined")
+ end
+ end
+
+ def test_attribute_methods_generated?
+ assert(!@klass.attribute_methods_generated?, 'attribute_methods_generated?')
+ @klass.define_attribute_methods
+ assert(@klass.attribute_methods_generated?, 'attribute_methods_generated?')
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index 8214815bde..dfacf58da8 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -8,6 +8,7 @@ require 'models/topic'
require 'models/company'
require 'models/category'
require 'models/reply'
+require 'models/contact'
class AttributeMethodsTest < ActiveRecord::TestCase
fixtures :topics, :developers, :companies, :computers
@@ -105,7 +106,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def test_read_attributes_before_type_cast
category = Category.new({:name=>"Test categoty", :type => nil})
- category_attrs = {"name"=>"Test categoty", "type" => nil, "categorizations_count" => nil}
+ category_attrs = {"name"=>"Test categoty", "id" => nil, "type" => nil, "categorizations_count" => nil}
assert_equal category_attrs , category.attributes_before_type_cast
end
@@ -116,24 +117,23 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
end
- unless current_adapter?(:Mysql2Adapter)
- def test_read_attributes_before_type_cast_on_datetime
- developer = Developer.find(:first)
- # Oracle adapter returns Time before type cast
- unless current_adapter?(:OracleAdapter)
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s
- else
- assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
+ def test_read_attributes_before_type_cast_on_datetime
+ developer = Developer.find(:first)
+ if current_adapter?(:Mysql2Adapter, :OracleAdapter)
+ # Mysql2 and Oracle adapters keep the value in Time instance
+ assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s(:db)
+ else
+ assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s
+ end
- developer.created_at = "345643456"
- assert_equal developer.created_at_before_type_cast, "345643456"
- assert_equal developer.created_at, nil
+ developer.created_at = "345643456"
- developer.created_at = "2010-03-21 21:23:32"
- assert_equal developer.created_at_before_type_cast.to_s, "2010-03-21 21:23:32"
- assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32")
- end
- end
+ assert_equal developer.created_at_before_type_cast, "345643456"
+ assert_equal developer.created_at, nil
+
+ developer.created_at = "2010-03-21 21:23:32"
+ assert_equal developer.created_at_before_type_cast, "2010-03-21 21:23:32"
+ assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32")
end
def test_hash_content
@@ -247,6 +247,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase
# puts ""
end
+ def test_read_overridden_attribute
+ topic = Topic.new(:title => 'a')
+ def topic.title() 'b' end
+ assert_equal 'a', topic[:title]
+ end
+
def test_query_attribute_string
[nil, "", " "].each do |value|
assert_equal false, Topic.new(:author_name => value).author_name?
@@ -455,6 +461,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
end
+ def test_write_nil_to_time_attributes
+ in_time_zone "Pacific Time (US & Canada)" do
+ record = @target.new
+ record.written_on = nil
+ assert_nil record.written_on
+ end
+ end
+
def test_time_attributes_are_retrieved_in_current_time_zone
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
@@ -596,6 +610,10 @@ 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
private
def cached_columns
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index fbf7121468..8f55b7ebe6 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -21,19 +21,19 @@ require 'models/eye'
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
def test_autosave_should_be_a_valid_option_for_has_one
- assert base.valid_keys_for_has_one_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::HasOne.valid_options.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_belongs_to
- assert base.valid_keys_for_belongs_to_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::BelongsTo.valid_options.include?(:autosave)
end
def test_autosave_should_be_a_valid_option_for_has_many
- assert base.valid_keys_for_has_many_association.include?(:autosave)
+ 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 base.valid_keys_for_has_and_belongs_to_many_association.include?(:autosave)
+ assert ActiveRecord::Associations::Builder::HasAndBelongsToMany.valid_options.include?(:autosave)
end
def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
@@ -90,7 +90,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm = Firm.find(:first)
assert firm.valid?
- firm.account = Account.new
+ firm.build_account
assert !firm.account.valid?
assert !firm.valid?
@@ -102,7 +102,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
firm = Firm.find(:first)
assert firm.valid?
- firm.unvalidated_account = Account.new
+ firm.build_unvalidated_account
assert !firm.unvalidated_account.valid?
assert firm.valid?
@@ -112,7 +112,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
def test_build_before_child_saved
firm = Firm.find(1)
- account = firm.account.build("credit_limit" => 1000)
+ account = firm.build_account("credit_limit" => 1000)
assert_equal account, firm.account
assert !account.persisted?
assert firm.save
@@ -340,6 +340,13 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
tags(:misc).create_tagging(:taggable => posts(:thinking))
assert_equal num_tagging + 1, Tagging.count
end
+
+ def test_build_and_then_save_parent_should_not_reload_target
+ client = Client.find(:first)
+ apple = client.build_firm(:name => "Apple")
+ client.save!
+ assert_no_queries { assert_equal apple, client.firm }
+ end
end
class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
@@ -565,7 +572,7 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
end
class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -578,7 +585,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
@pirate.ship.mark_for_destruction
assert !@pirate.reload.marked_for_destruction?
- assert !@pirate.ship.marked_for_destruction?
+ assert !@pirate.ship.reload.marked_for_destruction?
end
# has_one
@@ -667,119 +674,227 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
end
end
+ @ship.pirate.catchphrase = "Changed Catchphrase"
+
assert_raise(RuntimeError) { assert !@ship.save }
assert_not_nil @ship.reload.pirate
end
- # has_many & has_and_belongs_to
- %w{ parrots birds }.each do |association_name|
- define_method("test_should_destroy_#{association_name}_as_part_of_the_save_transaction_if_they_were_marked_for_destroyal") do
- 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
+ def test_should_save_changed_child_objects_if_parent_is_saved
+ @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ @parrot = @pirate.parrots.create!(:name => 'Posideons Killer')
+ @parrot.name = "NewName"
+ @ship.save
+
+ assert_equal 'NewName', @parrot.reload.name
+ end
+
+ def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
+ 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
- assert !@pirate.send(association_name).any? { |child| child.marked_for_destruction? }
+ assert !@pirate.birds.any? { |child| child.marked_for_destruction? }
- @pirate.send(association_name).each { |child| child.mark_for_destruction }
- klass = @pirate.send(association_name).first.class
- ids = @pirate.send(association_name).map(&:id)
+ @pirate.birds.each { |child| child.mark_for_destruction }
+ klass = @pirate.birds.first.class
+ ids = @pirate.birds.map(&:id)
- assert @pirate.send(association_name).all? { |child| child.marked_for_destruction? }
- ids.each { |id| assert klass.find_by_id(id) }
+ assert @pirate.birds.all? { |child| child.marked_for_destruction? }
+ ids.each { |id| assert klass.find_by_id(id) }
- @pirate.save
- assert @pirate.reload.send(association_name).empty?
- ids.each { |id| assert_nil klass.find_by_id(id) }
+ @pirate.save
+ assert @pirate.reload.birds.empty?
+ ids.each { |id| assert_nil klass.find_by_id(id) }
+ end
+
+ def test_should_skip_validation_on_has_many_if_marked_for_destruction
+ 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
+
+ @pirate.birds.each { |bird| bird.name = '' }
+ assert !@pirate.valid?
+
+ @pirate.birds.each do |bird|
+ bird.mark_for_destruction
+ bird.expects(:valid?).never
end
+ assert_difference("Bird.count", -2) { @pirate.save! }
+ end
- define_method("test_should_skip_validation_on_the_#{association_name}_association_if_marked_for_destruction") do
- 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
- children = @pirate.send(association_name)
+ def test_should_skip_validation_on_has_many_if_destroyed
+ @pirate.birds.create!(:name => "birds_1")
- children.each { |child| child.name = '' }
- assert !@pirate.valid?
+ @pirate.birds.each { |bird| bird.name = '' }
+ assert !@pirate.valid?
- children.each do |child|
- child.mark_for_destruction
- child.expects(:valid?).never
+ @pirate.birds.each { |bird| bird.destroy }
+ assert @pirate.valid?
+ end
+
+ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many
+ @pirate.birds.create!(:name => "birds_1")
+
+ @pirate.birds.each { |bird| bird.mark_for_destruction }
+ assert @pirate.save
+
+ @pirate.birds.each { |bird| bird.expects(:destroy).never }
+ assert @pirate.save
+ end
+
+ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_many
+ 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
+ before = @pirate.birds.map { |c| c.mark_for_destruction ; c }
+
+ # Stub the destroy method of the second child to raise an exception
+ class << before.last
+ def destroy(*args)
+ super
+ raise 'Oh noes!'
end
- assert_difference("#{association_name.classify}.count", -2) { @pirate.save! }
end
- define_method("test_should_skip_validation_on_the_#{association_name}_association_if_destroyed") do
- @pirate.send(association_name).create!(:name => "#{association_name}_1")
- children = @pirate.send(association_name)
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, @pirate.reload.birds
+ end
+
+ # Add and remove callbacks tests for association collections.
+ %w{ method proc }.each do |callback_type|
+ define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do
+ association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
+
+ pirate = Pirate.new(:catchphrase => "Arr")
+ pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
- children.each { |child| child.name = '' }
- assert !@pirate.valid?
+ expected = [
+ "before_adding_#{callback_type}_bird_<new>",
+ "after_adding_#{callback_type}_bird_<new>"
+ ]
- children.each { |child| child.destroy }
- assert @pirate.valid?
+ assert_equal expected, pirate.ship_log
end
- define_method("test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_#{association_name}") do
- @pirate.send(association_name).create!(:name => "#{association_name}_1")
- children = @pirate.send(association_name)
+ define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do
+ association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
- children.each { |child| child.mark_for_destruction }
- assert @pirate.save
- children.each { |child| child.expects(:destroy).never }
- assert @pirate.save
+ @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
+ @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ child_id = @pirate.send(association_name_with_callbacks).first.id
+
+ @pirate.ship_log.clear
+ @pirate.save
+
+ expected = [
+ "before_removing_#{callback_type}_bird_#{child_id}",
+ "after_removing_#{callback_type}_bird_#{child_id}"
+ ]
+
+ assert_equal expected, @pirate.ship_log
end
+ end
- define_method("test_should_rollback_destructions_if_an_exception_occurred_while_saving_#{association_name}") do
- 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") }
- before = @pirate.send(association_name).map { |c| c.mark_for_destruction ; c }
+ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
- # Stub the destroy method of the the second child to raise an exception
- class << before.last
- def destroy(*args)
- super
- raise 'Oh noes!'
- end
- end
+ assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? }
+ @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
- assert_raise(RuntimeError) { assert !@pirate.save }
- assert_equal before, @pirate.reload.send(association_name)
+ assert_no_difference "Parrot.count" do
+ @pirate.save
end
- # Add and remove callbacks tests for association collections.
- %w{ method proc }.each do |callback_type|
- define_method("test_should_run_add_callback_#{callback_type}s_for_#{association_name}") do
- association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks"
+ assert @pirate.reload.parrots.empty?
- pirate = Pirate.new(:catchphrase => "Arr")
- pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
+ join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}")
+ assert join_records.empty?
+ end
- expected = [
- "before_adding_#{callback_type}_#{association_name.singularize}_<new>",
- "after_adding_#{callback_type}_#{association_name.singularize}_<new>"
- ]
+ def test_should_skip_validation_on_habtm_if_marked_for_destruction
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
- assert_equal expected, pirate.ship_log
- end
+ @pirate.parrots.each { |parrot| parrot.name = '' }
+ assert !@pirate.valid?
+
+ @pirate.parrots.each do |parrot|
+ parrot.mark_for_destruction
+ parrot.expects(:valid?).never
+ end
+
+ @pirate.save!
+ assert @pirate.reload.parrots.empty?
+ end
+
+ def test_should_skip_validation_on_habtm_if_destroyed
+ @pirate.parrots.create!(:name => "parrots_1")
- define_method("test_should_run_remove_callback_#{callback_type}s_for_#{association_name}") do
- association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks"
+ @pirate.parrots.each { |parrot| parrot.name = '' }
+ assert !@pirate.valid?
- @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
- @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
- child_id = @pirate.send(association_name_with_callbacks).first.id
+ @pirate.parrots.each { |parrot| parrot.destroy }
+ assert @pirate.valid?
+ end
- @pirate.ship_log.clear
- @pirate.save
+ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
+ @pirate.parrots.create!(:name => "parrots_1")
+
+ @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
+ assert @pirate.save
+
+ assert_no_queries do
+ assert @pirate.save
+ end
+ end
- expected = [
- "before_removing_#{callback_type}_#{association_name.singularize}_#{child_id}",
- "after_removing_#{callback_type}_#{association_name.singularize}_#{child_id}"
- ]
+ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habtm
+ 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
+ before = @pirate.parrots.map { |c| c.mark_for_destruction ; c }
- assert_equal expected, @pirate.ship_log
+ class << @pirate.parrots
+ def destroy(*args)
+ super
+ raise 'Oh noes!'
end
end
+
+ assert_raise(RuntimeError) { assert !@pirate.save }
+ assert_equal before, @pirate.reload.parrots
+ end
+
+ # Add and remove callbacks tests for association collections.
+ %w{ method proc }.each do |callback_type|
+ define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do
+ association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
+
+ pirate = Pirate.new(:catchphrase => "Arr")
+ pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
+
+ expected = [
+ "before_adding_#{callback_type}_parrot_<new>",
+ "after_adding_#{callback_type}_parrot_<new>"
+ ]
+
+ assert_equal expected, pirate.ship_log
+ end
+
+ define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do
+ association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
+
+ @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
+ @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ child_id = @pirate.send(association_name_with_callbacks).first.id
+
+ @pirate.ship_log.clear
+ @pirate.save
+
+ expected = [
+ "before_removing_#{callback_type}_parrot_#{child_id}",
+ "after_removing_#{callback_type}_parrot_#{child_id}"
+ ]
+
+ assert_equal expected, @pirate.ship_log
+ end
end
end
class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -850,7 +965,10 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
- assert_equal [nil, nil, nil, nil], values
+ expected = ActiveRecord::IdentityMap.enabled? ?
+ [nil, nil, '', ''] :
+ [nil, nil, nil, nil]
+ assert_equal expected, values
else
assert_equal ['', '', '', ''], values
end
@@ -899,7 +1017,7 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
end
class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@ship = Ship.create(:name => 'Nights Dirty Lightning')
@@ -945,7 +1063,8 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
@ship.save(:validate => false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
- assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase]
+ expected = ActiveRecord::IdentityMap.enabled? ? [nil, ''] : [nil, nil]
+ assert_equal expected, [@ship.reload.name, @ship.pirate.catchphrase]
else
assert_equal ['', ''], [@ship.reload.name, @ship.pirate.catchphrase]
end
@@ -1146,7 +1265,7 @@ module AutosaveAssociationOnACollectionAssociationTests
end
class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@association_name = :birds
@@ -1160,7 +1279,7 @@ class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
end
class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@association_name = :parrots
@@ -1175,7 +1294,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::T
end
class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -1191,11 +1310,12 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te
end
class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate.create_ship(:name => 'titanic')
+ super
end
test "should automatically validate associations with :validate => true" do
@@ -1204,7 +1324,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes
assert !@pirate.valid?
end
- test "should not automatically validate associations without :validate => true" do
+ test "should not automatically asd validate associations without :validate => true" do
assert @pirate.valid?
@pirate.non_validated_ship.name = ''
assert @pirate.valid?
@@ -1212,7 +1332,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes
end
class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -1232,7 +1352,7 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::
end
class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@@ -1254,7 +1374,7 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test
end
class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.new
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 86d4a90fc4..b62b5003e4 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -19,6 +19,8 @@ require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
require 'models/loose_person'
+require 'models/edge'
+require 'models/joke'
require 'rexml/document'
require 'active_support/core_ext/exception'
@@ -48,6 +50,57 @@ class Boolean < ActiveRecord::Base; end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
+ def test_columns_should_obey_set_primary_key
+ pk = Subscriber.columns.find { |x| x.name == 'nick' }
+ assert pk.primary, 'nick should be primary key'
+ end
+
+ def test_primary_key_with_no_id
+ assert_nil Edge.primary_key
+ end
+
+ unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
+ def test_limit_with_comma
+ assert_nothing_raised do
+ Topic.limit("1,2").all
+ end
+ end
+ end
+
+ def test_limit_without_comma
+ assert_nothing_raised do
+ assert_equal 1, Topic.limit("1").all.length
+ end
+
+ assert_nothing_raised do
+ assert_equal 1, Topic.limit(1).all.length
+ end
+ end
+
+ def test_invalid_limit
+ assert_raises(ArgumentError) do
+ Topic.limit("asdfadf").all
+ end
+ end
+
+ def test_limit_should_sanitize_sql_injection_for_limit_without_comas
+ assert_raises(ArgumentError) do
+ Topic.limit("1 select * from schema").all
+ end
+ end
+
+ def test_limit_should_sanitize_sql_injection_for_limit_with_comas
+ assert_raises(ArgumentError) do
+ Topic.limit("1, 7 procedure help()").all
+ 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
+ end
+ end
+
def test_select_symbol
topic_ids = Topic.select(:id).map(&:id).sort
assert_equal Topic.find(:all).map(&:id).sort, topic_ids
@@ -81,6 +134,7 @@ class BasicsTest < ActiveRecord::TestCase
fakepool = Class.new(Struct.new(:spec)) {
def with_connection; yield self; end
def connection_pool; self; end
+ def table_exists?(name); false; end
def quote_table_name(*args); raise "lol quote_table_name"; end
}
@@ -698,7 +752,7 @@ class BasicsTest < ActiveRecord::TestCase
duped_topic.reload
# FIXME: I think this is poor behavior, and will fix it with #5686
- assert_equal({'a' => 'c'}.to_s, duped_topic.title)
+ assert_equal({'a' => 'c'}.to_yaml, duped_topic.title)
end
def test_dup_with_aggregate_of_same_name_as_attribute
@@ -997,6 +1051,25 @@ class BasicsTest < ActiveRecord::TestCase
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)
@@ -1013,6 +1086,52 @@ class BasicsTest < ActiveRecord::TestCase
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)
@@ -1068,9 +1187,14 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_define_attr_method_with_block
- k = Class.new( ActiveRecord::Base )
- k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key }
- assert_equal "sys_id", k.primary_key
+ k = Class.new( ActiveRecord::Base ) do
+ class << self
+ attr_accessor :foo_key
+ end
+ end
+ k.foo_key = "id"
+ k.send(:define_attr_method, :foo_key) { "sys_" + original_foo_key }
+ assert_equal "sys_id", k.foo_key
end
def test_set_table_name_with_value
@@ -1081,6 +1205,16 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "bar", k.table_name
end
+ def test_switching_between_table_name
+ assert_difference("GoodJoke.count") do
+ Joke.set_table_name "cold_jokes"
+ Joke.create
+
+ Joke.set_table_name "funny_jokes"
+ Joke.create
+ end
+ end
+
def test_quoted_table_name_after_set_table_name
klass = Class.new(ActiveRecord::Base)
@@ -1109,6 +1243,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_set_primary_key_with_block
k = Class.new( ActiveRecord::Base )
+ k.primary_key = 'id'
k.set_primary_key { "sys_" + original_primary_key }
assert_equal "sys_id", k.primary_key
end
@@ -1161,12 +1296,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal res6, res7
end
- def test_interpolate_sql
- assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') }
- assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') }
- assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar} baz') }
- end
-
def test_scoped_find_conditions
scoped_developers = Developer.send(:with_scope, :find => { :conditions => 'salary > 90000' }) do
Developer.find(:all, :conditions => 'id < 5')
@@ -1477,6 +1606,14 @@ class BasicsTest < ActiveRecord::TestCase
end
end
+ def test_clear_cache!
+ # preheat cache
+ c1 = Post.columns
+ ActiveRecord::Base.clear_cache!
+ c2 = Post.columns
+ assert_not_equal c1, c2
+ end
+
def test_default_scope_is_reset
Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
UnloadablePost.table_name = 'posts'
@@ -1492,4 +1629,11 @@ class BasicsTest < ActiveRecord::TestCase
ensure
Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost)
end
+
+ def test_marshal_round_trip
+ expected = posts(:welcome)
+ actual = Marshal.load(Marshal.dump(expected))
+
+ assert_equal expected.attributes, actual.attributes
+ end
end
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index 9e72ac4250..dc0e0da4c5 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -7,6 +7,7 @@ class EachTest < ActiveRecord::TestCase
def setup
@posts = Post.order("id asc")
@total = Post.count
+ Post.count('id') # preheat arel's table cache
end
def test_each_should_excecute_one_query_per_batch
diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb
new file mode 100644
index 0000000000..19383bb06b
--- /dev/null
+++ b/activerecord/test/cases/bind_parameter_test.rb
@@ -0,0 +1,90 @@
+require 'cases/helper'
+require 'models/topic'
+
+module ActiveRecord
+ class BindParameterTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ class LogListener
+ attr_accessor :calls
+
+ def initialize
+ @calls = []
+ end
+
+ def call(*args)
+ calls << args
+ end
+ end
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @listener = LogListener.new
+ @pk = Topic.columns.find { |c| c.primary }
+ ActiveSupport::Notifications.subscribe('sql.active_record', @listener)
+ end
+
+ def teardown
+ ActiveSupport::Notifications.unsubscribe(@listener)
+ end
+
+ def test_binds_are_logged
+ # FIXME: use skip with minitest
+ return unless @connection.supports_statement_cache?
+
+ sub = @connection.substitute_for(@pk, [])
+ binds = [[@pk, 1]]
+ sql = "select * from topics where id = #{sub}"
+
+ @connection.exec_query(sql, 'SQL', binds)
+
+ message = @listener.calls.find { |args| args[4][:sql] == sql }
+ assert_equal binds, message[4][:binds]
+ end
+
+ def test_find_one_uses_binds
+ # FIXME: use skip with minitest
+ return unless @connection.supports_statement_cache?
+
+ Topic.find(1)
+ binds = [[@pk, 1]]
+ message = @listener.calls.find { |args| args[4][:binds] == binds }
+ assert message, 'expected a message with binds'
+ end
+
+ def test_logs_bind_vars
+ # FIXME: use skip with minitest
+ return unless @connection.supports_statement_cache?
+
+ pk = Topic.columns.find { |x| x.primary }
+
+ payload = {
+ :name => 'SQL',
+ :sql => 'select * from topics where id = ?',
+ :binds => [[pk, 10]]
+ }
+ event = ActiveSupport::Notifications::Event.new(
+ 'foo',
+ Time.now,
+ Time.now,
+ 123,
+ payload)
+
+ logger = Class.new(ActiveRecord::LogSubscriber) {
+ attr_reader :debugs
+ def initialize
+ super
+ @debugs = []
+ end
+
+ def debug str
+ @debugs << str
+ end
+ }.new
+
+ logger.sql event
+ assert_match([[pk.name, 10]].inspect, logger.debugs.first)
+ end
+ end
+end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 5cb8485b4b..caf07a7357 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -23,6 +23,17 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal 53.0, value
end
+ def test_should_return_decimal_average_of_integer_field
+ value = Account.average(:id)
+ assert_equal 3.5, value
+ end
+
+ def test_should_return_integer_average_if_db_returns_such
+ Account.connection.stubs :select_value => 3
+ value = Account.average(:id)
+ assert_equal 3, value
+ end
+
def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
@@ -98,6 +109,36 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal [2, 6], c.keys.compact
end
+ def test_limit_with_offset_is_kept
+ return if current_adapter?(:OracleAdapter)
+
+ queries = assert_sql { Account.limit(1).offset(1).count }
+ assert_equal 1, queries.length
+ assert_match(/LIMIT/, queries.first)
+ assert_match(/OFFSET/, queries.first)
+ end
+
+ def test_offset_without_limit_removes_offset
+ queries = assert_sql { Account.offset(1).count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
+ def test_limit_without_offset_removes_limit
+ queries = assert_sql { Account.limit(1).count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
+ def test_no_limit_no_offset
+ queries = assert_sql { Account.count }
+ assert_equal 1, queries.length
+ assert_no_match(/LIMIT/, queries.first)
+ assert_no_match(/OFFSET/, queries.first)
+ end
+
def test_should_group_by_summed_field_having_condition
c = Account.sum(:credit_limit, :group => :firm_id,
:having => 'sum(credit_limit) > 50')
diff --git a/activerecord/test/cases/coders/yaml_column_test.rb b/activerecord/test/cases/coders/yaml_column_test.rb
new file mode 100644
index 0000000000..c7dcc21809
--- /dev/null
+++ b/activerecord/test/cases/coders/yaml_column_test.rb
@@ -0,0 +1,46 @@
+
+require "cases/helper"
+
+module ActiveRecord
+ module Coders
+ class YAMLColumnTest < ActiveRecord::TestCase
+ def test_initialize_takes_class
+ coder = YAMLColumn.new(Object)
+ assert_equal Object, coder.object_class
+ end
+
+ def test_type_mismatch_on_different_classes
+ coder = YAMLColumn.new(Array)
+ assert_raises(SerializationTypeMismatch) do
+ coder.load "--- foo"
+ end
+ end
+
+ def test_nil_is_ok
+ coder = YAMLColumn.new
+ assert_nil coder.load "--- "
+ end
+
+ def test_returns_new_with_different_class
+ coder = YAMLColumn.new SerializationTypeMismatch
+ assert_equal SerializationTypeMismatch, coder.load("--- ").class
+ end
+
+ def test_returns_string_unless_starts_with_dash
+ coder = YAMLColumn.new
+ assert_equal 'foo', coder.load("foo")
+ end
+
+ def test_load_handles_other_classes
+ coder = YAMLColumn.new
+ assert_equal [], coder.load([])
+ end
+
+ def test_load_swallows_yaml_exceptions
+ coder = YAMLColumn.new
+ bad_yaml = '--- {'
+ assert_equal bad_yaml, coder.load(bad_yaml)
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
index cc6a6b44f2..d1dddd4c2c 100644
--- a/activerecord/test/cases/column_definition_test.rb
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -1,121 +1,145 @@
require "cases/helper"
-class ColumnDefinitionTest < ActiveRecord::TestCase
- def setup
- @adapter = ActiveRecord::ConnectionAdapters::AbstractAdapter.new(nil)
- def @adapter.native_database_types
- {:string => "varchar"}
- end
- end
+module ActiveRecord
+ module ConnectionAdapters
+ class ColumnDefinitionTest < ActiveRecord::TestCase
+ def setup
+ @adapter = AbstractAdapter.new(nil)
+ def @adapter.native_database_types
+ {:string => "varchar"}
+ end
+ end
- # Avoid column definitions in create table statements like:
- # `title` varchar(255) DEFAULT NULL
- def test_should_not_include_default_clause_when_default_is_null
- column = ActiveRecord::ConnectionAdapters::Column.new("title", nil, "varchar(20)")
- column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
- @adapter, column.name, "string",
- column.limit, column.precision, column.scale, column.default, column.null)
- assert_equal "title varchar(20)", column_def.to_sql
- end
+ def test_can_set_coder
+ column = Column.new("title", nil, "varchar(20)")
+ column.coder = YAML
+ assert_equal YAML, column.coder
+ end
- def test_should_include_default_clause_when_default_is_present
- column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)")
- column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
- @adapter, column.name, "string",
- column.limit, column.precision, column.scale, column.default, column.null)
- assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql
- end
+ def test_encoded?
+ column = Column.new("title", nil, "varchar(20)")
+ assert !column.encoded?
- def test_should_specify_not_null_if_null_option_is_false
- column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)", false)
- column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new(
- @adapter, column.name, "string",
- column.limit, column.precision, column.scale, column.default, column.null)
- assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql
- end
+ column.coder = YAML
+ assert column.encoded?
+ end
- if current_adapter?(:MysqlAdapter)
- def test_should_set_default_for_mysql_binary_data_types
- binary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "binary(1)")
- assert_equal "a", binary_column.default
+ def test_type_case_coded_column
+ column = Column.new("title", nil, "varchar(20)")
+ column.coder = YAML
+ assert_equal "hello", column.type_cast("--- hello")
+ end
- varbinary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "varbinary(1)")
- assert_equal "a", varbinary_column.default
- end
+ # Avoid column definitions in create table statements like:
+ # `title` varchar(255) DEFAULT NULL
+ def test_should_not_include_default_clause_when_default_is_null
+ column = Column.new("title", nil, "varchar(20)")
+ column_def = ColumnDefinition.new(
+ @adapter, column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal "title varchar(20)", column_def.to_sql
+ end
- def test_should_not_set_default_for_blob_and_text_data_types
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "blob")
+ def test_should_include_default_clause_when_default_is_present
+ column = Column.new("title", "Hello", "varchar(20)")
+ column_def = ColumnDefinition.new(
+ @adapter, column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql
end
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "Hello", "text")
+ def test_should_specify_not_null_if_null_option_is_false
+ column = Column.new("title", "Hello", "varchar(20)", false)
+ column_def = ColumnDefinition.new(
+ @adapter, column.name, "string",
+ column.limit, column.precision, column.scale, column.default, column.null)
+ assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql
end
- text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text")
- assert_equal nil, text_column.default
+ if current_adapter?(:MysqlAdapter)
+ def test_should_set_default_for_mysql_binary_data_types
+ binary_column = MysqlColumn.new("title", "a", "binary(1)")
+ assert_equal "a", binary_column.default
- not_null_text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text", false)
- assert_equal "", not_null_text_column.default
- end
+ varbinary_column = MysqlColumn.new("title", "a", "varbinary(1)")
+ assert_equal "a", varbinary_column.default
+ end
- def test_has_default_should_return_false_for_blog_and_test_data_types
- blob_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "blob")
- assert !blob_column.has_default?
+ def test_should_not_set_default_for_blob_and_text_data_types
+ assert_raise ArgumentError do
+ MysqlColumn.new("title", "a", "blob")
+ end
- text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text")
- assert !text_column.has_default?
- end
- end
+ assert_raise ArgumentError do
+ MysqlColumn.new("title", "Hello", "text")
+ end
- if current_adapter?(:Mysql2Adapter)
- def test_should_set_default_for_mysql_binary_data_types
- binary_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "binary(1)")
- assert_equal "a", binary_column.default
+ text_column = MysqlColumn.new("title", nil, "text")
+ assert_equal nil, text_column.default
- varbinary_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "varbinary(1)")
- assert_equal "a", varbinary_column.default
- end
+ not_null_text_column = MysqlColumn.new("title", nil, "text", false)
+ assert_equal "", not_null_text_column.default
+ end
- def test_should_not_set_default_for_blob_and_text_data_types
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "blob")
- end
+ def test_has_default_should_return_false_for_blog_and_test_data_types
+ blob_column = MysqlColumn.new("title", nil, "blob")
+ assert !blob_column.has_default?
- assert_raise ArgumentError do
- ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "Hello", "text")
+ text_column = MysqlColumn.new("title", nil, "text")
+ assert !text_column.has_default?
+ end
end
- text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text")
- assert_equal nil, text_column.default
+ if current_adapter?(:Mysql2Adapter)
+ def test_should_set_default_for_mysql_binary_data_types
+ binary_column = Mysql2Column.new("title", "a", "binary(1)")
+ assert_equal "a", binary_column.default
- not_null_text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text", false)
- assert_equal "", not_null_text_column.default
- end
+ varbinary_column = Mysql2Column.new("title", "a", "varbinary(1)")
+ assert_equal "a", varbinary_column.default
+ end
- def test_has_default_should_return_false_for_blog_and_test_data_types
- blob_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "blob")
- assert !blob_column.has_default?
+ def test_should_not_set_default_for_blob_and_text_data_types
+ assert_raise ArgumentError do
+ Mysql2Column.new("title", "a", "blob")
+ end
- text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text")
- assert !text_column.has_default?
- end
- end
+ assert_raise ArgumentError do
+ Mysql2Column.new("title", "Hello", "text")
+ end
- if current_adapter?(:PostgreSQLAdapter)
- def test_bigint_column_should_map_to_integer
- bigint_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('number', nil, "bigint")
- assert_equal :integer, bigint_column.type
- end
+ text_column = Mysql2Column.new("title", nil, "text")
+ assert_equal nil, text_column.default
- def test_smallint_column_should_map_to_integer
- smallint_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('number', nil, "smallint")
- assert_equal :integer, smallint_column.type
- end
+ not_null_text_column = Mysql2Column.new("title", nil, "text", false)
+ assert_equal "", not_null_text_column.default
+ end
+
+ def test_has_default_should_return_false_for_blog_and_test_data_types
+ blob_column = Mysql2Column.new("title", nil, "blob")
+ assert !blob_column.has_default?
- def test_uuid_column_should_map_to_string
- uuid_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('unique_id', nil, "uuid")
- assert_equal :string, uuid_column.type
+ text_column = Mysql2Column.new("title", nil, "text")
+ assert !text_column.has_default?
+ end
+ end
+
+ if current_adapter?(:PostgreSQLAdapter)
+ def test_bigint_column_should_map_to_integer
+ bigint_column = PostgreSQLColumn.new('number', nil, "bigint")
+ assert_equal :integer, bigint_column.type
+ end
+
+ def test_smallint_column_should_map_to_integer
+ smallint_column = PostgreSQLColumn.new('number', nil, "smallint")
+ assert_equal :integer, smallint_column.type
+ end
+
+ def test_uuid_column_should_map_to_string
+ uuid_column = PostgreSQLColumn.new('unique_id', nil, "uuid")
+ assert_equal :string, uuid_column.type
+ end
+ end
end
end
end
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index 2e18117895..7ac14fa8d6 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -3,6 +3,58 @@ require "cases/helper"
module ActiveRecord
module ConnectionAdapters
class ConnectionPoolTest < ActiveRecord::TestCase
+ def setup
+ # Keep a duplicate pool so we do not bother others
+ @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+
+ if in_memory_db?
+ # Separate connections to an in-memory database create an entirely new database,
+ # with an empty schema etc, so we just stub out this schema on the fly.
+ @pool.with_connection do |connection|
+ connection.create_table :posts do |t|
+ t.integer :cololumn
+ end
+ end
+ end
+ end
+
+ def test_pool_caches_columns
+ columns = @pool.columns['posts']
+ assert_equal columns, @pool.columns['posts']
+ end
+
+ def test_pool_caches_columns_hash
+ columns_hash = @pool.columns_hash['posts']
+ assert_equal columns_hash, @pool.columns_hash['posts']
+ end
+
+ def test_clearing_column_cache
+ @pool.columns['posts']
+ @pool.columns_hash['posts']
+
+ @pool.clear_cache!
+
+ assert_equal 0, @pool.columns.size
+ assert_equal 0, @pool.columns_hash.size
+ end
+
+ def test_primary_key
+ assert_equal 'id', @pool.primary_keys['posts']
+ end
+
+ def test_primary_key_for_non_existent_table
+ assert_equal 'id', @pool.primary_keys['omgponies']
+ end
+
+ def test_primary_key_is_set_on_columns
+ posts_columns = @pool.columns_hash['posts']
+ assert posts_columns['id'].primary
+
+ (posts_columns.keys - ['id']).each do |key|
+ assert !posts_columns[key].primary
+ end
+ end
+
def test_clear_stale_cached_connections!
pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
@@ -55,6 +107,26 @@ module ActiveRecord
end.join()
end
+
+ def test_automatic_reconnect=
+ pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
+ assert pool.automatic_reconnect
+ assert pool.connection
+
+ pool.disconnect!
+ assert pool.connection
+
+ pool.disconnect!
+ pool.automatic_reconnect = false
+
+ assert_raises(ConnectionNotEstablished) do
+ pool.connection
+ end
+
+ assert_raises(ConnectionNotEstablished) do
+ pool.with_connection
+ end
+ end
end
end
end
diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb
new file mode 100644
index 0000000000..d63ecdbcc5
--- /dev/null
+++ b/activerecord/test/cases/custom_locking_test.rb
@@ -0,0 +1,17 @@
+require "cases/helper"
+require 'models/person'
+
+module ActiveRecord
+ class CustomLockingTest < ActiveRecord::TestCase
+ fixtures :people
+
+ def test_custom_lock
+ 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.find(1, :lock => 'LOCK IN SHARE MODE')
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index f4af6506c5..2e620d8b03 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -984,7 +984,7 @@ class FinderTest < ActiveRecord::TestCase
def test_select_rows
assert_equal(
- [["1", nil, nil, "37signals"],
+ [["1", "1", nil, "37signals"],
["2", "1", "2", "Summit"],
["3", "1", "1", "Microsoft"]],
Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}})
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 9ce163a00f..fa40fad56d 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -13,6 +13,7 @@ require 'models/category'
require 'models/parrot'
require 'models/pirate'
require 'models/treasure'
+require 'models/traffic_light'
require 'models/matey'
require 'models/ship'
require 'models/book'
@@ -24,7 +25,7 @@ class FixturesTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
self.use_transactional_fixtures = false
- fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries
+ fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights
FIXTURES = %w( accounts binaries companies customers
developers developers_projects entrants
@@ -34,7 +35,7 @@ class FixturesTest < ActiveRecord::TestCase
def test_clean_fixtures
FIXTURES.each do |name|
fixtures = nil
- assert_nothing_raised { fixtures = create_fixtures(name) }
+ assert_nothing_raised { fixtures = create_fixtures(name).first }
assert_kind_of(Fixtures, fixtures)
fixtures.each { |_name, fixture|
fixture.each { |key, value|
@@ -52,7 +53,7 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_attributes
- topics = create_fixtures("topics")
+ topics = create_fixtures("topics").first
assert_equal("The First Topic", topics["first"]["title"])
assert_nil(topics["second"]["author_email_address"])
end
@@ -126,12 +127,11 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_instantiation
- topics = create_fixtures("topics")
+ topics = create_fixtures("topics").first
assert_kind_of Topic, topics["first"].find
end
def test_complete_instantiation
- assert_equal 4, @topics.size
assert_equal "The First Topic", @first.title
end
@@ -141,7 +141,6 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_erb_in_fixtures
- assert_equal 11, @developers.size
assert_equal "fixture_5", @dev_5.name
end
@@ -198,12 +197,15 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_binary_in_fixtures
- assert_equal 1, @binaries.size
data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read }
data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding)
data.freeze
assert_equal data, @flowers.data
end
+
+ def test_serialized_fixtures
+ assert_equal ["Green", "Red", "Orange"], traffic_lights(:uk).state
+ end
end
if Account.connection.respond_to?(:reset_pk_sequence!)
@@ -240,7 +242,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!)
def test_create_fixtures_resets_sequences_when_not_cached
@instances.each do |instance|
- max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (_, fixture)|
+ max_id = create_fixtures(instance.class.table_name).first.fixtures.inject(0) do |_max_id, (_, fixture)|
fixture_id = fixture['id'].to_i
fixture_id > _max_id ? fixture_id : _max_id
end
@@ -299,9 +301,6 @@ class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase
def test_without_instance_instantiation
assert !defined?(@first), "@first is not defined"
- assert_not_nil @topics
- assert_not_nil @developers
- assert_not_nil @accounts
end
end
@@ -379,6 +378,21 @@ class ForeignKeyFixturesTest < ActiveRecord::TestCase
end
end
+class OverRideFixtureMethodTest < ActiveRecord::TestCase
+ fixtures :topics
+
+ def topics(name)
+ topic = super
+ topic.title = 'omg'
+ topic
+ end
+
+ def test_fixture_methods_can_be_overridden
+ x = topics :first
+ assert_equal 'omg', x.title
+ end
+end
+
class CheckSetTableNameFixturesTest < ActiveRecord::TestCase
set_fixture_class :funny_jokes => 'Joke'
fixtures :funny_jokes
@@ -504,7 +518,7 @@ class FasterFixturesTest < ActiveRecord::TestCase
fixtures :categories, :authors
def load_extra_fixture(name)
- fixture = create_fixtures(name)
+ fixture = create_fixtures(name).first
assert fixture.is_a?(Fixtures)
@loaded_fixtures[fixture.table_name] = fixture
end
diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb
new file mode 100644
index 0000000000..15598392e2
--- /dev/null
+++ b/activerecord/test/cases/habtm_destroy_order_test.rb
@@ -0,0 +1,17 @@
+require "cases/helper"
+require "models/lesson"
+require "models/student"
+
+class HabtmDestroyOrderTest < ActiveRecord::TestCase
+ test "may not delete a lesson with students" do
+ sicp = Lesson.new(:name => "SICP")
+ ben = Student.new(:name => "Ben Bitdiddle")
+ sicp.students << ben
+ sicp.save!
+ assert_raises LessonError do
+ assert_no_difference('Lesson.count') do
+ sicp.destroy
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index f9bbc5299b..fd20f1b120 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -11,7 +11,14 @@ require 'mocha'
require 'active_record'
require 'active_support/dependencies'
-require 'connection'
+begin
+ require 'connection'
+rescue LoadError
+ # If we cannot load connection we assume that driver was not loaded for this test case, so we load sqlite3 as default one.
+ # This allows for running separate test cases by simply running test file.
+ connection_type = defined?(JRUBY_VERSION) ? 'jdbc' : 'native'
+ require "test/connections/#{connection_type}_sqlite3/connection"
+end
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
@@ -19,6 +26,9 @@ ActiveSupport::Deprecation.debug = true
# Quote "type" if it's a reserved word for the current connection.
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
+# Enable Identity Map for testing
+ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "false" ? false : true)
+
def current_adapter?(*types)
types.any? do |type|
ActiveRecord::ConnectionAdapters.const_defined?(type) &&
@@ -26,6 +36,15 @@ def current_adapter?(*types)
end
end
+def in_memory_db?
+ current_adapter?(:SQLiteAdapter) &&
+ ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
+end
+
+def supports_savepoints?
+ ActiveRecord::Base.connection.supports_savepoints?
+end
+
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
@@ -40,42 +59,31 @@ ensure
ActiveRecord::Base.default_timezone = old_zone
end
-ActiveRecord::Base.connection.class.class_eval do
- IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /SHOW FIELDS/]
+module ActiveRecord
+ class SQLCounter
+ IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/]
- # FIXME: this needs to be refactored so specific database can add their own
- # ignored SQL. This ignored SQL is for Oracle.
- IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from ((all|user)_tab_columns|(all|user)_triggers|(all|user)_constraints)/im]
+ # FIXME: this needs to be refactored so specific database can add their own
+ # ignored SQL. This ignored SQL is for Oracle.
+ IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im]
- def execute_with_query_record(sql, name = nil, &block)
- $queries_executed ||= []
- $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
- execute_without_query_record(sql, name, &block)
- end
+ def initialize
+ $queries_executed = []
+ end
- alias_method_chain :execute, :query_record
+ def call(name, start, finish, message_id, values)
+ sql = values[:sql]
- def exec_query_with_query_record(sql, name = nil, binds = [], &block)
- $queries_executed ||= []
- $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
- exec_query_without_query_record(sql, name, binds, &block)
+ # FIXME: this seems bad. we should probably have a better way to indicate
+ # the query was cached
+ unless 'CACHE' == values[:name]
+ $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r }
+ end
+ end
end
-
- alias_method_chain :exec_query, :query_record
+ ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new)
end
-ActiveRecord::Base.connection.class.class_eval {
- attr_accessor :column_calls
-
- def columns_with_calls(*args)
- @column_calls ||= 0
- @column_calls += 1
- columns_without_calls(*args)
- end
-
- alias_method_chain :columns, :calls
-}
-
unless ENV['FIXTURE_DEBUG']
module ActiveRecord::TestFixtures::ClassMethods
def try_to_load_dependency_with_silence(*args)
@@ -96,15 +104,15 @@ class ActiveSupport::TestCase
self.use_transactional_fixtures = true
def create_fixtures(*table_names, &block)
- Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
+ Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, fixture_class_names, &block)
end
end
-# silence verbose schema loading
-original_stdout = $stdout
-$stdout = StringIO.new
+def load_schema
+ # silence verbose schema loading
+ original_stdout = $stdout
+ $stdout = StringIO.new
-begin
adapter_name = ActiveRecord::Base.connection.adapter_name.downcase
adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb"
@@ -117,6 +125,8 @@ ensure
$stdout = original_stdout
end
+load_schema
+
class << Time
unless method_defined? :now_before_time_travel
alias_method :now_before_time_travel, :now
@@ -133,4 +143,3 @@ class << Time
@now = nil
end
end
-
diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb
new file mode 100644
index 0000000000..d98638ab73
--- /dev/null
+++ b/activerecord/test/cases/identity_map_test.rb
@@ -0,0 +1,402 @@
+require "cases/helper"
+require 'models/developer'
+require 'models/project'
+require 'models/company'
+require 'models/topic'
+require 'models/reply'
+require 'models/computer'
+require 'models/customer'
+require 'models/order'
+require 'models/post'
+require 'models/author'
+require 'models/tag'
+require 'models/tagging'
+require 'models/comment'
+require 'models/sponsor'
+require 'models/member'
+require 'models/essay'
+require 'models/subscriber'
+require "models/pirate"
+require "models/bird"
+require "models/parrot"
+
+if ActiveRecord::IdentityMap.enabled?
+class IdentityMapTest < ActiveRecord::TestCase
+ fixtures :accounts, :companies, :developers, :projects, :topics,
+ :developers_projects, :computers, :authors, :author_addresses,
+ :posts, :tags, :taggings, :comments, :subscribers
+
+ ##############################################################################
+ # Basic tests checking if IM is functioning properly on basic find operations#
+ ##############################################################################
+
+ def test_find_id
+ assert_same(Client.find(3), Client.find(3))
+ end
+
+ def test_find_id_without_identity_map
+ ActiveRecord::IdentityMap.without do
+ assert_not_same(Client.find(3), Client.find(3))
+ end
+ end
+
+ def test_find_id_use_identity_map
+ ActiveRecord::IdentityMap.enabled = false
+ ActiveRecord::IdentityMap.use do
+ assert_same(Client.find(3), Client.find(3))
+ end
+ ActiveRecord::IdentityMap.enabled = true
+ end
+
+ def test_find_pkey
+ assert_same(
+ Subscriber.find('swistak'),
+ Subscriber.find('swistak')
+ )
+ end
+
+ def test_find_by_id
+ assert_same(
+ Client.find_by_id(3),
+ Client.find_by_id(3)
+ )
+ end
+
+ def test_find_by_string_and_numeric_id
+ assert_same(
+ Client.find_by_id("3"),
+ Client.find_by_id(3)
+ )
+ end
+
+ def test_find_by_pkey
+ assert_same(
+ Subscriber.find_by_nick('swistak'),
+ Subscriber.find_by_nick('swistak')
+ )
+ end
+
+ def test_find_first_id
+ assert_same(
+ Client.find(:first, :conditions => {:id => 1}),
+ Client.find(:first, :conditions => {:id => 1})
+ )
+ end
+
+ def test_find_first_pkey
+ assert_same(
+ Subscriber.find(:first, :conditions => {:nick => 'swistak'}),
+ Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ )
+ end
+
+ ##############################################################################
+ # Tests checking if IM is functioning properly on more advanced finds #
+ # and associations #
+ ##############################################################################
+
+ def test_owner_object_is_associated_from_identity_map
+ post = Post.find(1)
+ comment = post.comments.first
+
+ assert_no_queries do
+ comment.post
+ end
+ assert_same post, comment.post
+ end
+
+ def test_associated_object_are_assigned_from_identity_map
+ post = Post.find(1)
+
+ post.comments.each do |comment|
+ assert_same post, comment.post
+ assert_equal post.object_id, comment.post.object_id
+ end
+ end
+
+ def test_creation
+ t1 = Topic.create("title" => "t1")
+ t2 = Topic.find(t1.id)
+ assert_same(t1, t2)
+ end
+
+ ##############################################################################
+ # Tests checking dirty attribute behaviour with IM #
+ ##############################################################################
+
+ def test_loading_new_instance_should_not_update_dirty_attributes
+ swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ swistak.name = "Swistak Sreberkowiec"
+ assert_equal(["name"], swistak.changed)
+ assert_equal({"name" => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes)
+
+ s = Subscriber.find('swistak')
+
+ assert swistak.name_changed?
+ assert_equal("Swistak Sreberkowiec", swistak.name)
+ end
+
+ def test_loading_new_instance_should_change_dirty_attribute_original_value
+ swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ swistak.name = "Swistak Sreberkowiec"
+
+ Subscriber.update_all({:name => "Raczkowski Marcin"}, {:name => "Marcin Raczkowski"})
+
+ s = Subscriber.find('swistak')
+
+ assert_equal({'name' => ["Raczkowski Marcin", "Swistak Sreberkowiec"]}, swistak.changes)
+ assert_equal("Swistak Sreberkowiec", swistak.name)
+ end
+
+ def test_loading_new_instance_should_remove_dirt
+ swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'})
+ swistak.name = "Swistak Sreberkowiec"
+
+ assert_equal({"name" => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes)
+
+ Subscriber.update_all({:name => "Swistak Sreberkowiec"}, {:name => "Marcin Raczkowski"})
+
+ s = Subscriber.find('swistak')
+
+ assert_equal("Swistak Sreberkowiec", swistak.name)
+ assert_equal({}, swistak.changes)
+ assert !swistak.name_changed?
+ end
+
+ def test_has_many_associations
+ pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ pirate.birds.create!(:name => 'Posideons Killer')
+ pirate.birds.create!(:name => 'Killer bandita Dionne')
+
+ posideons, killer = pirate.birds
+
+ pirate.reload
+
+ pirate.birds_attributes = [{ :id => posideons.id, :name => 'Grace OMalley' }]
+ assert_equal 'Grace OMalley', pirate.birds.to_a.find { |r| r.id == posideons.id }.name
+ end
+
+ def test_changing_associations
+ post1 = Post.create("title" => "One post", "body" => "Posting...")
+ post2 = Post.create("title" => "Another post", "body" => "Posting... Again...")
+ comment = Comment.new("body" => "comment")
+
+ comment.post = post1
+ assert comment.save
+
+ assert_same(post1.comments.first, comment)
+
+ comment.post = post2
+ assert comment.save
+
+ assert_same(post2.comments.first, comment)
+ assert_equal(0, post1.comments.size)
+ end
+
+ def test_im_with_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
+ tag = posts(:welcome).tags.first
+ tag_with_joins_and_select = posts(:welcome).tags.add_joins_and_select.first
+ assert_same(tag, tag_with_joins_and_select)
+ assert_nothing_raised(NoMethodError, "Joins/select was not loaded") { tag.author_id }
+ end
+
+ ##############################################################################
+ # Tests checking Identity Map behaviour with preloaded associations, joins, #
+ # includes etc. #
+ ##############################################################################
+
+ def test_find_with_preloaded_associations
+ assert_queries(2) do
+ posts = Post.preload(:comments)
+ assert posts.first.comments.first
+ end
+
+ # With IM we'll retrieve post object from previous query, it'll have comments
+ # already preloaded from first call
+ assert_queries(1) do
+ posts = Post.preload(:comments).to_a
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.preload(:author)
+ assert posts.first.author
+ end
+
+ # With IM we'll retrieve post object from previous query, it'll have comments
+ # already preloaded from first call
+ assert_queries(1) do
+ posts = Post.preload(:author).to_a
+ assert posts.first.author
+ end
+
+ assert_queries(1) do
+ posts = Post.preload(:author, :comments).to_a
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_find_with_included_associations
+ assert_queries(2) do
+ posts = Post.includes(:comments)
+ assert posts.first.comments.first
+ end
+
+ assert_queries(1) do
+ posts = Post.scoped.includes(:comments)
+ assert posts.first.comments.first
+ end
+
+ assert_queries(2) do
+ posts = Post.includes(:author)
+ assert posts.first.author
+ end
+
+ assert_queries(1) do
+ posts = Post.includes(:author, :comments).to_a
+ assert posts.first.author
+ assert posts.first.comments.first
+ end
+ end
+
+ def test_eager_loading_with_conditions_on_joined_table_preloads
+ posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_same posts.first.author, Author.first
+
+ posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_same posts.first.author, Author.first
+
+ posts = Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id')
+ assert_equal posts(:welcome, :thinking), posts
+ assert_same posts.first.author, Author.first
+
+ posts = Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id')
+ assert_equal posts(:welcome, :thinking), posts
+ assert_same posts.first.author, Author.first
+ end
+
+ def test_eager_loading_with_conditions_on_string_joined_table_preloads
+ posts = assert_queries(2) do
+ Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+
+ posts = assert_queries(1) do
+ Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id')
+ end
+ assert_equal [posts(:welcome)], posts
+ assert_equal authors(:david), assert_no_queries { posts[0].author}
+ end
+
+ ##############################################################################
+ # Behaviour releated to saving failures
+ ##############################################################################
+
+ def test_reload_object_if_save_failed
+ developer = Developer.first
+ developer.salary = 0
+
+ assert !developer.save
+
+ same_developer = Developer.first
+
+ assert_not_same developer, same_developer
+ assert_not_equal 0, same_developer.salary
+ assert_not_equal developer.salary, same_developer.salary
+ end
+
+ def test_reload_object_if_forced_save_failed
+ developer = Developer.first
+ developer.salary = 0
+
+ assert_raise(ActiveRecord::RecordInvalid) { developer.save! }
+
+ same_developer = Developer.first
+
+ assert_not_same developer, same_developer
+ assert_not_equal 0, same_developer.salary
+ assert_not_equal developer.salary, same_developer.salary
+ end
+
+ def test_reload_object_if_update_attributes_fails
+ developer = Developer.first
+ developer.salary = 0
+
+ assert !developer.update_attributes(:salary => 0)
+
+ same_developer = Developer.first
+
+ assert_not_same developer, same_developer
+ assert_not_equal 0, same_developer.salary
+ assert_not_equal developer.salary, same_developer.salary
+ end
+
+ ##############################################################################
+ # Behaviour of readonly, forzen, destroyed
+ ##############################################################################
+
+ def test_find_using_identity_map_respects_readonly_when_loading_associated_object_first
+ author = Author.first
+ readonly_comment = author.readonly_comments.first
+
+ comment = Comment.first
+ assert !comment.readonly?
+
+ assert readonly_comment.readonly?
+
+ assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save}
+ assert comment.save
+ end
+
+ def test_find_using_identity_map_respects_readonly
+ comment = Comment.first
+ assert !comment.readonly?
+
+ author = Author.first
+ readonly_comment = author.readonly_comments.first
+
+ assert readonly_comment.readonly?
+
+ assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save}
+ assert comment.save
+ end
+
+ def test_find_using_select_and_identity_map
+ author_id, author = Author.select('id').first, Author.first
+
+ assert_equal author_id, author
+ assert_same author_id, author
+ assert_not_nil author.name
+
+ post, post_id = Post.first, Post.select('id').first
+
+ assert_equal post_id, post
+ assert_same post_id, post
+ assert_not_nil post.title
+ end
+
+# Currently AR is not allowing changing primary key (see Persistence#update)
+# So we ignore it. If this changes, this test needs to be uncommented.
+# def test_updating_of_pkey
+# assert client = Client.find(3),
+# client.update_attribute(:id, 666)
+#
+# assert Client.find(666)
+# assert_same(client, Client.find(666))
+#
+# s = Subscriber.find_by_nick('swistak')
+# assert s.update_attribute(:nick, 'swistakTheJester')
+# assert_equal('swistakTheJester', s.nick)
+#
+# assert stj = Subscriber.find_by_nick('swistakTheJester')
+# assert_same(s, stj)
+# end
+
+end
+end
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index c3da9cdf53..b5d8314541 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -203,12 +203,12 @@ class InheritanceTest < ActiveRecord::TestCase
def test_eager_load_belongs_to_something_inherited
account = Account.find(1, :include => :firm)
- assert_not_nil account.instance_variable_get("@firm"), "nil proves eager load failed"
+ assert account.association_cache.key?(:firm), "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')} = 1\)/) do
+ assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do
Account.find(1, :include => :firm)
end
end
@@ -219,6 +219,10 @@ class InheritanceTest < ActiveRecord::TestCase
switch_to_default_inheritance_column
end
+ def test_inherits_custom_primary_key
+ assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
+ end
+
def test_inheritance_without_mapping
assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb
index b8c3ffb9cb..6cd8494c9e 100644
--- a/activerecord/test/cases/lifecycle_test.rb
+++ b/activerecord/test/cases/lifecycle_test.rb
@@ -7,6 +7,16 @@ require 'models/comment'
class SpecialDeveloper < Developer; end
+class DeveloperObserver < ActiveRecord::Observer
+ def calls
+ @calls ||= []
+ end
+
+ def before_save(developer)
+ calls << developer
+ end
+end
+
class SalaryChecker < ActiveRecord::Observer
observe :special_developer
attr_accessor :last_saved
@@ -101,9 +111,10 @@ class LifecycleTest < ActiveRecord::TestCase
fixtures :topics, :developers, :minimalistics
def test_before_destroy
- original_count = Topic.count
- (topic_to_be_destroyed = Topic.find(1)).destroy
- assert_equal original_count - (1 + topic_to_be_destroyed.replies.size), Topic.count
+ topic = Topic.find(1)
+ assert_difference 'Topic.count', -(1 + topic.replies.size) do
+ topic.destroy
+ end
end
def test_auto_observer
@@ -195,4 +206,14 @@ class LifecycleTest < ActiveRecord::TestCase
assert_equal developer, SalaryChecker.instance.last_saved
end
+ def test_observer_is_called_once
+ observer = DeveloperObserver.instance # activate
+ observer.calls.clear
+
+ developer = Developer.create! :name => 'Ancestor', :salary => 100000
+ special_developer = SpecialDeveloper.create! :name => 'Descendent', :salary => 100000
+
+ assert_equal [developer, special_developer], observer.calls
+ end
+
end
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index f9678cb0c5..636a709924 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -1,6 +1,7 @@
require 'thread'
require "cases/helper"
require 'models/person'
+require 'models/job'
require 'models/reader'
require 'models/legacy_thing'
require 'models/reference'
@@ -19,11 +20,6 @@ end
class OptimisticLockingTest < ActiveRecord::TestCase
fixtures :people, :legacy_things, :references
- # need to disable transactional fixtures, because otherwise the sqlite3
- # adapter (at least) chokes when we try and change the schema in the middle
- # of a test (see test_increment_counter_*).
- self.use_transactional_fixtures = false
-
def test_lock_existing
p1 = Person.find(1)
p2 = Person.find(1)
@@ -103,6 +99,14 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal 1, p1.lock_version
end
+ def test_touch_existing_lock
+ p1 = Person.find(1)
+ assert_equal 0, p1.lock_version
+
+ p1.touch
+ assert_equal 1, p1.lock_version
+ end
+
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
@@ -152,6 +156,33 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal "unchangeable name", p.first_name
end
+ def test_quote_table_name
+ ref = references(:michael_magician)
+ ref.favourite = !ref.favourite
+ assert ref.save
+ end
+
+ # Useful for partial updates, don't only update the lock_version if there
+ # is nothing else being updated.
+ def test_update_without_attributes_does_not_only_update_lock_version
+ assert_nothing_raised do
+ p1 = Person.create!(:first_name => 'anika')
+ lock_version = p1.lock_version
+ p1.save
+ p1.reload
+ assert_equal lock_version, p1.lock_version
+ end
+ end
+end
+
+class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
+ fixtures :people, :legacy_things, :references
+
+ # need to disable transactional fixtures, because otherwise the sqlite3
+ # adapter (at least) chokes when we try and change the schema in the middle
+ # of a test (see test_increment_counter_*).
+ self.use_transactional_fixtures = false
+
{ :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model|
define_method("test_increment_counter_updates_#{name}") do
counter_test model, 1 do |id|
@@ -198,24 +229,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::RecordNotFound) { LegacyThing.find(t.id) }
end
- def test_quote_table_name
- ref = references(:michael_magician)
- ref.favourite = !ref.favourite
- assert ref.save
- end
-
- # Useful for partial updates, don't only update the lock_version if there
- # is nothing else being updated.
- def test_update_without_attributes_does_not_only_update_lock_version
- assert_nothing_raised do
- p1 = Person.create!(:first_name => 'anika')
- lock_version = p1.lock_version
- p1.save
- p1.reload
- assert_equal lock_version, p1.lock_version
- end
- end
-
private
def add_counter_column_to(model, col='test_count')
@@ -252,7 +265,7 @@ end
# TODO: The Sybase, and OpenBase adapters currently have no support for pessimistic locking
-unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
+unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db?
class PessimisticLockingTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
fixtures :people, :readers
diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb
index 0ffd0e2ab3..7e8383da9e 100644
--- a/activerecord/test/cases/method_scoping_test.rb
+++ b/activerecord/test/cases/method_scoping_test.rb
@@ -14,7 +14,7 @@ class MethodScopingTest < ActiveRecord::TestCase
def test_set_conditions
Developer.send(:with_scope, :find => { :conditions => 'just a test...' }) do
- assert_equal '(just a test...)', Developer.scoped.arel.send(:where_clauses).join(' AND ')
+ assert_match '(just a test...)', Developer.scoped.arel.to_sql
end
end
@@ -227,7 +227,7 @@ class MethodScopingTest < ActiveRecord::TestCase
end
def test_scoped_create_with_join_and_merge
- (Comment.where(:body => "but Who's Buying?").joins(:post) & Post.where(:body => 'Peace Sells...')).with_scope do
+ Comment.where(:body => "but Who's Buying?").joins(:post).merge(Post.where(:body => 'Peace Sells...')).with_scope do
assert_equal({:body => "but Who's Buying?"}, Comment.scoped.scope_for_create)
end
end
@@ -275,7 +275,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do
Developer.send(:with_scope, :find => { :limit => 10 }) do
devs = Developer.scoped
- assert_equal '(salary = 80000)', devs.arel.send(:where_clauses).join(' AND ')
+ assert_match '(salary = 80000)', devs.arel.to_sql
assert_equal 10, devs.taken
end
end
@@ -309,7 +309,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do
devs = Developer.scoped
- assert_equal "(name = 'David') AND (salary = 80000)", devs.arel.send(:where_clauses).join(' AND ')
+ assert_match "(name = 'David') AND (salary = 80000)", devs.arel.to_sql
assert_equal(1, Developer.count)
end
Developer.send(:with_scope, :find => { :conditions => "name = 'Maiha'" }) do
@@ -322,7 +322,7 @@ class NestedScopingTest < ActiveRecord::TestCase
Developer.send(:with_scope, :find => { :conditions => 'salary = 80000', :limit => 10 }) do
Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do
devs = Developer.scoped
- assert_equal "(salary = 80000) AND (name = 'David')", devs.arel.send(:where_clauses).join(' AND ')
+ assert_match "(salary = 80000) AND (name = 'David')", devs.arel.to_sql
assert_equal 10, devs.taken
end
end
diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb
index ea2292dda5..ae531ebb4c 100644
--- a/activerecord/test/cases/migration/command_recorder_test.rb
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -16,7 +16,7 @@ module ActiveRecord
def test_send_calls_super
assert_raises(NoMethodError) do
- @recorder.send(:create_table, :horses)
+ @recorder.send(:non_existing_method, :horses)
end
end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 1a65045ded..9d7c49768b 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -14,7 +14,7 @@ if ActiveRecord::Base.connection.supports_migrations?
class Reminder < ActiveRecord::Base; end
class ActiveRecord::Migration
- class <<self
+ class << self
attr_accessor :message_count
end
@@ -1923,6 +1923,149 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
+ if ActiveRecord::Base.connection.supports_bulk_alter?
+ class BulkAlterTableMigrationsTest < ActiveRecord::TestCase
+ def setup
+ @connection = Person.connection
+ @connection.create_table(:delete_me, :force => true) {|t| }
+ end
+
+ def teardown
+ Person.connection.drop_table(:delete_me) rescue nil
+ end
+
+ def test_adding_multiple_columns
+ assert_queries(1) do
+ with_bulk_change_table do |t|
+ t.column :name, :string
+ t.string :qualification, :experience
+ t.integer :age, :default => 0
+ t.date :birthdate
+ t.timestamps
+ end
+ end
+
+ assert_equal 8, columns.size
+ [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type }
+ assert_equal 0, column(:age).default
+ end
+
+ def test_removing_columns
+ with_bulk_change_table do |t|
+ t.string :qualification, :experience
+ end
+
+ [:qualification, :experience].each {|c| assert column(c) }
+
+ assert_queries(1) do
+ with_bulk_change_table do |t|
+ t.remove :qualification, :experience
+ t.string :qualification_experience
+ end
+ end
+
+ [:qualification, :experience].each {|c| assert ! column(c) }
+ assert column(:qualification_experience)
+ end
+
+ def test_adding_indexes
+ with_bulk_change_table do |t|
+ t.string :username
+ t.string :name
+ t.integer :age
+ end
+
+ # Adding an index fires a query everytime to check if an index already exists or not
+ assert_queries(3) do
+ with_bulk_change_table do |t|
+ t.index :username, :unique => true, :name => :awesome_username_index
+ t.index [:name, :age]
+ end
+ end
+
+ assert_equal 2, indexes.size
+
+ name_age_index = index(:index_delete_me_on_name_and_age)
+ assert_equal ['name', 'age'].sort, name_age_index.columns.sort
+ assert ! name_age_index.unique
+
+ assert index(:awesome_username_index).unique
+ end
+
+ def test_removing_index
+ with_bulk_change_table do |t|
+ t.string :name
+ t.index :name
+ end
+
+ assert index(:index_delete_me_on_name)
+
+ assert_queries(3) do
+ with_bulk_change_table do |t|
+ t.remove_index :name
+ t.index :name, :name => :new_name_index, :unique => true
+ end
+ end
+
+ assert ! index(:index_delete_me_on_name)
+
+ new_name_index = index(:new_name_index)
+ assert new_name_index.unique
+ end
+
+ def test_changing_columns
+ with_bulk_change_table do |t|
+ t.string :name
+ t.date :birthdate
+ end
+
+ assert ! column(:name).default
+ assert_equal :date, column(:birthdate).type
+
+ # One query for columns (delete_me table)
+ # One query for primary key (delete_me table)
+ # One query to do the bulk change
+ assert_queries(3) do
+ with_bulk_change_table do |t|
+ t.change :name, :string, :default => 'NONAME'
+ t.change :birthdate, :datetime
+ end
+ end
+
+ assert_equal 'NONAME', column(:name).default
+ assert_equal :datetime, column(:birthdate).type
+ end
+
+ protected
+
+ def with_bulk_change_table
+ # Reset columns/indexes cache as we're changing the table
+ @columns = @indexes = nil
+
+ Person.connection.change_table(:delete_me, :bulk => true) do |t|
+ yield t
+ end
+ end
+
+ def column(name)
+ columns.detect {|c| c.name == name.to_s }
+ end
+
+ def columns
+ @columns ||= Person.connection.columns('delete_me')
+ end
+
+ def index(name)
+ indexes.detect {|i| i.name == name.to_s }
+ end
+
+ def indexes
+ @indexes ||= Person.connection.indexes('delete_me')
+ end
+ end # AlterTableMigrationsTest
+
+ end
+
class CopyMigrationsTest < ActiveRecord::TestCase
def setup
end
@@ -2083,4 +2226,3 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
end
-
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
index 14870cb0e2..a2041af16a 100644
--- a/activerecord/test/cases/modules_test.rb
+++ b/activerecord/test/cases/modules_test.rb
@@ -49,7 +49,6 @@ class ModulesTest < ActiveRecord::TestCase
def test_find_account_and_include_company
account = MyApplication::Billing::Account.find(1, :include => :firm)
- assert_kind_of MyApplication::Business::Firm, account.instance_variable_get('@firm')
assert_kind_of MyApplication::Business::Firm, account.firm
end
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index 6ac3e3fc56..fb050c3e52 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -64,6 +64,10 @@ class NamedScopeTest < ActiveRecord::TestCase
assert Reply.scopes.include?(:base)
assert_equal Reply.find(:all), Reply.base
end
+
+ def test_classes_dont_inherit_subclasses_scopes
+ assert !ActiveRecord::Base.scopes.include?(:base)
+ end
def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
assert !Topic.find(:all, :conditions => {:approved => true}).empty?
@@ -141,26 +145,26 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal 1, Topic.multiple_extensions.extension_one
end
- def test_has_many_associations_have_access_to_named_scopes
+ def test_has_many_associations_have_access_to_scopes
assert_not_equal Post.containing_the_letter_a, authors(:david).posts
assert !Post.containing_the_letter_a.empty?
assert_equal authors(:david).posts & Post.containing_the_letter_a, authors(:david).posts.containing_the_letter_a
end
- def test_named_scope_with_STI
+ def test_scope_with_STI
assert_equal 3,Post.containing_the_letter_a.count
assert_equal 1,SpecialPost.containing_the_letter_a.count
end
- def test_has_many_through_associations_have_access_to_named_scopes
+ def test_has_many_through_associations_have_access_to_scopes
assert_not_equal Comment.containing_the_letter_e, authors(:david).comments
assert !Comment.containing_the_letter_e.empty?
assert_equal authors(:david).comments & Comment.containing_the_letter_e, authors(:david).comments.containing_the_letter_e
end
- def test_named_scopes_honor_current_scopes_from_when_defined
+ def test_scopes_honor_current_scopes_from_when_defined
assert !Post.ranked_by_comments.limit_by(5).empty?
assert !authors(:david).posts.ranked_by_comments.limit_by(5).empty?
assert_not_equal Post.ranked_by_comments.limit_by(5), authors(:david).posts.ranked_by_comments.limit_by(5)
@@ -236,7 +240,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_any_should_not_fire_query_if_named_scope_loaded
+ def test_any_should_not_fire_query_if_scope_loaded
topics = Topic.base
topics.collect # force load
assert_no_queries { assert topics.any? }
@@ -259,7 +263,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_many_should_not_fire_query_if_named_scope_loaded
+ def test_many_should_not_fire_query_if_scope_loaded
topics = Topic.base
topics.collect # force load
assert_no_queries { assert topics.many? }
@@ -276,27 +280,27 @@ class NamedScopeTest < ActiveRecord::TestCase
assert Topic.base.many?
end
- def test_should_build_on_top_of_named_scope
+ def test_should_build_on_top_of_scope
topic = Topic.approved.build({})
assert topic.approved
end
- def test_should_build_new_on_top_of_named_scope
+ def test_should_build_new_on_top_of_scope
topic = Topic.approved.new
assert topic.approved
end
- def test_should_create_on_top_of_named_scope
+ def test_should_create_on_top_of_scope
topic = Topic.approved.create({})
assert topic.approved
end
- def test_should_create_with_bang_on_top_of_named_scope
+ def test_should_create_with_bang_on_top_of_scope
topic = Topic.approved.create!({})
assert topic.approved
end
- def test_should_build_on_top_of_chained_named_scopes
+ def test_should_build_on_top_of_chained_scopes
topic = Topic.approved.by_lifo.build({})
assert topic.approved
assert_equal 'lifo', topic.author_name
@@ -310,7 +314,7 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_kind_of Topic, Topic.approved.sample
end
- def test_should_use_where_in_query_for_named_scope
+ def test_should_use_where_in_query_for_scope
assert_equal Developer.find_all_by_name('Jamis').to_set, Developer.find_all_by_id(Developer.jamises).to_set
end
@@ -361,7 +365,7 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).all.uniq
end
- def test_named_scopes_batch_finders
+ def test_scopes_batch_finders
assert_equal 3, Topic.approved.count
assert_queries(4) do
@@ -381,7 +385,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_named_scopes_with_reserved_names
+ def test_scopes_with_reserved_names
class << Topic
def public_method; end
public :public_method
@@ -400,7 +404,7 @@ class NamedScopeTest < ActiveRecord::TestCase
end
end
- def test_named_scopes_on_relations
+ def test_scopes_on_relations
# Topic.replied
approved_topics = Topic.scoped.approved.order('id DESC')
assert_equal topics(:fourth), approved_topics.first
@@ -409,19 +413,19 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_equal topics(:third), replied_approved_topics.first
end
- def test_index_on_named_scope
+ def test_index_on_scope
approved = Topic.approved.order('id ASC')
assert_equal topics(:second), approved[0]
assert approved.loaded?
end
- def test_nested_named_scopes_queries_size
+ def test_nested_scopes_queries_size
assert_queries(1) do
Topic.approved.by_lifo.replied.written_before(Time.now).all
end
end
- def test_named_scopes_are_cached_on_associations
+ def test_scopes_are_cached_on_associations
post = posts(:welcome)
assert_equal post.comments.containing_the_letter_e.object_id, post.comments.containing_the_letter_e.object_id
@@ -430,7 +434,7 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_no_queries { post.comments.containing_the_letter_e.all }
end
- def test_named_scopes_with_arguments_are_cached_on_associations
+ def test_scopes_with_arguments_are_cached_on_associations
post = posts(:welcome)
one = post.comments.limit_by(1).all
@@ -443,17 +447,17 @@ class NamedScopeTest < ActiveRecord::TestCase
assert_no_queries { post.comments.limit_by(2).all }
end
- def test_named_scopes_are_reset_on_association_reload
+ def test_scopes_are_reset_on_association_reload
post = posts(:welcome)
[:destroy_all, :reset, :delete_all].each do |method|
before = post.comments.containing_the_letter_e
- post.comments.send(method)
+ post.association(:comments).send(method)
assert before.object_id != post.comments.containing_the_letter_e.object_id, "AssociationCollection##{method} should reset the named scopes cache"
end
end
- def test_named_scoped_are_lazy_loaded_if_table_still_does_not_exist
+ def test_scoped_are_lazy_loaded_if_table_still_does_not_exist
assert_nothing_raised do
require "models/without_table"
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index ffcc7a081a..c57ab7ed28 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -147,6 +147,15 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
pirate.ship_attributes = { :id => "" }
assert_nothing_raised(ActiveRecord::RecordNotFound) { pirate.save! }
end
+
+ def test_first_and_array_index_zero_methods_return_the_same_value_when_nested_attributes_are_set_to_update_existing_record
+ Man.accepts_nested_attributes_for(:interests)
+ man = Man.create(:name => "John")
+ interest = man.interests.create :topic => 'gardning'
+ man = Man.find man.id
+ man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}]
+ assert_equal man.interests.first.topic, man.interests[0].topic
+ end
end
class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
@@ -298,7 +307,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true
@ship.delete
-
+
@pirate.reload.update_attributes(:update_only_ship_attributes => { :name => 'Mayflower' })
assert_not_nil @pirate.ship
@@ -451,7 +460,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
def test_should_not_destroy_the_associated_model_until_the_parent_is_saved
pirate = @ship.pirate
-
+
@ship.attributes = { :pirate_attributes => { :id => pirate.id, '_destroy' => true } }
assert_nothing_raised(ActiveRecord::RecordNotFound) { Pirate.find(pirate.id) }
@ship.save
@@ -859,7 +868,7 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase
end
class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@pirate = Pirate.create!(:catchphrase => "My baby takes tha mornin' train!")
@@ -899,7 +908,7 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe
end
class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@ship = Ship.create!(:name => "The good ship Dollypop")
@@ -909,16 +918,16 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
test "if association is not loaded and association record is saved and then in memory record attributes should be saved" do
@ship.parts_attributes=[{:id => @part.id,:name =>'Deck'}]
- assert_equal 1, @ship.parts.proxy_target.size
+ assert_equal 1, @ship.association(:parts).target.size
assert_equal 'Deck', @ship.parts[0].name
end
test "if association is not loaded and child doesn't change and I am saving a grandchild then in memory record should be used" do
@ship.parts_attributes=[{:id => @part.id,:trinkets_attributes =>[{:id => @trinket.id, :name => 'Ruby'}]}]
- assert_equal 1, @ship.parts.proxy_target.size
+ assert_equal 1, @ship.association(:parts).target.size
assert_equal 'Mast', @ship.parts[0].name
- assert_no_difference("@ship.parts[0].trinkets.proxy_target.size") do
- @ship.parts[0].trinkets.proxy_target.size
+ assert_no_difference("@ship.parts[0].association(:trinkets).target.size") do
+ @ship.parts[0].association(:trinkets).target.size
end
assert_equal 'Ruby', @ship.parts[0].trinkets[0].name
@ship.save
diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb
index de5fa140ba..6269437b14 100644
--- a/activerecord/test/cases/pooled_connections_test.rb
+++ b/activerecord/test/cases/pooled_connections_test.rb
@@ -137,4 +137,4 @@ class PooledConnectionsTest < ActiveRecord::TestCase
def add_record(name)
ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name }
end
-end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name
+end unless current_adapter?(:FrontBase) || in_memory_db?
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index 33916c4e46..53aefc7b58 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -63,7 +63,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) && SQLite3::Version::VERSION > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
+ elsif current_adapter?(:SQLite3Adapter) && SQLite3::VERSION > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
# 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/quoting_test.rb b/activerecord/test/cases/quoting_test.rb
index 2ef5b5a800..b87fb51d97 100644
--- a/activerecord/test/cases/quoting_test.rb
+++ b/activerecord/test/cases/quoting_test.rb
@@ -154,13 +154,13 @@ module ActiveRecord
end
def test_crazy_object
- crazy = Class.new { def to_s; 'lol' end }.new
+ crazy = Class.new { def to_yaml; 'lol' end }.new
assert_equal "'lol'", @quoter.quote(crazy, nil)
assert_equal "'lol'", @quoter.quote(crazy, Object.new)
end
def test_crazy_object_calls_quote_string
- crazy = Class.new { def to_s; 'lo\l' end }.new
+ crazy = Class.new { def to_yaml; 'lo\l' end }.new
assert_equal "'lo\\\\l'", @quoter.quote(crazy, nil)
assert_equal "'lo\\\\l'", @quoter.quote(crazy, Object.new)
end
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index 98011f40a4..e21109baae 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -6,13 +6,8 @@ require 'models/project'
require 'models/reader'
require 'models/person'
-# Dummy class methods to test implicit association scoping.
-def Comment.foo() find :first end
-def Project.foo() find :first end
-
-
class ReadOnlyTest < ActiveRecord::TestCase
- fixtures :posts, :comments, :developers, :projects, :developers_projects
+ fixtures :posts, :comments, :developers, :projects, :developers_projects, :people, :readers
def test_cant_save_readonly_record
dev = Developer.find(1)
@@ -49,15 +44,6 @@ class ReadOnlyTest < ActiveRecord::TestCase
Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? }
end
-
- def test_habtm_find_readonly
- dev = Developer.find(1)
- assert !dev.projects.empty?
- assert dev.projects.all?(&:readonly?)
- assert dev.projects.find(:all).all?(&:readonly?)
- assert dev.projects.readonly(true).all?(&:readonly?)
- end
-
def test_has_many_find_readonly
post = Post.find(1)
assert !post.comments.empty?
@@ -71,6 +57,18 @@ class ReadOnlyTest < ActiveRecord::TestCase
assert !people.any?(&:readonly?)
end
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_by_id
+ assert !posts(:welcome).people.find(1).readonly?
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_first
+ assert !posts(:welcome).people.first.readonly?
+ end
+
+ def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_last
+ assert !posts(:welcome).people.last.readonly?
+ end
+
def test_readonly_scoping
Post.send(:with_scope, :find => { :conditions => '1=1' }) do
assert !Post.find(1).readonly?
@@ -102,7 +100,13 @@ class ReadOnlyTest < ActiveRecord::TestCase
end
def test_association_collection_method_missing_scoping_not_readonly
- assert !Developer.find(1).projects.foo.readonly?
- assert !Post.find(1).comments.foo.readonly?
+ developer = Developer.find(1)
+ project = Post.find(1)
+
+ assert !developer.projects.all_as_method.first.readonly?
+ assert !developer.projects.all_as_scope.first.readonly?
+
+ assert !project.comments.all_as_method.first.readonly?
+ assert !project.comments.all_as_scope.first.readonly?
end
end
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index c461bb401f..9529ae56b8 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -17,6 +17,7 @@ require 'models/book'
require 'models/subscriber'
require 'models/subscription'
require 'models/tag'
+require 'models/sponsor'
class ReflectionTest < ActiveRecord::TestCase
include ActiveRecord::Reflection
@@ -136,11 +137,11 @@ class ReflectionTest < ActiveRecord::TestCase
def test_belongs_to_inferred_foreign_key_from_assoc_name
Company.belongs_to :foo
- assert_equal "foo_id", Company.reflect_on_association(:foo).primary_key_name
+ assert_equal "foo_id", Company.reflect_on_association(:foo).foreign_key
Company.belongs_to :bar, :class_name => "Xyzzy"
- assert_equal "bar_id", Company.reflect_on_association(:bar).primary_key_name
+ assert_equal "bar_id", Company.reflect_on_association(:bar).foreign_key
Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id"
- assert_equal "xyzzy_id", Company.reflect_on_association(:baz).primary_key_name
+ assert_equal "xyzzy_id", Company.reflect_on_association(:baz).foreign_key
end
def test_association_reflection_in_modules
@@ -187,8 +188,8 @@ class ReflectionTest < ActiveRecord::TestCase
def test_reflection_of_all_associations
# FIXME these assertions bust a lot
- assert_equal 37, Firm.reflect_on_all_associations.size
- assert_equal 27, Firm.reflect_on_all_associations(:has_many).size
+ assert_equal 36, Firm.reflect_on_all_associations.size
+ assert_equal 26, Firm.reflect_on_all_associations(:has_many).size
assert_equal 10, Firm.reflect_on_all_associations(:has_one).size
assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size
end
@@ -243,6 +244,7 @@ class ReflectionTest < ActiveRecord::TestCase
# Normal association
assert_equal "id", Author.reflect_on_association(:posts).association_primary_key.to_s
assert_equal "name", Author.reflect_on_association(:essay).association_primary_key.to_s
+ assert_equal "id", Tagging.reflect_on_association(:taggable).association_primary_key.to_s
# Through association (uses the :primary_key option from the source reflection)
assert_equal "nick", Author.reflect_on_association(:subscribers).association_primary_key.to_s
@@ -255,6 +257,11 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s
end
+ def test_foreign_type
+ assert_equal "sponsorable_type", Sponsor.reflect_on_association(:sponsorable).foreign_type.to_s
+ assert_equal "sponsorable_type", Sponsor.reflect_on_association(:thing).foreign_type.to_s
+ end
+
def test_collection_association
assert Pirate.reflect_on_association(:birds).collection?
assert Pirate.reflect_on_association(:parrots).collection?
@@ -292,6 +299,18 @@ class ReflectionTest < ActiveRecord::TestCase
assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true, :validate => false }, Firm).validate?
end
+ def test_foreign_key
+ assert_equal "author_id", Author.reflect_on_association(:posts).foreign_key.to_s
+ assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s
+ end
+
+ def test_primary_key_name
+ assert_deprecated do
+ assert_equal "author_id", Author.reflect_on_association(:posts).primary_key_name.to_s
+ assert_equal "category_id", Post.reflect_on_association(:categorizations).primary_key_name.to_s
+ end
+ end
+
private
def assert_reflection(klass, association, options)
assert reflection = klass.reflect_on_association(association)
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index 1f43515558..7369aaea1d 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -152,7 +152,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
Developer.where('salary = 80000').scoping do
Developer.limit(10).scoping do
devs = Developer.scoped
- assert_equal '(salary = 80000)', devs.arel.send(:where_clauses).join(' AND ')
+ assert_match '(salary = 80000)', devs.arel.to_sql
assert_equal 10, devs.taken
end
end
@@ -259,7 +259,8 @@ class HasManyScopingTest< ActiveRecord::TestCase
end
def test_should_default_scope_on_associations_is_overriden_by_association_conditions
- assert_equal [], people(:michael).fixed_bad_references
+ reference = references(:michael_unicyclist).becomes(BadReference)
+ assert_equal [reference], people(:michael).fixed_bad_references
end
def test_should_maintain_default_scope_on_eager_loaded_associations
@@ -422,7 +423,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal expected, received
end
- def test_named_scope_overwrites_default
+ def test_scope_overwrites_default
expected = Developer.find(:all, :order => 'salary DESC, name DESC').collect { |dev| dev.name }
received = DeveloperOrderedBySalary.by_name.find(:all).collect { |dev| dev.name }
assert_equal expected, received
@@ -485,4 +486,21 @@ class DefaultScopingTest < ActiveRecord::TestCase
posts_offset_limit = Post.offset(2).limit(3)
assert_equal posts_limit_offset, posts_offset_limit
end
+
+ def test_create_with_merge
+ aaron = PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20).merge(
+ PoorDeveloperCalledJamis.create_with(:name => 'Aaron')).new
+ assert_equal 20, aaron.salary
+ assert_equal 'Aaron', aaron.name
+
+ aaron = PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20).
+ create_with(:name => 'Aaron').new
+ assert_equal 20, aaron.salary
+ assert_equal 'Aaron', aaron.name
+ end
+
+ def test_create_with_reset
+ jamis = PoorDeveloperCalledJamis.create_with(:name => 'Aaron').create_with(nil).new
+ assert_equal 'Jamis', jamis.name
+ end
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 688fc70484..54537f11a8 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -27,6 +27,12 @@ class RelationTest < ActiveRecord::TestCase
assert_equal van.id, Minivan.where(:minivan_id => van).to_a.first.minivan_id
end
+ def test_do_not_double_quote_string_id_with_array
+ van = Minivan.last
+ assert van
+ assert_equal van, Minivan.where(:minivan_id => [van]).to_a.first
+ end
+
def test_bind_values
relation = Post.scoped
assert_equal [], relation.bind_values
@@ -36,7 +42,7 @@ class RelationTest < ActiveRecord::TestCase
assert_equal [], relation.bind_values
end
- def test_two_named_scopes_with_includes_should_not_drop_any_include
+ def test_two_scopes_with_includes_should_not_drop_any_include
car = Car.incl_engines.incl_tyres.first
assert_no_queries { car.tyres.length }
assert_no_queries { car.engines.length }
@@ -184,6 +190,10 @@ class RelationTest < ActiveRecord::TestCase
assert_equal [2, 4, 6, 8, 10], even_ids.sort
end
+ def test_joins_with_nil_argument
+ assert_nothing_raised { DependentFirm.joins(nil).first }
+ end
+
def test_finding_with_hash_conditions_on_joined_table
firms = DependentFirm.joins(:account).where({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a
assert_equal 1, firms.size
@@ -248,7 +258,7 @@ class RelationTest < ActiveRecord::TestCase
end
end
- def test_respond_to_class_methods_and_named_scopes
+ def test_respond_to_class_methods_and_scopes
assert DeveloperOrderedBySalary.scoped.respond_to?(:all_ordered_by_name)
assert Topic.scoped.respond_to?(:by_lifo)
end
@@ -275,8 +285,8 @@ class RelationTest < ActiveRecord::TestCase
assert posts.first.comments.first
end
- assert_queries(2) do
- posts = Post.preload(:comments).order('posts.id').to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
+ posts = Post.preload(:comments).to_a
assert posts.first.comments.first
end
@@ -285,13 +295,13 @@ class RelationTest < ActiveRecord::TestCase
assert posts.first.author
end
- assert_queries(2) do
- posts = Post.preload(:author).order('posts.id').to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
+ posts = Post.preload(:author).to_a
assert posts.first.author
end
- assert_queries(3) do
- posts = Post.preload(:author, :comments).order('posts.id').to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 3) do
+ posts = Post.preload(:author, :comments).to_a
assert posts.first.author
assert posts.first.comments.first
end
@@ -303,8 +313,8 @@ class RelationTest < ActiveRecord::TestCase
assert posts.first.comments.first
end
- assert_queries(2) do
- posts = Post.scoped.includes(:comments).order('posts.id')
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do
+ posts = Post.scoped.includes(:comments)
assert posts.first.comments.first
end
@@ -313,8 +323,8 @@ class RelationTest < ActiveRecord::TestCase
assert posts.first.author
end
- assert_queries(3) do
- posts = Post.includes(:author, :comments).order('posts.id').to_a
+ assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 3) do
+ posts = Post.includes(:author, :comments).to_a
assert posts.first.author
assert posts.first.comments.first
end
@@ -464,10 +474,17 @@ class RelationTest < ActiveRecord::TestCase
relation = relation.where(:name => david.name)
relation = relation.where(:name => 'Santiago')
relation = relation.where(:id => david.id)
- assert_equal [david], relation.all
+ assert_equal [], relation.all
+ end
+
+ def test_multi_where_ands_queries
+ relation = Author.unscoped
+ david = authors(:david)
+ sql = relation.where(:name => david.name).where(:name => 'Santiago').to_sql
+ assert_match('AND', sql)
end
- def test_find_all_with_multiple_ors
+ def test_find_all_with_multiple_should_use_and
david = authors(:david)
relation = [
{ :name => david.name },
@@ -476,7 +493,34 @@ class RelationTest < ActiveRecord::TestCase
].inject(Author.unscoped) do |memo, param|
memo.where(param)
end
- assert_equal [david], relation.all
+ assert_equal [], relation.all
+ end
+
+ def test_find_all_using_where_with_relation
+ david = authors(:david)
+ # switching the lines below would succeed in current rails
+ # assert_queries(2) {
+ assert_queries(1) {
+ relation = Author.where(:id => Author.where(:id => david.id))
+ assert_equal [david], relation.all
+ }
+ end
+
+ def test_find_all_using_where_with_relation_with_joins
+ david = authors(:david)
+ assert_queries(1) {
+ relation = Author.where(:id => Author.joins(:posts).where(:id => david.id))
+ assert_equal [david], relation.all
+ }
+ end
+
+
+ def test_find_all_using_where_with_relation_with_select_to_build_subquery
+ david = authors(:david)
+ assert_queries(1) {
+ relation = Author.where(:name => Author.where(:id => david.id).select(:name))
+ assert_equal [david], relation.all
+ }
end
def test_exists
@@ -535,17 +579,17 @@ class RelationTest < ActiveRecord::TestCase
end
def test_relation_merging
- devs = Developer.where("salary >= 80000") & Developer.limit(2) & Developer.order('id ASC').where("id < 3")
+ devs = Developer.where("salary >= 80000").merge(Developer.limit(2)).merge(Developer.order('id ASC').where("id < 3"))
assert_equal [developers(:david), developers(:jamis)], devs.to_a
- dev_with_count = Developer.limit(1) & Developer.order('id DESC') & Developer.select('developers.*')
+ dev_with_count = Developer.limit(1).merge(Developer.order('id DESC')).merge(Developer.select('developers.*'))
assert_equal [developers(:poor_jamis)], dev_with_count.to_a
end
def test_relation_merging_with_eager_load
relations = []
- relations << (Post.order('comments.id DESC') & Post.eager_load(:last_comment) & Post.scoped)
- relations << (Post.eager_load(:last_comment) & Post.order('comments.id DESC') & Post.scoped)
+ 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.each do |posts|
post = posts.find { |p| p.id == 1 }
@@ -554,18 +598,20 @@ class RelationTest < ActiveRecord::TestCase
end
def test_relation_merging_with_locks
- devs = Developer.lock.where("salary >= 80000").order("id DESC") & Developer.limit(2)
+ devs = Developer.lock.where("salary >= 80000").order("id DESC").merge(Developer.limit(2))
assert_present devs.locked
end
def test_relation_merging_with_preload
- [Post.scoped & Post.preload(:author), Post.preload(:author) & Post.scoped].each do |posts|
- assert_queries(2) { assert posts.first.author }
+ ActiveRecord::IdentityMap.without do
+ [Post.scoped.merge(Post.preload(:author)), Post.preload(:author).merge(Post.scoped)].each do |posts|
+ assert_queries(2) { assert posts.first.author }
+ end
end
end
def test_relation_merging_with_joins
- comments = Comment.joins(:post).where(:body => 'Thank you for the welcome') & Post.where(:body => 'Such a lovely day')
+ comments = Comment.joins(:post).where(:body => 'Thank you for the welcome').merge(Post.where(:body => 'Such a lovely day'))
assert_equal 1, comments.count
end
@@ -630,6 +676,14 @@ class RelationTest < ActiveRecord::TestCase
def test_any
posts = Post.scoped
+ # 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
+ # in Arel::Visitors::ToSql to trigger a SHOW TABLES query. Running that line here causes
+ # the SHOW TABLES result to be cached so we don't have to do it again in the block.
+ #
+ # This is obviously a rubbish fix but it's the best I can come up with for now...
+ posts.where(:id => nil).any?
+
assert_queries(3) do
assert posts.any? # Uses COUNT()
assert ! posts.where(:id => nil).any?
@@ -754,7 +808,7 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 'zyke', FastCar.order('name desc').find(:first, :order => 'id').name
end
- def test_default_scope_order_with_named_scope_order
+ def test_default_scope_order_with_scope_order
assert_equal 'zyke', CoolCar.order_using_new_style.limit(1).first.name
assert_equal 'zyke', CoolCar.order_using_old_style.limit(1).first.name
assert_equal 'zyke', FastCar.order_using_new_style.limit(1).first.name
@@ -788,4 +842,12 @@ class RelationTest < ActiveRecord::TestCase
assert_equal [rails_author], [rails_author] & relation
assert_equal [rails_author], relation & [rails_author]
end
+
+ def test_removing_limit_with_options
+ assert_not_equal 1, Post.limit(1).all(:limit => nil).count
+ end
+
+ def test_primary_key
+ assert_equal "id", Post.scoped.primary_key
+ end
end
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
index 25dbcc9fc2..677d659f39 100644
--- a/activerecord/test/cases/serialization_test.rb
+++ b/activerecord/test/cases/serialization_test.rb
@@ -23,6 +23,12 @@ class SerializationTest < ActiveRecord::TestCase
@contact = Contact.new(@contact_attributes)
end
+ def test_serialized_init_with
+ topic = Topic.allocate
+ topic.init_with('attributes' => { 'content' => '--- foo' })
+ assert_equal 'foo', topic.content
+ end
+
def test_to_xml
xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb
index 6f1c170a0c..cee5ddd003 100644
--- a/activerecord/test/cases/session_store/session_test.rb
+++ b/activerecord/test/cases/session_store/session_test.rb
@@ -5,7 +5,7 @@ require 'active_record/session_store'
module ActiveRecord
class SessionStore
class SessionTest < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints? && ActiveRecord::Base.connection.supports_ddl_transactions?
def setup
super
@@ -60,6 +60,7 @@ module ActiveRecord
end
def test_loaded?
+ Session.create_table!
s = Session.new
assert !s.loaded?, 'session is not loaded'
end
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 70c098bc6d..1c21f0f3b6 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -140,4 +140,34 @@ class TimestampTest < ActiveRecord::TestCase
ensure
Toy.belongs_to :pet
end
+
+ def test_timestamp_attributes_for_create
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_create), [:created_at, :created_on]
+ end
+
+ def test_timestamp_attributes_for_update
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_update), [:updated_at, :updated_on]
+ end
+
+ def test_all_timestamp_attributes
+ toy = Toy.first
+ assert_equal toy.send(:all_timestamp_attributes), [:created_at, :created_on, :updated_at, :updated_on]
+ end
+
+ def test_timestamp_attributes_for_create_in_model
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_create_in_model), [:created_at]
+ end
+
+ def test_timestamp_attributes_for_update_in_model
+ toy = Toy.first
+ assert_equal toy.send(:timestamp_attributes_for_update_in_model), [:updated_at]
+ end
+
+ def test_all_timestamp_attributes_in_model
+ toy = Toy.first
+ assert_equal toy.send(:all_timestamp_attributes_in_model), [:created_at, :updated_at]
+ end
end
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index b0ccd71836..110a18772f 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -370,23 +370,23 @@ class TransactionTest < ActiveRecord::TestCase
assert topic_2.save
@first.save
@second.destroy
- assert_equal true, topic_1.persisted?
+ assert topic_1.persisted?, 'persisted'
assert_not_nil topic_1.id
- assert_equal true, topic_2.persisted?
+ assert topic_2.persisted?, 'persisted'
assert_not_nil topic_2.id
- assert_equal true, @first.persisted?
+ assert @first.persisted?, 'persisted'
assert_not_nil @first.id
- assert_equal true, @second.destroyed?
+ assert @second.destroyed?, 'destroyed'
raise ActiveRecord::Rollback
end
- assert_equal false, topic_1.persisted?
+ assert !topic_1.persisted?, 'not persisted'
assert_nil topic_1.id
- assert_equal false, topic_2.persisted?
+ assert !topic_2.persisted?, 'not persisted'
assert_nil topic_2.id
- assert_equal true, @first.persisted?
+ assert @first.persisted?, 'persisted'
assert_not_nil @first.id
- assert_equal false, @second.destroyed?
+ assert !@second.destroyed?, 'not destroyed'
end
if current_adapter?(:PostgreSQLAdapter) && defined?(PGconn::PQTRANS_IDLE)
diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb
index 23ad10f3f9..f85fb4e5da 100644
--- a/activerecord/test/cases/unconnected_test.rb
+++ b/activerecord/test/cases/unconnected_test.rb
@@ -4,7 +4,7 @@ class TestRecord < ActiveRecord::Base
end
class TestUnconnectedAdapter < ActiveRecord::TestCase
- self.use_transactional_fixtures = false
+ self.use_transactional_fixtures = false unless supports_savepoints?
def setup
@underlying = ActiveRecord::Base.connection
@@ -14,6 +14,7 @@ class TestUnconnectedAdapter < ActiveRecord::TestCase
def teardown
@underlying = nil
ActiveRecord::Base.establish_connection(@specification)
+ load_schema if in_memory_db?
end
def test_connection_no_longer_established
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 679d67553b..b4f3dd034c 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -6,19 +6,6 @@ require 'models/warehouse_thing'
require 'models/guid'
require 'models/event'
-# The following methods in Topic are used in test_conditional_validation_*
-class Topic
- has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
- has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
-end
-
-class UniqueReply < Reply
- validates_uniqueness_of :content, :scope => 'parent_id'
-end
-
-class SillyUniqueReply < UniqueReply
-end
-
class Wizard < ActiveRecord::Base
self.abstract_class = true
diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb
index 2003e25e35..a6074b23e7 100644
--- a/activerecord/test/cases/xml_serialization_test.rb
+++ b/activerecord/test/cases/xml_serialization_test.rb
@@ -262,4 +262,10 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase
assert array.include? 'github'
end
+ def test_should_support_aliased_attributes
+ xml = Author.select("name as firstname").to_xml
+ array = Hash.from_xml(xml)['authors']
+ assert_equal array.size, array.select { |author| author.has_key? 'firstname' }.size
+ end
+
end
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
index 0fc9918744..0b54c309d1 100644
--- a/activerecord/test/cases/yaml_serialization_test.rb
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -17,4 +17,30 @@ class YamlSerializationTest < ActiveRecord::TestCase
t = YAML.load YAML.dump topic
assert_equal topic, t
end
+
+ def test_encode_with_coder
+ topic = Topic.first
+ coder = {}
+ topic.encode_with coder
+ assert_equal({'attributes' => topic.attributes}, coder)
+ end
+
+ begin
+ require 'psych'
+
+ def test_psych_roundtrip
+ topic = Topic.first
+ assert topic
+ t = Psych.load Psych.dump topic
+ assert_equal topic, t
+ end
+
+ def test_psych_roundtrip_new_object
+ topic = Topic.new
+ assert topic
+ t = Psych.load Psych.dump topic
+ assert_equal topic.attributes, t.attributes
+ end
+ rescue LoadError
+ end
end
diff --git a/activerecord/test/connections/native_sqlite3/connection.rb b/activerecord/test/connections/native_sqlite3/connection.rb
index c517c2375e..c2aff5551f 100644
--- a/activerecord/test/connections/native_sqlite3/connection.rb
+++ b/activerecord/test/connections/native_sqlite3/connection.rb
@@ -3,21 +3,12 @@ require_dependency 'models/course'
require 'logger'
ActiveRecord::Base.logger = Logger.new("debug.log")
-class SqliteError < StandardError
-end
-
BASE_DIR = FIXTURES_ROOT
sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3"
sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3"
def make_connection(clazz, db_file)
ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => db_file, :timeout => 5000 } }
- unless File.exist?(db_file)
- puts "SQLite3 database not found at #{db_file}. Rebuilding it."
- sqlite_command = %Q{sqlite3 "#{db_file}" "create table a (a integer); drop table a;"}
- puts "Executing '#{sqlite_command}'"
- raise SqliteError.new("Seems that there is no sqlite3 executable available") unless system(sqlite_command)
- end
clazz.establish_connection(clazz.name)
end
diff --git a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb b/activerecord/test/connections/native_sqlite3/in_memory_connection.rb
deleted file mode 100644
index 6aba9719bb..0000000000
--- a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-print "Using native SQLite3\n"
-require_dependency 'models/course'
-require 'logger'
-ActiveRecord::Base.logger = Logger.new("debug.log")
-
-class SqliteError < StandardError
-end
-
-def make_connection(clazz, db_definitions_file)
- clazz.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
- File.read(SCHEMA_ROOT + "/#{db_definitions_file}").split(';').each do |command|
- clazz.connection.execute(command) unless command.strip.empty?
- end
-end
-
-make_connection(ActiveRecord::Base, 'sqlite.sql')
-make_connection(Course, 'sqlite2.sql')
-load(SCHEMA_ROOT + "/schema.rb")
diff --git a/activerecord/test/connections/native_sqlite3_mem/connection.rb b/activerecord/test/connections/native_sqlite3_mem/connection.rb
new file mode 100644
index 0000000000..14e10900d1
--- /dev/null
+++ b/activerecord/test/connections/native_sqlite3_mem/connection.rb
@@ -0,0 +1,19 @@
+# This file connects to an in-memory SQLite3 database, which is a very fast way to run the tests.
+# The downside is that disconnect from the database results in the database effectively being
+# wiped. For this reason, pooled_connections_test.rb is disabled when using an in-memory database.
+
+print "Using native SQLite3 (in memory)\n"
+require_dependency 'models/course'
+require 'logger'
+ActiveRecord::Base.logger = Logger.new("debug.log")
+
+class SqliteError < StandardError
+end
+
+def make_connection(clazz)
+ ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => ':memory:' } }
+ clazz.establish_connection(clazz.name)
+end
+
+make_connection(ActiveRecord::Base)
+make_connection(Course)
diff --git a/activerecord/test/fixtures/companies.yml b/activerecord/test/fixtures/companies.yml
index ffaa097686..a982d3921d 100644
--- a/activerecord/test/fixtures/companies.yml
+++ b/activerecord/test/fixtures/companies.yml
@@ -12,6 +12,7 @@ first_firm:
type: Firm
name: 37signals
ruby_type: Firm
+ firm_id: 1
second_client:
id: 3
diff --git a/activerecord/test/fixtures/dashboards.yml b/activerecord/test/fixtures/dashboards.yml
index e75bf46e6c..a4c7e0d309 100644
--- a/activerecord/test/fixtures/dashboards.yml
+++ b/activerecord/test/fixtures/dashboards.yml
@@ -1,3 +1,6 @@
cool_first:
dashboard_id: d1
- name: my_dashboard \ No newline at end of file
+ name: my_dashboard
+second:
+ dashboard_id: d2
+ name: second
diff --git a/activerecord/test/fixtures/posts.yml b/activerecord/test/fixtures/posts.yml
index 264ca164f0..7298096025 100644
--- a/activerecord/test/fixtures/posts.yml
+++ b/activerecord/test/fixtures/posts.yml
@@ -5,6 +5,7 @@ welcome:
body: Such a lovely day
comments_count: 2
taggings_count: 1
+ tags_count: 1
type: Post
thinking:
@@ -14,6 +15,7 @@ thinking:
body: Like I hopefully always am
comments_count: 1
taggings_count: 1
+ tags_count: 1
type: SpecialPost
authorless:
diff --git a/activerecord/test/fixtures/ships.yml b/activerecord/test/fixtures/ships.yml
index 137055aad1..df914262b3 100644
--- a/activerecord/test/fixtures/ships.yml
+++ b/activerecord/test/fixtures/ships.yml
@@ -1,5 +1,6 @@
black_pearl:
name: "Black Pearl"
+ pirate: blackbeard
interceptor:
id: 2
name: "Interceptor"
diff --git a/activerecord/test/fixtures/speedometers.yml b/activerecord/test/fixtures/speedometers.yml
index 6a471aba0a..e12398f0c4 100644
--- a/activerecord/test/fixtures/speedometers.yml
+++ b/activerecord/test/fixtures/speedometers.yml
@@ -1,4 +1,8 @@
cool_first:
speedometer_id: s1
name: my_speedometer
- dashboard_id: d1 \ No newline at end of file
+ dashboard_id: d1
+second:
+ speedometer_id: s2
+ name: second
+ dashboard_id: d2
diff --git a/activerecord/test/fixtures/subscribers.yml b/activerecord/test/fixtures/subscribers.yml
index 9ffb4a156f..c6a8c2fa24 100644
--- a/activerecord/test/fixtures/subscribers.yml
+++ b/activerecord/test/fixtures/subscribers.yml
@@ -5,3 +5,7 @@ first:
second:
nick: webster132
name: David Heinemeier Hansson
+
+thrid:
+ nick: swistak
+ name: Marcin Raczkowski \ No newline at end of file
diff --git a/activerecord/test/fixtures/traffic_lights.yml b/activerecord/test/fixtures/traffic_lights.yml
new file mode 100644
index 0000000000..6dabd53474
--- /dev/null
+++ b/activerecord/test/fixtures/traffic_lights.yml
@@ -0,0 +1,6 @@
+uk:
+ location: UK
+ state:
+ - Green
+ - Red
+ - Orange
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index 43bfd93e60..f362f70dec 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -26,6 +26,12 @@ class Author < ActiveRecord::Base
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 :first_posts
+ has_many :comments_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc'
+
+ has_one :first_post
+ has_one :comment_on_first_post, :through => :first_post, :source => :comments, :order => 'posts.id desc, comments.id asc'
+
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' }
@@ -72,6 +78,11 @@ class Author < ActiveRecord::Base
has_many :categorizations
has_many :categories, :through => :categorizations
+ has_many :named_categories, :through => :categorizations
+
+ has_many :special_categorizations
+ 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' }
diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb
index 9eefc5803a..7178bb0d00 100644
--- a/activerecord/test/models/bulb.rb
+++ b/activerecord/test/models/bulb.rb
@@ -1,7 +1,14 @@
class Bulb < ActiveRecord::Base
-
+
default_scope :conditions => {:name => 'defaulty' }
-
+
belongs_to :car
+ attr_reader :scoped_methods_after_initialize
+
+ after_initialize :record_scoped_methods_after_initialize
+ def record_scoped_methods_after_initialize
+ @scoped_methods_after_initialize = self.class.scoped_methods.dup
+ end
+
end
diff --git a/activerecord/test/models/categorization.rb b/activerecord/test/models/categorization.rb
index 8e2fa96498..09489b8ea4 100644
--- a/activerecord/test/models/categorization.rb
+++ b/activerecord/test/models/categorization.rb
@@ -1,7 +1,20 @@
class Categorization < ActiveRecord::Base
belongs_to :post
belongs_to :category
+ belongs_to :named_category, :class_name => 'Category', :foreign_key => :named_category_name, :primary_key => :name
belongs_to :author
has_many :post_taggings, :through => :author, :source => :taggings
+
+ belongs_to :author_using_custom_pk, :class_name => 'Author', :foreign_key => :author_id, :primary_key => :author_address_extra_id
+ has_many :authors_using_custom_pk, :class_name => 'Author', :foreign_key => :id, :primary_key => :category_id
+end
+
+class SpecialCategorization < ActiveRecord::Base
+ self.table_name = 'categorizations'
+
+ default_scope where(:special => true)
+
+ belongs_to :author
+ belongs_to :category
end
diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb
index 95825c72ef..02b85fd38a 100644
--- a/activerecord/test/models/category.rb
+++ b/activerecord/test/models/category.rb
@@ -22,9 +22,12 @@ class Category < ActiveRecord::Base
end
has_many :categorizations
- has_many :authors, :through => :categorizations, :select => 'authors.*, categorizations.post_id'
-
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'
+
+ scope :general, :conditions => { :name => 'General' }
end
class SpecialCategory < Category
diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb
index 83d6b1b15a..24a65b0f2f 100644
--- a/activerecord/test/models/club.rb
+++ b/activerecord/test/models/club.rb
@@ -1,4 +1,5 @@
class Club < ActiveRecord::Base
+ has_one :membership
has_many :memberships
has_many :members, :through => :memberships
has_many :current_memberships
diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb
index 1a3fb42b66..2a4c37089a 100644
--- a/activerecord/test/models/comment.rb
+++ b/activerecord/test/models/comment.rb
@@ -1,6 +1,7 @@
class Comment < ActiveRecord::Base
scope :limit_by, lambda {|l| limit(l) }
scope :containing_the_letter_e, :conditions => "comments.body LIKE '%e%'"
+ scope :not_again, where("comments.body NOT LIKE '%again%'")
scope :for_first_post, :conditions => { :post_id => 1 }
scope :for_first_author,
:joins => :post,
@@ -16,6 +17,11 @@ class Comment < ActiveRecord::Base
def self.search_by_type(q)
self.find(:all, :conditions => ["#{QUOTED_TYPE} = ?", q])
end
+
+ def self.all_as_method
+ all
+ end
+ scope :all_as_scope, {}
end
class SpecialComment < Comment
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index ee5f77b613..e0b30efd51 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -38,7 +38,9 @@ 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' )"
+ "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )",
+ :before_remove => :log_before_remove,
+ :after_remove => :log_after_remove
has_many :unsorted_clients, :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"
@@ -46,20 +48,16 @@ class Firm < Company
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_with_interpolated_conditions, :class_name => "Client", :conditions => 'rating > #{rating}'
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 => 'SELECT * FROM companies WHERE client_of = #{id}'
- has_many :clients_using_multiline_sql, :class_name => "Client", :finder_sql => '
- SELECT
- companies.*
- FROM companies WHERE companies.client_of = #{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 => 'SELECT * FROM companies WHERE client_of = #{id}',
- :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = #{id}'
+ :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 => 'SELECT * FROM companies WHERE client_of = #{id}',
- :counter_sql => 'SELECT 0 FROM companies WHERE client_of = #{id}'
+ :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'
@@ -88,6 +86,19 @@ class Firm < Company
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
+
+ def log
+ @log ||= []
+ end
+
+ private
+ def log_before_remove(record)
+ log << "before_remove#{record.id}"
+ end
+
+ def log_after_remove(record)
+ log << "after_remove#{record.id}"
+ end
end
class DependentFirm < Company
@@ -109,6 +120,9 @@ class Client < Company
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" }
+ has_many :accounts, :through => :firm
+ belongs_to :account
# Record destruction so we can test whether firm.clients.clear has
# is calling client.destroy, deleting from the database, or setting
diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb
index 975a885331..e081eee661 100644
--- a/activerecord/test/models/contact.rb
+++ b/activerecord/test/models/contact.rb
@@ -1,8 +1,14 @@
class Contact < ActiveRecord::Base
+ establish_connection(:adapter => 'fake')
+
+ connection.tables = ['contacts']
+ connection.primary_keys = {
+ 'contacts' => 'id'
+ }
+
# mock out self.columns so no pesky db is needed for these tests
def self.column(name, sql_type = nil, options = {})
- @columns ||= []
- @columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options[:null])
+ connection.merge_column('contacts', name, sql_type, options)
end
column :name, :string
diff --git a/activerecord/test/models/contract.rb b/activerecord/test/models/contract.rb
index 606c99cd4e..94fd48e12a 100644
--- a/activerecord/test/models/contract.rb
+++ b/activerecord/test/models/contract.rb
@@ -1,4 +1,4 @@
class Contract < ActiveRecord::Base
belongs_to :company
belongs_to :developer
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb
index e258ccdb6c..777f6b5ba0 100644
--- a/activerecord/test/models/customer.rb
+++ b/activerecord/test/models/customer.rb
@@ -70,4 +70,4 @@ class Fullname
def to_s
"#{first} #{last.upcase}"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/joke.rb b/activerecord/test/models/joke.rb
index 3978abc2ba..d7f01e59e6 100644
--- a/activerecord/test/models/joke.rb
+++ b/activerecord/test/models/joke.rb
@@ -1,3 +1,7 @@
class Joke < ActiveRecord::Base
set_table_name 'funny_jokes'
end
+
+class GoodJoke < ActiveRecord::Base
+ set_table_name 'funny_jokes'
+end
diff --git a/activerecord/test/models/lesson.rb b/activerecord/test/models/lesson.rb
new file mode 100644
index 0000000000..4c88153068
--- /dev/null
+++ b/activerecord/test/models/lesson.rb
@@ -0,0 +1,11 @@
+class LessonError < Exception
+end
+
+class Lesson < ActiveRecord::Base
+ has_and_belongs_to_many :students
+ before_destroy :ensure_no_students
+
+ def ensure_no_students
+ raise LessonError unless students.empty?
+ end
+end
diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb
index fbf0b80164..991e0e051f 100644
--- a/activerecord/test/models/member.rb
+++ b/activerecord/test/models/member.rb
@@ -1,9 +1,10 @@
class Member < ActiveRecord::Base
has_one :current_membership
- has_many :memberships
+ has_one :membership
has_many :fellow_members, :through => :club, :source => :members
has_one :club, :through => :current_membership
- has_one :favourite_club, :through => :memberships, :conditions => ["memberships.favourite = ?", true], :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 :sponsor, :as => :sponsorable
has_one :sponsor_club, :through => :sponsor
has_one :member_detail
@@ -20,4 +21,10 @@ class Member < ActiveRecord::Base
has_many :organization_member_details_2, :through => :organization, :source => :member_details
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 :clubs, :through => :current_memberships
end
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index 5a5b6f9626..ad59d12672 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -1,17 +1,24 @@
class Person < ActiveRecord::Base
has_many :readers
+ has_one :reader
+
has_many :posts, :through => :readers
has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, :conditions => 'comments.id is null'
has_many :references
has_many :bad_references
has_many :fixed_bad_references, :conditions => { :favourite => true }, :class_name => 'BadReference'
- has_many :jobs, :through => :references
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 :jobs, :through => :references
+ has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy
+ has_many :jobs_with_dependent_delete_all, :source => :job, :through => :references, :dependent => :delete_all
+ has_many :jobs_with_dependent_nullify, :source => :job, :through => :references, :dependent => :nullify
+
belongs_to :primary_contact, :class_name => 'Person'
has_many :agents, :class_name => 'Person', :foreign_key => 'primary_contact_id'
+ has_many :agents_of_agents, :through => :agents, :source => :agents
belongs_to :number1_fan, :class_name => 'Person'
has_many :agents_posts, :through => :agents, :source => :posts
@@ -20,3 +27,24 @@ class Person < ActiveRecord::Base
scope :males, :conditions => { :gender => 'M' }
scope :females, :conditions => { :gender => 'F' }
end
+
+class PersonWithDependentDestroyJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :destroy
+end
+
+class PersonWithDependentDeleteAllJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :delete_all
+end
+
+class PersonWithDependentNullifyJobs < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_many :references, :foreign_key => :person_id
+ has_many :jobs, :source => :job, :through => :references, :dependent => :nullify
+end
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index f2c45053e7..0d3f62bb33 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -34,6 +34,8 @@ 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 :bulb, :foreign_key => :car_id
+
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? }
accepts_nested_attributes_for :update_only_ship, :update_only => true
@@ -78,3 +80,7 @@ class Pirate < ActiveRecord::Base
ship_log << "#{callback}_#{record.class.name.downcase}_#{record.id || '<new>'}"
end
end
+
+class DestructivePirate < Pirate
+ has_one :dependent_ship, :class_name => 'Ship', :foreign_key => :pirate_id, :dependent => :destroy
+end
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index e9c8c02e45..b39325f949 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -38,9 +38,11 @@ class Post < ActiveRecord::Base
end
has_many :author_favorites, :through => :author
+ has_many :author_categorizations, :through => :author, :source => :categorizations
+ has_many :author_addresses, :through => :author
has_many :comments_with_interpolated_conditions, :class_name => 'Comment',
- :conditions => ['#{"#{aliased_table_name}." rescue ""}body = ?', 'Thank you for the welcome']
+ :conditions => proc { ["#{"#{aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome'] }
has_one :very_special_comment
has_one :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post
@@ -55,11 +57,21 @@ class Post < ActiveRecord::Base
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings do
def add_joins_and_select
- find :all, :select => 'tags.*, authors.id as author_id', :include => false,
+ find :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'
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 :funky_tags, :through => :taggings, :source => :tag
has_many :super_tags, :through => :taggings
@@ -77,9 +89,21 @@ class Post < ActiveRecord::Base
has_many :categorizations, :foreign_key => :category_id
has_many :authors, :through => :categorizations
+ has_many :categorizations_using_author_id, :primary_key => :author_id, :foreign_key => :post_id, :class_name => 'Categorization'
+ has_many :authors_using_author_id, :through => :categorizations_using_author_id, :source => :author
+
+ has_many :taggings_using_author_id, :primary_key => :author_id, :as => :taggable, :class_name => 'Tagging'
+ has_many :tags_using_author_id, :through => :taggings_using_author_id, :source => :tag
+
+ has_many :standard_categorizations, :class_name => 'Categorization', :foreign_key => :post_id
+ has_many :author_using_custom_pk, :through => :standard_categorizations
+ has_many :authors_using_custom_pk, :through => :standard_categorizations
+ has_many :named_categories, :through => :standard_categorizations
+
has_many :readers
has_many :readers_with_person, :include => :person, :class_name => "Reader"
has_many :people, :through => :readers
+ has_many :single_people, :through => :readers
has_many :people_with_callbacks, :source=>:person, :through => :readers,
:before_add => lambda {|owner, reader| log(:added, :before, reader.first_name) },
:after_add => lambda {|owner, reader| log(:added, :after, reader.first_name) },
@@ -127,3 +151,10 @@ class PostForAuthor < ActiveRecord::Base
cattr_accessor :selected_author
default_scope lambda { where(:author_id => PostForAuthor.selected_author) }
end
+
+class FirstPost < ActiveRecord::Base
+ self.table_name = 'posts'
+ default_scope where(:id => 1)
+ has_many :comments, :foreign_key => :post_id
+ has_one :comment, :foreign_key => :post_id
+end
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 416032cb75..efe1ce67da 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -7,14 +7,15 @@ class Project < ActiveRecord::Base
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 => '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 => '
- 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 => "DELETE FROM developers_projects WHERE project_id = \#{id} AND developer_id = \#{record.id}"
+ 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_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}"},
@@ -28,6 +29,10 @@ class Project < ActiveRecord::Base
@developers_log = []
end
+ def self.all_as_method
+ all
+ end
+ scope :all_as_scope, {}
end
class SpecialProject < Project
diff --git a/activerecord/test/models/reader.rb b/activerecord/test/models/reader.rb
index 27527bf566..0207a2bd92 100644
--- a/activerecord/test/models/reader.rb
+++ b/activerecord/test/models/reader.rb
@@ -1,4 +1,5 @@
class Reader < ActiveRecord::Base
belongs_to :post
- belongs_to :person
+ belongs_to :person, :inverse_of => :readers
+ belongs_to :single_person, :class_name => 'Person', :foreign_key => :person_id, :inverse_of => :reader
end
diff --git a/activerecord/test/models/reference.rb b/activerecord/test/models/reference.rb
index 87d4a71963..e33a0f2acc 100644
--- a/activerecord/test/models/reference.rb
+++ b/activerecord/test/models/reference.rb
@@ -3,6 +3,18 @@ class Reference < ActiveRecord::Base
belongs_to :job
has_many :agents_posts_authors, :through => :person
+
+ class << self
+ attr_accessor :make_comments
+ end
+
+ before_destroy :make_comments
+
+ def make_comments
+ if self.class.make_comments
+ person.update_attributes :comments => "Reference destroyed"
+ end
+ end
end
class BadReference < ActiveRecord::Base
diff --git a/activerecord/test/models/reply.rb b/activerecord/test/models/reply.rb
index 110d540120..6adfe0ae3c 100644
--- a/activerecord/test/models/reply.rb
+++ b/activerecord/test/models/reply.rb
@@ -10,6 +10,13 @@ class Reply < Topic
attr_accessible :title, :author_name, :author_email_address, :written_on, :content, :last_read, :parent_title
end
+class UniqueReply < Reply
+ validates_uniqueness_of :content, :scope => 'parent_id'
+end
+
+class SillyUniqueReply < UniqueReply
+end
+
class WrongReply < Reply
validate :errors_on_empty_content
validate :title_is_wrong_create, :on => :create
diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb
index 50c2c2d76c..aa4a3638fd 100644
--- a/activerecord/test/models/sponsor.rb
+++ b/activerecord/test/models/sponsor.rb
@@ -1,4 +1,7 @@
class Sponsor < ActiveRecord::Base
belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id"
belongs_to :sponsorable, :polymorphic => true
-end \ No newline at end of file
+ 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'}
+end
diff --git a/activerecord/test/models/student.rb b/activerecord/test/models/student.rb
new file mode 100644
index 0000000000..f459f2a9a3
--- /dev/null
+++ b/activerecord/test/models/student.rb
@@ -0,0 +1,3 @@
+class Student < ActiveRecord::Base
+ has_and_belongs_to_many :lessons
+end
diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb
index c6ff8d390b..17e627a60e 100644
--- a/activerecord/test/models/tagging.rb
+++ b/activerecord/test/models/tagging.rb
@@ -8,5 +8,7 @@ class Tagging < ActiveRecord::Base
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 :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/task.rb b/activerecord/test/models/task.rb
index ee0282c79b..e36989dd56 100644
--- a/activerecord/test/models/task.rb
+++ b/activerecord/test/models/task.rb
@@ -1,3 +1,5 @@
class Task < ActiveRecord::Base
-
+ def updated_at
+ ending
+ end
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index 6496f36f7e..6440dbe8ab 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -45,6 +45,10 @@ class Topic < ActiveRecord::Base
has_many :replies, :dependent => :destroy, :foreign_key => "parent_id"
has_many :replies_with_primary_key, :class_name => "Reply", :dependent => :destroy, :primary_key => "title", :foreign_key => "parent_title"
+
+ has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
+ has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id"
+
serialize :content
before_create :default_written_on
diff --git a/activerecord/test/models/traffic_light.rb b/activerecord/test/models/traffic_light.rb
new file mode 100644
index 0000000000..228f3f7bd4
--- /dev/null
+++ b/activerecord/test/models/traffic_light.rb
@@ -0,0 +1,3 @@
+class TrafficLight < ActiveRecord::Base
+ serialize :state, Array
+end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 5deb233f2d..bdadd0698b 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -113,8 +113,10 @@ ActiveRecord::Schema.define do
create_table :categorizations, :force => true do |t|
t.column :category_id, :integer
+ t.string :named_category_name
t.column :post_id, :integer
t.column :author_id, :integer
+ t.column :special, :boolean
end
create_table :citations, :force => true do |t|
@@ -145,6 +147,7 @@ ActiveRecord::Schema.define do
t.text :body, :null => false
end
t.string :type
+ t.integer :taggings_count, :default => 0
end
create_table :companies, :force => true do |t|
@@ -155,6 +158,7 @@ ActiveRecord::Schema.define do
t.string :name
t.integer :client_of
t.integer :rating, :default => 1
+ t.integer :account_id
end
add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index"
@@ -231,6 +235,10 @@ ActiveRecord::Schema.define do
t.string :name
end
+ create_table :cold_jokes, :force => true do |t|
+ t.string :name
+ end
+
create_table :goofy_string_id, :force => true, :id => false do |t|
t.string :id, :null => false
t.string :info
@@ -281,6 +289,15 @@ ActiveRecord::Schema.define do
t.integer :version, :null => false, :default => 0
end
+ create_table :lessons, :force => true do |t|
+ t.string :name
+ end
+
+ create_table :lessons_students, :id => false, :force => true do |t|
+ t.references :lesson
+ t.references :student
+ end
+
create_table :line_items, :force => true do |t|
t.integer :invoice_id
t.integer :amount
@@ -419,6 +436,8 @@ ActiveRecord::Schema.define do
t.string :gender, :limit => 1
t.references :number1_fan
t.integer :lock_version, :null => false, :default => 0
+ t.string :comments
+ t.timestamps
end
create_table :pets, :primary_key => :pet_id ,:force => true do |t|
@@ -447,6 +466,11 @@ ActiveRecord::Schema.define do
t.string :type
t.integer :comments_count, :default => 0
t.integer :taggings_count, :default => 0
+ t.integer :taggings_with_delete_all_count, :default => 0
+ t.integer :taggings_with_destroy_count, :default => 0
+ t.integer :tags_count, :default => 0
+ t.integer :tags_with_destroy_count, :default => 0
+ t.integer :tags_with_nullify_count, :default => 0
end
create_table :price_estimates, :force => true do |t|
@@ -516,6 +540,10 @@ ActiveRecord::Schema.define do
t.string :sponsorable_type
end
+ create_table :students, :force => true do |t|
+ t.string :name
+ end
+
create_table :subscribers, :force => true, :id => false do |t|
t.string :nick, :null => false
t.string :name
diff --git a/activeresource/MIT-LICENSE b/activeresource/MIT-LICENSE
index 1bf965ff1e..216b6e5ba0 100644
--- a/activeresource/MIT-LICENSE
+++ b/activeresource/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2006-2010 David Heinemeier Hansson
+Copyright (c) 2006-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activeresource/README.rdoc b/activeresource/README.rdoc
index 0aaad1d097..afa25e1676 100644
--- a/activeresource/README.rdoc
+++ b/activeresource/README.rdoc
@@ -95,7 +95,7 @@ Collections can also be requested in a similar fashion
#
# for GET http://api.people.com:3000/people.xml
#
- people = Person.find(:all)
+ people = Person.all
people.first # => <Person::xxx 'first' => 'Ryan' ...>
people.last # => <Person::xxx 'first' => 'Jim' ...>
diff --git a/activeresource/Rakefile b/activeresource/Rakefile
index cf01bc1389..42e450da66 100755
--- a/activeresource/Rakefile
+++ b/activeresource/Rakefile
@@ -19,7 +19,7 @@ namespace :test do
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
activesupport_path = "#{File.dirname(__FILE__)}/../activesupport/lib"
Dir.glob("test/**/*_test.rb").all? do |file|
- system(ruby, '-w', "-Ilib:test:#{activesupport_path}", file)
+ sh(ruby, '-w', "-Ilib:test:#{activesupport_path}", file)
end or raise "Failures"
end
end
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb
index d959fd103a..daa8962929 100644
--- a/activeresource/lib/active_resource/base.rb
+++ b/activeresource/lib/active_resource/base.rb
@@ -200,7 +200,7 @@ module ActiveResource
# an ActiveResource::MissingPrefixParam will be raised.
#
# class Comment < ActiveResource::Base
- # self.site = "http://someip.com/posts/:post_id/"
+ # self.site = "http://someip.com/posts/:post_id/"
# end
#
# Comment.find(1)
@@ -1095,7 +1095,7 @@ module ActiveResource
end
# Delegates to id in order to allow two resources of the same type and \id to work with something like:
- # [Person.find(1), Person.find(2)] & [Person.find(1), Person.find(4)] # => [Person.find(1)]
+ # [(a = Person.find 1), (b = Person.find 2)] & [(c = Person.find 1), (d = Person.find 4)] # => [a]
def hash
id.hash
end
diff --git a/activeresource/lib/active_resource/http_mock.rb b/activeresource/lib/active_resource/http_mock.rb
index 9aefde7c30..75649053d0 100644
--- a/activeresource/lib/active_resource/http_mock.rb
+++ b/activeresource/lib/active_resource/http_mock.rb
@@ -60,10 +60,21 @@ module ActiveResource
# end
module_eval <<-EOE, __FILE__, __LINE__ + 1
def #{method}(path, request_headers = {}, body = nil, status = 200, response_headers = {})
- @responses << [Request.new(:#{method}, path, nil, request_headers), Response.new(body || "", status, response_headers)]
+ request = Request.new(:#{method}, path, nil, request_headers)
+ response = Response.new(body || "", status, response_headers)
+
+ delete_duplicate_responses(request)
+
+ @responses << [request, response]
end
EOE
end
+
+ private
+
+ def delete_duplicate_responses(request)
+ @responses.delete_if {|r| r[0] == request }
+ end
end
class << self
@@ -181,11 +192,11 @@ module ActiveResource
pairs = args.first || {}
reset! if args.last.class != FalseClass
- delete_responses_to_replace pairs.to_a
- responses.concat pairs.to_a
if block_given?
yield Responder.new(responses)
else
+ delete_responses_to_replace pairs.to_a
+ responses.concat pairs.to_a
Responder.new(responses)
end
end
diff --git a/activeresource/test/cases/http_mock_test.rb b/activeresource/test/cases/http_mock_test.rb
index 82b5e60c77..43cf5f5ef0 100644
--- a/activeresource/test/cases/http_mock_test.rb
+++ b/activeresource/test/cases/http_mock_test.rb
@@ -140,7 +140,19 @@ class HttpMockTest < ActiveSupport::TestCase
assert_equal 2, ActiveResource::HttpMock.responses.length
end
- test "allows you to replace the existing reponse with the same request" do
+ test "allows you to replace the existing reponse with the same request by calling a block" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ ActiveResource::HttpMock.respond_to(false) do |mock|
+ mock.send(:get, "/people/1", {}, "XML2")
+ end
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+
+ test "allows you to replace the existing reponse with the same request by passing pairs" do
ActiveResource::HttpMock.respond_to do |mock|
mock.send(:get, "/people/1", {}, "XML1")
end
@@ -151,11 +163,22 @@ class HttpMockTest < ActiveSupport::TestCase
ok_response = ActiveResource::Response.new(matz, 200, {})
ActiveResource::HttpMock.respond_to({get_matz => ok_response}, false)
+ assert_equal 1, ActiveResource::HttpMock.responses.length
+ end
+ test "do not replace the response with the same path but different method by calling a block" do
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.send(:get, "/people/1", {}, "XML1")
+ end
assert_equal 1, ActiveResource::HttpMock.responses.length
+
+ ActiveResource::HttpMock.respond_to(false) do |mock|
+ mock.send(:put, "/people/1", {}, "XML2")
+ end
+ assert_equal 2, ActiveResource::HttpMock.responses.length
end
- test "do not replace the response with the same path but different method" do
+ test "do not replace the response with the same path but different method by passing pairs" do
ActiveResource::HttpMock.respond_to do |mock|
mock.send(:get, "/people/1", {}, "XML1")
end
diff --git a/activeresource/test/cases/validations_test.rb b/activeresource/test/cases/validations_test.rb
index bd79fdd952..671d1ea8f0 100644
--- a/activeresource/test/cases/validations_test.rb
+++ b/activeresource/test/cases/validations_test.rb
@@ -48,6 +48,12 @@ class ValidationsTest < ActiveModel::TestCase
assert p.save, "should have saved after fixing the validation, but had: #{p.errors.inspect}"
end
+ def test_client_side_validation_maximum
+ project = Project.new(:description => '123456789012345')
+ assert ! project.valid?
+ assert_equal ['is too long (maximum is 10 characters)'], project.errors[:description]
+ end
+
protected
# quickie helper to create a new project with all the required
diff --git a/activeresource/test/fixtures/project.rb b/activeresource/test/fixtures/project.rb
index e15fa6f620..53de666601 100644
--- a/activeresource/test/fixtures/project.rb
+++ b/activeresource/test/fixtures/project.rb
@@ -1,25 +1,18 @@
# used to test validations
class Project < ActiveResource::Base
self.site = "http://37s.sunrise.i:3000"
+ schema do
+ string :email
+ string :name
+ end
- validates_presence_of :name
+ validates :name, :presence => true
+ validates :description, :presence => false, :length => {:maximum => 10}
validate :description_greater_than_three_letters
# to test the validate *callback* works
def description_greater_than_three_letters
errors.add :description, 'must be greater than three letters long' if description.length < 3 unless description.blank?
end
-
-
- # stop-gap accessor to default this attribute to nil
- # Otherwise the validations fail saying that the method does not exist.
- # In future, method_missing will be updated to not explode on a known
- # attribute.
- def name
- attributes['name'] || nil
- end
- def description
- attributes['description'] || nil
- end
end
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
index 6e8cce0d27..373236ce9a 100644
--- a/activesupport/CHANGELOG
+++ b/activesupport/CHANGELOG
@@ -1,5 +1,16 @@
*Rails 3.1.0 (unreleased)*
+* 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]
diff --git a/activesupport/MIT-LICENSE b/activesupport/MIT-LICENSE
index cd928b856d..5e8b7a9450 100644
--- a/activesupport/MIT-LICENSE
+++ b/activesupport/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2005-2010 David Heinemeier Hansson
+Copyright (c) 2005-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 6b87774978..6b662ac660 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -42,6 +42,7 @@ module ActiveSupport
autoload :DescendantsTracker
autoload :FileUpdateChecker
+ autoload :FileWatcher
autoload :LogSubscriber
autoload :Notifications
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index 4dce35f1c9..0649a058aa 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -50,34 +50,39 @@ module ActiveSupport
end
end
- # Middleware class can be inserted as a Rack handler to be local cache for the
- # duration of request.
- def middleware
- @middleware ||= begin
- klass = Class.new
- klass.class_eval(<<-EOS, __FILE__, __LINE__ + 1)
- class << self
- def name
- "ActiveSupport::Cache::Strategy::LocalCache"
- end
- alias :to_s :name
- end
+ #--
+ # This class wraps up local storage for middlewares. Only the middleware method should
+ # construct them.
+ class Middleware # :nodoc:
+ attr_reader :name, :thread_local_key
- def initialize(app)
- @app = app
- end
+ def initialize(name, thread_local_key)
+ @name = name
+ @thread_local_key = thread_local_key
+ @app = nil
+ end
- def call(env)
- Thread.current[:#{thread_local_key}] = LocalStore.new
- @app.call(env)
- ensure
- Thread.current[:#{thread_local_key}] = nil
- end
- EOS
- klass
+ def new(app)
+ @app = app
+ self
+ end
+
+ def call(env)
+ Thread.current[thread_local_key] = LocalStore.new
+ @app.call(env)
+ ensure
+ Thread.current[thread_local_key] = nil
end
end
+ # Middleware class can be inserted as a Rack handler to be local cache for the
+ # duration of request.
+ def middleware
+ @middleware ||= Middleware.new(
+ "ActiveSupport::Cache::Strategy::LocalCache",
+ thread_local_key)
+ end
+
def clear(options = nil) # :nodoc:
local_cache.clear(options) if local_cache
super
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 844237fe6a..96ce79e896 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -5,27 +5,28 @@ require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/kernel/singleton_class'
module ActiveSupport
- # Callbacks are hooks into the life cycle of an object that allow you to trigger logic
- # before or after an alteration of the object state.
+ # \Callbacks are code hooks that are run at key points in an object's lifecycle.
+ # The typical use case is to have a base class define a set of callbacks relevant
+ # to the other functionality it supplies, so that subclasses can install callbacks
+ # that enhance or modify the base functionality without needing to override
+ # or redefine methods of the base class.
#
- # Mixing in this module allows you to define callbacks in your class.
+ # Mixing in this module allows you to define the events in the object's lifecycle
+ # that will support callbacks (via +ClassMethods.define_callbacks+), set the instance
+ # methods, procs, or callback objects to be called (via +ClassMethods.set_callback+),
+ # and run the installed callbacks at the appropriate times (via +run_callbacks+).
#
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
+ # Three kinds of callbacks are supported: before callbacks, run before a certain event;
+ # after callbacks, run after the event; and around callbacks, blocks that surround the
+ # event, triggering it when they yield. Callback code can be contained in instance
+ # methods, procs or lambdas, or callback objects that respond to certain predetermined
+ # methods. See +ClassMethods.set_callback+ for details.
#
- # define_callbacks :save
- # end
+ # ==== Example
#
- # class ConfigStorage < Storage
- # set_callback :save, :before, :saving_message
- # def saving_message
- # puts "saving..."
- # end
- #
- # set_callback :save, :after do |object|
- # puts "saved"
- # end
+ # class Record
+ # include ActiveSupport::Callbacks
+ # define_callbacks :save
#
# def save
# run_callbacks :save do
@@ -34,29 +35,7 @@ module ActiveSupport
# end
# end
#
- # config = ConfigStorage.new
- # config.save
- #
- # Output:
- # saving...
- # - save
- # saved
- #
- # Callbacks from parent classes are inherited.
- #
- # Example:
- # class Storage
- # include ActiveSupport::Callbacks
- #
- # define_callbacks :save
- #
- # set_callback :save, :before, :prepare
- # def prepare
- # puts "preparing save"
- # end
- # end
- #
- # class ConfigStorage < Storage
+ # class PersonRecord < Record
# set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
@@ -65,19 +44,12 @@ module ActiveSupport
# set_callback :save, :after do |object|
# puts "saved"
# end
- #
- # def save
- # run_callbacks :save do
- # puts "- save"
- # end
- # end
# end
#
- # config = ConfigStorage.new
- # config.save
+ # person = PersonRecord.new
+ # person.save
#
# Output:
- # preparing save
# saving...
# - save
# saved
@@ -89,11 +61,25 @@ module ActiveSupport
extend ActiveSupport::DescendantsTracker
end
+ # Runs the callbacks for the given event.
+ #
+ # Calls the before and around callbacks in the order they were set, yields
+ # the block (if given one), and then runs the after callbacks in reverse order.
+ # Optionally accepts a key, which will be used to compile an optimized callback
+ # method for each key. See +ClassMethods.define_callbacks+ for more information.
+ #
+ # If the callback chain was halted, returns +false+. Otherwise returns the result
+ # of the block, or +true+ if no block is given.
+ #
+ # run_callbacks :save do
+ # save
+ # end
+ #
def run_callbacks(kind, *args, &block)
send("_run_#{kind}_callbacks", *args, &block)
end
- class Callback
+ class Callback #:nodoc:#
@@_callback_sequence = 0
attr_accessor :chain, :filter, :kind, :options, :per_key, :klass, :raw_filter
@@ -185,7 +171,11 @@ module ActiveSupport
# end
filter = <<-RUBY_EVAL
unless halted
- result = #{@filter}
+ # This double assignment is to prevent warnings in 1.9.3. I would
+ # remove the `result` variable, but apparently some other
+ # generated code is depending on this variable being set sometimes
+ # and sometimes not.
+ result = result = #{@filter}
halted = (#{chain.config[:terminator]})
end
RUBY_EVAL
@@ -328,7 +318,7 @@ module ActiveSupport
end
# An Array with a compile method
- class CallbackChain < Array
+ class CallbackChain < Array #:nodoc:#
attr_reader :name, :config
def initialize(name, config)
@@ -373,18 +363,7 @@ module ActiveSupport
end
module ClassMethods
- # Make the run_callbacks :save method. The generated method takes
- # a block that it'll yield to. It'll call the before and around filters
- # in order, yield the block, and then run the after filters.
- #
- # run_callbacks :save do
- # save
- # end
- #
- # The run_callbacks :save method can optionally take a key, which
- # will be used to compile an optimized callback method for each
- # key. See #define_callbacks for more information.
- #
+ # Generate the internal runner method called by +run_callbacks+.
def __define_runner(symbol) #:nodoc:
body = send("_#{symbol}_callbacks").compile
@@ -440,14 +419,42 @@ module ActiveSupport
end
end
- # Set callbacks for a previously defined callback.
+ # Install a callback for the given event.
#
- # Syntax:
# set_callback :save, :before, :before_meth
# set_callback :save, :after, :after_meth, :if => :condition
# set_callback :save, :around, lambda { |r| stuff; yield; stuff }
#
- # Use skip_callback to skip any defined one.
+ # The second arguments indicates whether the callback is to be run +:before+,
+ # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
+ # means the first example above can also be written as:
+ #
+ # set_callback :save, :before_meth
+ #
+ # The callback can specified as a symbol naming an instance method; as a proc,
+ # lambda, or block; as a string to be instance evaluated; or as an object that
+ # responds to a certain method determined by the <tt>:scope</tt> argument to
+ # +define_callback+.
+ #
+ # If a proc, lambda, or block is given, its body is evaluated in the context
+ # of the current object. It can also optionally accept the current object as
+ # an argument.
+ #
+ # Before and around callbacks are called in the order that they are set; after
+ # callbacks are called in the reverse order.
+ #
+ # ===== Options
+ #
+ # * <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
+ # will be called only when it returns a false value.
+ # * <tt>:prepend</tt> - If true, the callback will be prepended to the existing
+ # chain rather than appended.
+ # * <tt>:per_key</tt> - A hash with <tt>:if</tt> and <tt>:unless</tt> options;
+ # see "Per-key conditions" below.
+ #
+ # ===== Per-key conditions
#
# When creating or skipping callbacks, you can specify conditions that
# are always the same for a given key. For instance, in Action Pack,
@@ -459,7 +466,7 @@ module ActiveSupport
#
# set_callback :process_action, :before, :authenticate, :per_key => {:unless => proc {|c| c.action_name == "index"}}
#
- # Per-Key conditions are evaluated only once per use of a given key.
+ # Per-key conditions are evaluated only once per use of a given key.
# In the case of the above example, you would do:
#
# run_callbacks(:process_action, action_name) { ... dispatch stuff ... }
@@ -486,7 +493,8 @@ module ActiveSupport
end
end
- # Skip a previously defined callback.
+ # Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or <tt>:unless</tt>
+ # options may be passed in order to control when the callback is skipped.
#
# class Writer < Person
# skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 }
@@ -509,7 +517,7 @@ module ActiveSupport
end
end
- # Reset callbacks for a given type.
+ # Remove all set callbacks for the given event.
#
def reset_callbacks(symbol)
callbacks = send("_#{symbol}_callbacks")
@@ -526,68 +534,71 @@ module ActiveSupport
__define_runner(symbol)
end
- # Defines callbacks types:
+ # Define sets of events in the object lifecycle that support callbacks.
#
# define_callbacks :validate
+ # define_callbacks :initialize, :save, :destroy
#
- # This macro accepts the following options:
+ # ===== Options
#
- # * <tt>:terminator</tt> - Indicates when a before filter is considered
- # to halted. This is a string to be eval'ed and has the result of the
- # very filter available in the <tt>result</tt> variable:
+ # * <tt>:terminator</tt> - Determines when a before filter will halt the callback
+ # chain, preventing following callbacks from being called and the event from being
+ # triggered. This is a string to be eval'ed. The result of the callback is available
+ # in the <tt>result</tt> variable.
#
- # define_callbacks :validate, :terminator => "result == false"
+ # define_callbacks :validate, :terminator => "result == false"
#
- # In the example above, if any before validate callbacks returns +false+,
- # other callbacks are not executed. Defaults to "false", meaning no value
- # halts the chain.
+ # In this example, if any before validate callbacks returns +false+,
+ # other callbacks are not executed. Defaults to "false", meaning no value
+ # halts the chain.
#
# * <tt>:rescuable</tt> - By default, after filters are not executed if
- # the given block or a before filter raises an error. Set this option to
- # true to change this behavior.
+ # the given block or a before filter raises an error. By setting this option
+ # to <tt>true</tt> exception raised by given block is stored and after
+ # executing all the after callbacks the stored exception is raised.
#
- # * <tt>:scope</tt> - Indicates which methods should be executed when a class
- # is given as callback. Defaults to <tt>[:kind]</tt>.
+ # * <tt>:scope</tt> - Indicates which methods should be executed when an object
+ # is used as a callback.
#
- # class Audit
- # def before(caller)
- # puts 'Audit: before is called'
- # end
+ # class Audit
+ # def before(caller)
+ # puts 'Audit: before is called'
+ # end
#
- # def before_save(caller)
- # puts 'Audit: before_save is called'
- # end
- # end
+ # def before_save(caller)
+ # puts 'Audit: before_save is called'
+ # end
+ # end
#
- # class Account
- # include ActiveSupport::Callbacks
+ # class Account
+ # include ActiveSupport::Callbacks
#
- # define_callbacks :save
- # set_callback :save, :before, Audit.new
+ # define_callbacks :save
+ # set_callback :save, :before, Audit.new
#
- # def save
- # run_callbacks :save do
- # puts 'save in main'
- # end
- # end
- # end
+ # def save
+ # run_callbacks :save do
+ # puts 'save in main'
+ # end
+ # end
+ # end
#
- # In the above case whenever you save an account the method <tt>Audit#before</tt> will
- # be called. On the other hand
+ # In the above case whenever you save an account the method <tt>Audit#before</tt> will
+ # be called. On the other hand
#
- # define_callbacks :save, :scope => [:kind, :name]
+ # define_callbacks :save, :scope => [:kind, :name]
#
- # would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
- # <tt>"#{kind}_#{name}"</tt> on the given instance. In this case "kind" is "before" and
- # "name" is "save". In this context ":kind" and ":name" have special meanings: ":kind"
- # refers to the kind of callback (before/after/around) and ":name" refers to the
- # method on which callbacks are being defined.
+ # would trigger <tt>Audit#before_save</tt> instead. That's constructed by calling
+ # <tt>#{kind}_#{name}</tt> on the given instance. In this case "kind" is "before" and
+ # "name" is "save". In this context +:kind+ and +:name+ have special meanings: +:kind+
+ # refers to the kind of callback (before/after/around) and +:name+ refers to the
+ # method on which callbacks are being defined.
#
- # A declaration like
+ # A declaration like
#
- # define_callbacks :save, :scope => [:name]
+ # define_callbacks :save, :scope => [:name]
#
- # would call <tt>Audit#save</tt>.
+ # would call <tt>Audit#save</tt>.
#
def define_callbacks(*callbacks)
config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
index ac94d12e5e..81fb859334 100644
--- a/activesupport/lib/active_support/concern.rb
+++ b/activesupport/lib/active_support/concern.rb
@@ -3,7 +3,7 @@ module ActiveSupport
#
# module M
# def self.included(base)
- # base.extend, ClassMethods
+ # base.extend ClassMethods
# base.send(:include, InstanceMethods)
# scope :disabled, where(:disabled => true)
# end
diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb
index 644db0b205..be19189c04 100644
--- a/activesupport/lib/active_support/configurable.rb
+++ b/activesupport/lib/active_support/configurable.rb
@@ -26,7 +26,7 @@ module ActiveSupport
module ClassMethods
def config
- @_config ||= if superclass.respond_to?(:config)
+ @_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
superclass.config.inheritable_copy
else
# create a new "anonymous" class that will host the compiled reader methods
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
index f7f03f4d95..080604147d 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -1,23 +1,38 @@
require 'bigdecimal'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
class BigDecimal
YAML_TAG = 'tag:yaml.org,2002:float'
YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
- yaml_as YAML_TAG
-
# This emits the number without any scientific notation.
# This is better than self.to_f.to_s since it doesn't lose precision.
#
# Note that reconstituting YAML floats to native floats may lose precision.
def to_yaml(opts = {})
+ return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
+
YAML.quick_emit(nil, opts) do |out|
string = to_s
out.scalar(YAML_TAG, YAML_MAPPING[string] || string, :plain)
end
end
+ def encode_with(coder)
+ string = to_s
+ coder.represent_scalar(nil, YAML_MAPPING[string] || string)
+ end
+
+ def to_d
+ self
+ end
+
DEFAULT_STRING_FORMAT = 'F'
def to_formatted_s(format = DEFAULT_STRING_FORMAT)
_original_to_s(format)
diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb
index 3e5d1a2a42..46e9daaa8f 100644
--- a/activesupport/lib/active_support/core_ext/class/subclasses.rb
+++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb
@@ -2,49 +2,35 @@ require 'active_support/core_ext/module/anonymous'
require 'active_support/core_ext/module/reachable'
class Class #:nodoc:
- # Rubinius
- if defined?(Class.__subclasses__)
- alias :subclasses :__subclasses__
+ begin
+ ObjectSpace.each_object(Class.new) {}
def descendants
descendants = []
- __subclasses__.each do |k|
- descendants << k
- descendants.concat k.descendants
+ ObjectSpace.each_object(class << self; self; end) do |k|
+ descendants.unshift k unless k == self
end
descendants
end
- else # MRI
- begin
- ObjectSpace.each_object(Class.new) {}
-
- def descendants
- descendants = []
- ObjectSpace.each_object(class << self; self; end) do |k|
- descendants.unshift k unless k == self
- end
- descendants
- end
- rescue StandardError # JRuby
- def descendants
- descendants = []
- ObjectSpace.each_object(Class) do |k|
- descendants.unshift k if k < self
- end
- descendants.uniq!
- descendants
+ rescue StandardError # JRuby
+ def descendants
+ descendants = []
+ ObjectSpace.each_object(Class) do |k|
+ descendants.unshift k if k < self
end
+ descendants.uniq!
+ descendants
end
+ end
- # Returns an array with the direct children of +self+.
- #
- # Integer.subclasses # => [Bignum, Fixnum]
- def subclasses
- subclasses, chain = [], descendants
- chain.each do |k|
- subclasses << k unless chain.any? { |c| c > k }
- end
- subclasses
+ # Returns an array with the direct children of +self+.
+ #
+ # Integer.subclasses # => [Bignum, Fixnum]
+ def subclasses
+ subclasses, chain = [], descendants
+ chain.each do |k|
+ subclasses << k unless chain.any? { |c| c > k }
end
+ subclasses
end
end
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index f34185f22c..724e076407 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -36,9 +36,9 @@ class Date
::Date.current.tomorrow
end
- # Returns Time.zone.today when config.time_zone is set, otherwise just returns Date.today.
+ # Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
def current
- ::Time.zone_default ? ::Time.zone.today : ::Date.today
+ ::Time.zone ? ::Time.zone.today : ::Date.today
end
end
diff --git a/activesupport/lib/active_support/core_ext/date/conversions.rb b/activesupport/lib/active_support/core_ext/date/conversions.rb
index 092f936961..769ead9544 100644
--- a/activesupport/lib/active_support/core_ext/date/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date/conversions.rb
@@ -1,5 +1,5 @@
require 'date'
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
require 'active_support/core_ext/date/zones'
class Date
@@ -93,6 +93,12 @@ class Date
::DateTime.civil(year, month, day, 0, 0, 0, 0)
end if RUBY_VERSION < '1.9'
+ def iso8601
+ strftime('%F')
+ end if RUBY_VERSION < '1.9'
+
+ alias_method :rfc3339, :iso8601 if RUBY_VERSION < '1.9'
+
def xmlschema
to_time_in_current_zone.xmlschema
end
diff --git a/activesupport/lib/active_support/core_ext/date/zones.rb b/activesupport/lib/active_support/core_ext/date/zones.rb
index 3a83af6be2..a70b47b7bc 100644
--- a/activesupport/lib/active_support/core_ext/date/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date/zones.rb
@@ -2,10 +2,10 @@ require 'date'
require 'active_support/core_ext/time/zones'
class Date
- # Converts Date to a TimeWithZone in the current zone if Time.zone_default is set,
- # otherwise converts Date to a Time via Date#to_time
+ # Converts Date to a TimeWithZone in the current zone if Time.zone or Time.zone_default
+ # is set, otherwise converts Date to a Time via Date#to_time
def to_time_in_current_zone
- if ::Time.zone_default
+ if ::Time.zone
::Time.zone.local(year, month, day)
else
to_time
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 1dc3933e12..8d01376f1d 100644
--- a/activesupport/lib/active_support/core_ext/date_time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/calculations.rb
@@ -9,8 +9,9 @@ class DateTime
::Time.local(2007).utc_offset.to_r / 86400
end
+ # Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise returns <tt>Time.now.to_datetime</tt>.
def current
- ::Time.zone_default ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
+ ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end
end
diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
index 8e267c76c4..21b84b994b 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
require 'active_support/core_ext/time/conversions'
require 'active_support/core_ext/date_time/calculations'
require 'active_support/values/time_zone'
@@ -66,7 +66,7 @@ class DateTime
# Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class
# If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time
def to_time
- self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self
+ self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self
end
# To be able to keep Times, Dates and DateTimes interchangeable on conversions
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb
index 4e8ec5a3a8..3005fef44c 100644
--- a/activesupport/lib/active_support/core_ext/hash/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -26,10 +26,22 @@ class Hash
#
# * If +value+ is a callable object it must expect one or two arguments. Depending
# on the arity, the callable is invoked with the +options+ hash as first argument
- # with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. Its
- # return value becomes a new node.
+ # with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
+ # callable can add nodes by using <tt>options[:builder]</tt>.
+ #
+ # "foo".to_xml(lambda { |options, key| options[:builder].b(key) })
+ # # => "<b>foo</b>"
#
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
+ #
+ # class Foo
+ # def to_xml(options)
+ # options[:builder].bar "fooing!"
+ # end
+ # end
+ #
+ # {:foo => Foo.new}.to_xml(:skip_instruct => true)
+ # # => "<hash><bar>fooing!</bar></hash>"
#
# * Otherwise, a node with +key+ as tag is created with a string representation of
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
diff --git a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
index 0b6731883c..e3259a0a84 100644
--- a/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
+++ b/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
@@ -7,11 +7,11 @@ class Module
# attr_accessor_with_default :age, 25
# end
#
- # some_person.age
- # => 25
- # some_person.age = 26
- # some_person.age
- # => 26
+ # person = Person.new
+ # person.age # => 25
+ #
+ # person.age = 26
+ # person.age # => 26
#
# To give attribute <tt>:element_name</tt> a dynamic default value, evaluated
# in scope of self:
diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb
index 3209cf7f11..c23afabfdb 100644
--- a/activesupport/lib/active_support/core_ext/object/with_options.rb
+++ b/activesupport/lib/active_support/core_ext/object/with_options.rb
@@ -7,13 +7,27 @@ class Object
# provided. Each method called on the block variable must take an options
# hash as its final argument.
#
- # with_options :order => 'created_at', :class_name => 'Comment' do |post|
- # post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all
- # post.has_many :unapproved_comments, :conditions => ['approved = ?', false]
- # post.has_many :all_comments
+ # Without with_options, this code contains duplication:
+ #
+ # class Account < ActiveRecord::Base
+ # has_many :customers, :dependent => :destroy
+ # has_many :products, :dependent => :destroy
+ # has_many :invoices, :dependent => :destroy
+ # has_many :expenses, :dependent => :destroy
+ # end
+ #
+ # Using with_options, we can remove the duplication:
+ #
+ # class Account < ActiveRecord::Base
+ # with_options :dependent => :destroy do |assoc|
+ # assoc.has_many :customers
+ # assoc.has_many :products
+ # assoc.has_many :invoices
+ # assoc.has_many :expenses
+ # end
# end
#
- # Can also be used with an explicit receiver:
+ # It can also be used with an explicit receiver:
#
# map.with_options :controller => "people" do |people|
# people.connect "/people", :action => "index"
diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb
index c0736f3a44..2428a02242 100644
--- a/activesupport/lib/active_support/core_ext/range.rb
+++ b/activesupport/lib/active_support/core_ext/range.rb
@@ -2,3 +2,4 @@ require 'active_support/core_ext/range/blockless_step'
require 'active_support/core_ext/range/conversions'
require 'active_support/core_ext/range/include_range'
require 'active_support/core_ext/range/overlaps'
+require 'active_support/core_ext/range/cover'
diff --git a/activesupport/lib/active_support/core_ext/range/cover.rb b/activesupport/lib/active_support/core_ext/range/cover.rb
new file mode 100644
index 0000000000..3a182cddd2
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/cover.rb
@@ -0,0 +1,3 @@
+class Range
+ alias_method(:cover?, :include?) unless instance_methods.include?(:cover?)
+end
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
index 55b24b0925..2f0676f567 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -3,7 +3,7 @@ require 'active_support/inflector/inflections'
require 'active_support/inflector/transliterate'
# String inflections define new methods on the String class to transform names for different purposes.
-# For instance, you can figure out the name of a database from the name of a class.
+# For instance, you can figure out the name of a table from the name of a class.
#
# "ScaleScore".tableize # => "scale_scores"
#
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 bb0f747960..c930abc003 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -101,7 +101,13 @@ module ActiveSupport #:nodoc:
self
end
+ def encode_with(coder)
+ coder.represent_scalar nil, to_str
+ end
+
def to_yaml(*args)
+ return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
+
to_str.to_yaml(*args)
end
end
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index fa052fa86b..6e4b69f681 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -41,9 +41,9 @@ class Time
time_with_datetime_fallback(:local, *args)
end
- # Returns <tt>Time.zone.now</tt> when <tt>config.time_zone</tt> is set, otherwise just returns <tt>Time.now</tt>.
+ # Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
def current
- ::Time.zone_default ? ::Time.zone.now : ::Time.now
+ ::Time.zone ? ::Time.zone.now : ::Time.now
end
end
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index d4ae3131ec..d9d5e02778 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
require 'active_support/core_ext/time/publicize_conversion_methods'
require 'active_support/values/time_zone'
@@ -55,31 +55,9 @@ class Time
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
end
- # Converts a Time object to a Date, dropping hour, minute, and second precision.
- #
- # my_time = Time.now # => Mon Nov 12 22:59:51 -0500 2007
- # my_time.to_date # => Mon, 12 Nov 2007
- #
- # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
- # your_time.to_date # => Tue, 13 Jan 2009
- def to_date
- ::Date.new(year, month, day)
- end unless method_defined?(:to_date)
-
# A method to keep Time, Date and DateTime instances interchangeable on conversions.
# In this case, it simply returns +self+.
def to_time
self
end unless method_defined?(:to_time)
-
- # Converts a Time instance to a Ruby DateTime instance, preserving UTC offset.
- #
- # my_time = Time.now # => Mon Nov 12 23:04:21 -0500 2007
- # my_time.to_datetime # => Mon, 12 Nov 2007 23:04:21 -0500
- #
- # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
- # your_time.to_datetime # => Tue, 13 Jan 2009 13:13:03 -0500
- def to_datetime
- ::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400))
- end unless method_defined?(:to_datetime)
end
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
index ef401a6d18..ff90d7ca58 100644
--- a/activesupport/lib/active_support/core_ext/time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -19,14 +19,18 @@ class Time
# * A TZInfo::Timezone object.
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
#
- # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt>
- # just needs to return a string identifying the user's preferred TimeZone:
+ # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
+ # <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
#
# class ApplicationController < ActionController::Base
- # before_filter :set_time_zone
+ # around_filter :set_time_zone
#
# def set_time_zone
- # Time.zone = current_user.time_zone
+ # old_time_zone = Time.zone
+ # Time.zone = current_user.time_zone if logged_in?
+ # yield
+ # ensure
+ # Time.zone = old_time_zone
# end
# end
def zone=(time_zone)
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index dab6fdbac6..47596a389d 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -5,6 +5,7 @@ require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/module/anonymous'
+require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/name_error'
@@ -47,9 +48,6 @@ module ActiveSupport #:nodoc:
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
- mattr_accessor :references
- self.references = {}
-
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
mattr_accessor :explicitly_unloadable_constants
@@ -524,31 +522,76 @@ module ActiveSupport #:nodoc:
explicitly_unloadable_constants.each { |const| remove_constant const }
end
- class Reference
- @@constants = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
+ class ClassCache
+ def initialize
+ @store = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
+ end
+
+ def empty?
+ @store.empty?
+ end
+
+ def key?(key)
+ @store.key?(key)
+ end
+
+ def []=(key, value)
+ return unless key.respond_to?(:name)
+
+ raise(ArgumentError, 'anonymous classes cannot be cached') if key.name.blank?
+
+ @store[key.name] = value
+ end
+
+ def [](key)
+ key = key.name if key.respond_to?(:name)
+
+ @store[key]
+ end
+ alias :get :[]
- attr_reader :name
+ class Getter # :nodoc:
+ def initialize(name)
+ @name = name
+ end
- def initialize(name)
- @name = name.to_s
- @@constants[@name] = name if name.respond_to?(:name)
+ def get
+ Reference.get @name
+ end
+ deprecate :get
end
- def get
- @@constants[@name]
+ def new(name)
+ self[name] = name
+ Getter.new(name)
end
+ deprecate :new
- def self.clear!
- @@constants.clear
+ def store(name)
+ self[name] = name
+ self
+ end
+
+ def clear!
+ @store.clear
end
end
+ Reference = ClassCache.new
+
def ref(name)
- references[name] ||= Reference.new(name)
+ Reference.new(name)
+ end
+ deprecate :ref
+
+ # Store a reference to a class +klass+.
+ def reference(klass)
+ Reference.store klass
end
+ # Get the reference for class named +name+.
def constantize(name)
- ref(name).get
+ Reference.get(name)
end
# Determine if the given constant has been automatically loaded.
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index e1b8211d68..ce0775a690 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -4,12 +4,12 @@ require 'active_support/deprecation/method_wrappers'
require 'active_support/deprecation/proxy_wrappers'
module ActiveSupport
- module Deprecation #:nodoc:
+ module Deprecation
class << self
# The version the deprecated behavior will be removed, by default.
attr_accessor :deprecation_horizon
end
- self.deprecation_horizon = '3.0'
+ self.deprecation_horizon = '3.1'
# By default, warnings are not silenced and debugging is off.
self.silenced = false
diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb
index f54f65dcf0..da4af339fc 100644
--- a/activesupport/lib/active_support/deprecation/behaviors.rb
+++ b/activesupport/lib/active_support/deprecation/behaviors.rb
@@ -7,10 +7,17 @@ module ActiveSupport
# Whether to print a backtrace along with the warning.
attr_accessor :debug
+ # Returns the set behaviour or if one isn't set, defaults to +:stderr+
def behavior
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
end
+ # Sets the behaviour to the specified value. Can be a single value or an array.
+ #
+ # Examples
+ #
+ # ActiveSupport::Deprecation.behavior = :stderr
+ # ActiveSupport::Deprecation.behavior = [:stderr, :log]
def behavior=(behavior)
@behavior = Array.wrap(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
end
diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
index 970536a594..a65fcafb44 100644
--- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
@@ -1,4 +1,4 @@
-require 'active_support/inflector'
+require 'active_support/inflector/methods'
module ActiveSupport
module Deprecation
diff --git a/activesupport/lib/active_support/deprecation/reporting.rb b/activesupport/lib/active_support/deprecation/reporting.rb
index 6a7b11c7e0..ced08b8783 100644
--- a/activesupport/lib/active_support/deprecation/reporting.rb
+++ b/activesupport/lib/active_support/deprecation/reporting.rb
@@ -3,6 +3,12 @@ module ActiveSupport
class << self
attr_accessor :silenced
+ # Outputs a deprecation warning to the output configured by <tt>ActiveSupport::Deprecation.behavior</tt>
+ #
+ # Example:
+ #
+ # ActiveSupport::Deprecation.warn("something broke!")
+ # #=> "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
def warn(message = nil, callstack = caller)
return if silenced
deprecation_message(callstack, message).tap do |m|
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index de3ded1e1f..00c67a470d 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -80,6 +80,10 @@ module ActiveSupport
parts.to_sentence(:locale => :en)
end
+ def as_json(options = nil) #:nodoc:
+ to_i
+ end
+
protected
def sum(sign, time = ::Time.current) #:nodoc:
diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb
index cd658fe173..a97e9d7daf 100644
--- a/activesupport/lib/active_support/file_update_checker.rb
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -8,7 +8,7 @@ module ActiveSupport
# I18n.reload!
# end
#
- # ActionDispatch::Callbacks.to_prepare do
+ # ActionDispatch::Reloader.to_prepare do
# i18n_reloader.execute_if_updated
# end
#
diff --git a/activesupport/lib/active_support/file_watcher.rb b/activesupport/lib/active_support/file_watcher.rb
new file mode 100644
index 0000000000..81e63e76a7
--- /dev/null
+++ b/activesupport/lib/active_support/file_watcher.rb
@@ -0,0 +1,36 @@
+module ActiveSupport
+ class FileWatcher
+ class Backend
+ def initialize(path, watcher)
+ @watcher = watcher
+ @path = path
+ end
+
+ def trigger(files)
+ @watcher.trigger(files)
+ end
+ end
+
+ def initialize
+ @regex_matchers = {}
+ end
+
+ def watch(pattern, &block)
+ @regex_matchers[pattern] = block
+ end
+
+ def trigger(files)
+ trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
+
+ files.each do |file, state|
+ @regex_matchers.each do |pattern, block|
+ trigger_files[block][state] << file if pattern === file
+ end
+ end
+
+ trigger_files.each do |block, payload|
+ block.call payload
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb
index 35a50e9a77..62f9c9aa2e 100644
--- a/activesupport/lib/active_support/gzip.rb
+++ b/activesupport/lib/active_support/gzip.rb
@@ -5,6 +5,10 @@ module ActiveSupport
# A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip.
module Gzip
class Stream < StringIO
+ def initialize(*)
+ super
+ set_encoding "BINARY" if "".encoding_aware?
+ end
def close; rewind; end
end
@@ -22,4 +26,4 @@ module ActiveSupport
output.string
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb
index f8a5616a76..4a9ee5a769 100644
--- a/activesupport/lib/active_support/i18n_railtie.rb
+++ b/activesupport/lib/active_support/i18n_railtie.rb
@@ -19,14 +19,29 @@ module I18n
# on to_prepare callbacks. This will only happen on the config.after_initialize
# callback below.
initializer "i18n.callbacks" do
- ActionDispatch::Callbacks.to_prepare do
+ ActionDispatch::Reloader.to_prepare do
I18n::Railtie.reloader.execute_if_updated
end
end
- # Set the i18n configuration only after initialization since a lot of
+ # Set the i18n configuration after initialization since a lot of
# configuration is still usually done in application initializers.
config.after_initialize do |app|
+ I18n::Railtie.initialize_i18n(app)
+ end
+
+ # Trigger i18n config before any eager loading has happened
+ # so it's ready if any classes require it when eager loaded
+ config.before_eager_load do |app|
+ I18n::Railtie.initialize_i18n(app)
+ end
+
+ protected
+
+ # Setup i18n configuration
+ def self.initialize_i18n(app)
+ return if @i18n_inited
+
fallbacks = app.config.i18n.delete(:fallbacks)
app.config.i18n.each do |setting, value|
@@ -44,9 +59,9 @@ module I18n
reloader.paths.concat I18n.load_path
reloader.execute_if_updated
- end
- protected
+ @i18n_inited = true
+ end
def self.include_fallbacks_module
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
@@ -78,4 +93,4 @@ module I18n
end
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index e7b5387ed7..06ceccdb22 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -4,10 +4,12 @@ module ActiveSupport
inflect.plural(/s$/i, 's')
inflect.plural(/(ax|test)is$/i, '\1es')
inflect.plural(/(octop|vir)us$/i, '\1i')
+ inflect.plural(/(octop|vir)i$/i, '\1i')
inflect.plural(/(alias|status)$/i, '\1es')
inflect.plural(/(bu)s$/i, '\1ses')
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
inflect.plural(/([ti])um$/i, '\1a')
+ inflect.plural(/([ti])a$/i, '\1a')
inflect.plural(/sis$/i, 'ses')
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
inflect.plural(/(hive)$/i, '\1s')
@@ -15,7 +17,9 @@ module ActiveSupport
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
inflect.plural(/([m|l])ouse$/i, '\1ice')
+ inflect.plural(/([m|l])ice$/i, '\1ice')
inflect.plural(/^(ox)$/i, '\1en')
+ inflect.plural(/^(oxen)$/i, '\1')
inflect.plural(/(quiz)$/i, '\1zes')
inflect.singular(/s$/i, '')
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index 3caf78bc7d..e136e4c5b3 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -148,7 +148,7 @@ module ActiveSupport
def singularize(word)
result = word.to_s.dup
- if inflections.uncountables.any? { |inflection| result =~ /#{inflection}\Z/i }
+ if inflections.uncountables.any? { |inflection| result =~ /\b(#{inflection})\Z/i }
result
else
inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
diff --git a/activesupport/lib/active_support/json/backends/jsongem.rb b/activesupport/lib/active_support/json/backends/jsongem.rb
index cfe28d7bb9..533ba25da3 100644
--- a/activesupport/lib/active_support/json/backends/jsongem.rb
+++ b/activesupport/lib/active_support/json/backends/jsongem.rb
@@ -26,7 +26,11 @@ module ActiveSupport
when nil
nil
when DATE_REGEX
- DateTime.parse(data)
+ begin
+ DateTime.parse(data)
+ rescue ArgumentError
+ data
+ end
when Array
data.map! { |d| convert_dates_from(d) }
when Hash
diff --git a/activesupport/lib/active_support/json/backends/yajl.rb b/activesupport/lib/active_support/json/backends/yajl.rb
index 64e50e0d87..58818658c7 100644
--- a/activesupport/lib/active_support/json/backends/yajl.rb
+++ b/activesupport/lib/active_support/json/backends/yajl.rb
@@ -23,7 +23,11 @@ module ActiveSupport
when nil
nil
when DATE_REGEX
- DateTime.parse(data)
+ begin
+ DateTime.parse(data)
+ rescue ArgumentError
+ data
+ end
when Array
data.map! { |d| convert_dates_from(d) }
when Hash
diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb
index 4cb9d01077..077eda548a 100644
--- a/activesupport/lib/active_support/json/backends/yaml.rb
+++ b/activesupport/lib/active_support/json/backends/yaml.rb
@@ -7,14 +7,21 @@ module ActiveSupport
ParseError = ::StandardError
extend self
+ EXCEPTIONS = [::ArgumentError] # :nodoc:
+ begin
+ require 'psych'
+ EXCEPTIONS << Psych::SyntaxError
+ rescue LoadError
+ end
+
# Parses a JSON string or IO and converts it into an object
def decode(json)
if json.respond_to?(:read)
json = json.read
end
YAML.load(convert_json_to_yaml(json))
- rescue ArgumentError
- raise ParseError, "Invalid JSON string"
+ rescue *EXCEPTIONS => e
+ raise ParseError, "Invalid JSON string: '%s'" % json
end
protected
@@ -29,10 +36,10 @@ module ActiveSupport
quoting = char
pos = scanner.pos
elsif quoting == char
- if json[pos..scanner.pos-2] =~ DATE_REGEX
+ if valid_date?(json[pos..scanner.pos-2])
# found a date, track the exact positions of the quotes so we can
# overwrite them with spaces later.
- times << pos << scanner.pos
+ times << pos
end
quoting = false
end
@@ -47,7 +54,9 @@ module ActiveSupport
json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do
ustr = $1
if ustr.start_with?('u')
- [ustr[1..-1].to_i(16)].pack("U")
+ char = [ustr[1..-1].to_i(16)].pack("U")
+ # "\n" needs extra escaping due to yaml formatting
+ char == "\n" ? "\\n" : char
elsif ustr == '\\'
'\\\\'
else
@@ -63,12 +72,14 @@ module ActiveSupport
chunk = scanner.peek(right_pos[i] - scanner.pos + 1)
# overwrite the quotes found around the dates with spaces
while times.size > 0 && times[0] <= right_pos[i]
- chunk[times.shift - scanner.pos - 1] = ' '
+ chunk.insert(times.shift - scanner.pos - 1, '! ')
end
chunk.gsub!(/\\([\\\/]|u[[:xdigit:]]{4})/) do
ustr = $1
if ustr.start_with?('u')
- [ustr[1..-1].to_i(16)].pack("U")
+ char = [ustr[1..-1].to_i(16)].pack("U")
+ # "\n" needs extra escaping due to yaml formatting
+ char == "\n" ? "\\n" : char
elsif ustr == '\\'
'\\\\'
else
@@ -83,6 +94,16 @@ module ActiveSupport
output
end
end
+
+ private
+ def valid_date?(date_string)
+ begin
+ date_string =~ DATE_REGEX && DateTime.parse(date_string)
+ rescue ArgumentError
+ false
+ end
+ end
+
end
end
end
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index c8cac52027..82b8a7e148 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -23,7 +23,7 @@ module ActiveSupport
module JSON
# matches YAML-formatted dates
- DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[ \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
+ DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
def self.encode(value, options = nil)
@@ -153,6 +153,12 @@ class Object
end
end
+class Struct
+ def as_json(options = nil) #:nodoc:
+ Hash[members.zip(values)]
+ end
+end
+
class TrueClass
AS_JSON = ActiveSupport::JSON::Variable.new('true').freeze
def as_json(options = nil) AS_JSON end #:nodoc:
diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb
index 5c24b9c759..52a64383a2 100644
--- a/activesupport/lib/active_support/log_subscriber/test_helper.rb
+++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb
@@ -38,13 +38,14 @@ module ActiveSupport
ActiveSupport::LogSubscriber.colorize_logging = false
+ @old_notifier = ActiveSupport::Notifications.notifier
set_logger(@logger)
ActiveSupport::Notifications.notifier = @notifier
end
def teardown
set_logger(nil)
- ActiveSupport::Notifications.notifier = nil
+ ActiveSupport::Notifications.notifier = @old_notifier
end
class MockLogger
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index fd79188ba4..77696eb1db 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -44,8 +44,11 @@ module ActiveSupport
@instrumenters = Hash.new { |h,k| h[k] = notifier.listening?(k) }
class << self
- attr_writer :notifier
- delegate :publish, :to => :notifier
+ attr_accessor :notifier
+
+ def publish(name, *args)
+ notifier.publish(name, *args)
+ end
def instrument(name, payload = {})
if @instrumenters[name]
@@ -61,18 +64,16 @@ module ActiveSupport
end
end
- def unsubscribe(*args)
- notifier.unsubscribe(*args)
+ def unsubscribe(args)
+ notifier.unsubscribe(args)
@instrumenters.clear
end
- def notifier
- @notifier ||= Fanout.new
- end
-
def instrumenter
Thread.current[:"instrumentation_#{notifier.object_id}"] ||= Instrumenter.new(notifier)
end
end
+
+ self.notifier = Fanout.new
end
end
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 8e157d3af4..fbc40d1b69 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -1,3 +1,8 @@
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
YAML.add_builtin_type("omap") do |type, val|
@@ -20,9 +25,17 @@ module ActiveSupport
"!tag:yaml.org,2002:omap"
end
+ def encode_with(coder)
+ coder.represent_seq '!omap', map { |k,v| { k => v } }
+ end
+
def to_yaml(opts = {})
+ if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
+ return super
+ end
+
YAML.quick_emit(self, opts) do |out|
- out.seq(taguri, to_yaml_style) do |seq|
+ out.seq(taguri) do |seq|
each do |k, v|
seq.add(k => v)
end
@@ -124,15 +137,21 @@ module ActiveSupport
end
def each_key
+ return to_enum(:each_key) unless block_given?
@keys.each { |key| yield key }
+ self
end
def each_value
+ return to_enum(:each_value) unless block_given?
@keys.each { |key| yield self[key]}
+ self
end
def each
+ return to_enum(:each) unless block_given?
@keys.each {|key| yield [key, self[key]]}
+ self
end
alias_method :each_pair, :each
diff --git a/activesupport/lib/active_support/ordered_options.rb b/activesupport/lib/active_support/ordered_options.rb
index 124e1a74f8..b40cbceb7e 100644
--- a/activesupport/lib/active_support/ordered_options.rb
+++ b/activesupport/lib/active_support/ordered_options.rb
@@ -31,7 +31,7 @@ module ActiveSupport #:nodoc:
def method_missing(name, *args)
if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
+ self[$1] = args.first
else
self[name]
end
diff --git a/activesupport/lib/active_support/testing/performance.rb b/activesupport/lib/active_support/testing/performance.rb
index 64b436ba8c..8c91a061fb 100644
--- a/activesupport/lib/active_support/testing/performance.rb
+++ b/activesupport/lib/active_support/testing/performance.rb
@@ -401,7 +401,7 @@ begin
Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
# Ruby 1.9 with GC::Profiler
- if GC.respond_to?(:total_time)
+ if defined?(GC::Profiler) && GC::Profiler.respond_to?(:total_time)
def measure
GC::Profiler.total_time
end
diff --git a/activesupport/lib/active_support/testing/setup_and_teardown.rb b/activesupport/lib/active_support/testing/setup_and_teardown.rb
index b2d9ddfeb7..22e41fa905 100644
--- a/activesupport/lib/active_support/testing/setup_and_teardown.rb
+++ b/activesupport/lib/active_support/testing/setup_and_teardown.rb
@@ -31,14 +31,14 @@ module ActiveSupport
def run(runner)
result = '.'
begin
- _run_setup_callbacks do
+ run_callbacks :setup do
result = super
end
rescue Exception => e
result = runner.puke(self.class, method_name, e)
ensure
begin
- _run_teardown_callbacks
+ run_callbacks :teardown
rescue Exception => e
result = runner.puke(self.class, method_name, e)
end
@@ -62,7 +62,7 @@ module ActiveSupport
begin
begin
- _run_setup_callbacks do
+ run_callbacks :setup do
setup
__send__(@method_name)
mocha_verify(mocha_counter) if mocha_counter
@@ -77,7 +77,7 @@ module ActiveSupport
ensure
begin
teardown
- _run_teardown_callbacks
+ run_callbacks :teardown
rescue Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception => e
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 6a7da8266c..3da216ac78 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -137,14 +137,20 @@ module ActiveSupport
end
end
- def to_yaml(options = {})
- if options.kind_of?(YAML::Emitter)
- utc.to_yaml(options)
+ def encode_with(coder)
+ if coder.respond_to?(:represent_object)
+ coder.represent_object(nil, utc)
else
- time.to_yaml(options).gsub('Z', formatted_offset(true, 'Z'))
+ coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
end
end
+ def to_yaml(options = {})
+ return super if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
+
+ utc.to_yaml(options)
+ end
+
def httpdate
utc.httpdate
end
diff --git a/activesupport/lib/active_support/xml_mini/libxml.rb b/activesupport/lib/active_support/xml_mini/libxml.rb
index 7fdcb11465..16570c6aea 100644
--- a/activesupport/lib/active_support/xml_mini/libxml.rb
+++ b/activesupport/lib/active_support/xml_mini/libxml.rb
@@ -1,5 +1,6 @@
require 'libxml'
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini LibXML implementation
module ActiveSupport
diff --git a/activesupport/lib/active_support/xml_mini/libxmlsax.rb b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
index fe2c1b9349..2536b1f33e 100644
--- a/activesupport/lib/active_support/xml_mini/libxmlsax.rb
+++ b/activesupport/lib/active_support/xml_mini/libxmlsax.rb
@@ -1,5 +1,6 @@
require 'libxml'
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini LibXML implementation using a SAX-based parser
module ActiveSupport
@@ -82,4 +83,4 @@ module ActiveSupport
end
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/xml_mini/nokogiri.rb b/activesupport/lib/active_support/xml_mini/nokogiri.rb
index e03a744257..04ec9e8ab8 100644
--- a/activesupport/lib/active_support/xml_mini/nokogiri.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogiri.rb
@@ -5,6 +5,7 @@ rescue LoadError => e
raise e
end
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini Nokogiri implementation
module ActiveSupport
diff --git a/activesupport/lib/active_support/xml_mini/nokogirisax.rb b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
index 25afbfcd1c..93fd3dfe57 100644
--- a/activesupport/lib/active_support/xml_mini/nokogirisax.rb
+++ b/activesupport/lib/active_support/xml_mini/nokogirisax.rb
@@ -5,6 +5,7 @@ rescue LoadError => e
raise e
end
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini Nokogiri implementation using a SAX-based parser
module ActiveSupport
diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb
index 36692af1d3..a13ad10118 100644
--- a/activesupport/lib/active_support/xml_mini/rexml.rb
+++ b/activesupport/lib/active_support/xml_mini/rexml.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/object/blank'
+require 'stringio'
# = XmlMini ReXML implementation
module ActiveSupport
diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb
index 97c0ef14db..8d1b1c02c6 100644
--- a/activesupport/test/buffered_logger_test.rb
+++ b/activesupport/test/buffered_logger_test.rb
@@ -115,11 +115,9 @@ class BufferedLoggerTest < Test::Unit::TestCase
def test_should_create_the_log_directory_if_it_doesnt_exist
tmp_directory = File.join(File.dirname(__FILE__), "tmp")
log_file = File.join(tmp_directory, "development.log")
- assert !File.exist?(tmp_directory)
+ FileUtils.rm_rf(tmp_directory)
@logger = Logger.new(log_file)
assert File.exist?(tmp_directory)
- ensure
- FileUtils.rm_rf(tmp_directory)
end
def test_logger_should_maintain_separate_buffers_for_each_thread
diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb
index 8caf000c5d..71249050fc 100644
--- a/activesupport/test/callback_inheritance_test.rb
+++ b/activesupport/test/callback_inheritance_test.rb
@@ -70,7 +70,7 @@ class EmptyParent
end
def dispatch
- _run_dispatch_callbacks
+ run_callbacks :dispatch
self
end
end
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
index 51b28b6a43..cff914f4ae 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -3,6 +3,27 @@ require 'test/unit'
require 'active_support'
module CallbacksTest
+ class Phone
+ include ActiveSupport::Callbacks
+ define_callbacks :save, :rescuable => true
+
+ set_callback :save, :before, :before_save1
+ set_callback :save, :after, :after_save1
+
+ def before_save1; self.history << :before; end
+ def after_save1; self.history << :after; end
+
+ def save
+ run_callbacks :save do
+ raise 'boom'
+ end
+ end
+
+ def history
+ @history ||= []
+ end
+ end
+
class Record
include ActiveSupport::Callbacks
@@ -338,6 +359,14 @@ module CallbacksTest
end
class CallbacksTest < Test::Unit::TestCase
+ def test_save_phone
+ phone = Phone.new
+ assert_raise RuntimeError do
+ phone.save
+ end
+ assert_equal [:before, :after], phone.history
+ end
+
def test_save_person
person = Person.new
assert_equal [], person.history
@@ -573,5 +602,5 @@ module CallbacksTest
], writer.history
end
end
-
+
end
diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb
new file mode 100644
index 0000000000..8445af8d25
--- /dev/null
+++ b/activesupport/test/class_cache_test.rb
@@ -0,0 +1,108 @@
+require 'abstract_unit'
+require 'active_support/dependencies'
+
+module ActiveSupport
+ module Dependencies
+ class ClassCacheTest < ActiveSupport::TestCase
+ def setup
+ @cache = ClassCache.new
+ end
+
+ def test_empty?
+ assert @cache.empty?
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert !@cache.empty?
+ end
+
+ def test_clear!
+ assert @cache.empty?
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert !@cache.empty?
+ @cache.clear!
+ assert @cache.empty?
+ end
+
+ def test_set_key
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert @cache.key?(ClassCacheTest.name)
+ end
+
+ def test_set_rejects_strings
+ @cache[ClassCacheTest.name] = ClassCacheTest
+ assert @cache.empty?
+ end
+
+ def test_get_with_class
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert_equal ClassCacheTest, @cache[ClassCacheTest]
+ end
+
+ def test_get_with_name
+ @cache[ClassCacheTest] = ClassCacheTest
+ assert_equal ClassCacheTest, @cache[ClassCacheTest.name]
+ end
+
+ def test_get_constantizes
+ assert @cache.empty?
+ assert_equal ClassCacheTest, @cache[ClassCacheTest.name]
+ end
+
+ def test_get_is_an_alias
+ assert_equal @cache[ClassCacheTest], @cache.get(ClassCacheTest.name)
+ end
+
+ def test_new
+ assert_deprecated do
+ @cache.new ClassCacheTest
+ end
+ assert @cache.key?(ClassCacheTest.name)
+ end
+
+ def test_new_rejects_strings
+ assert_deprecated do
+ @cache.new ClassCacheTest.name
+ end
+ assert !@cache.key?(ClassCacheTest.name)
+ end
+
+ def test_new_rejects_strings
+ @cache.store ClassCacheTest.name
+ assert !@cache.key?(ClassCacheTest.name)
+ end
+
+ def test_store_returns_self
+ x = @cache.store ClassCacheTest
+ assert_equal @cache, x
+ end
+
+ def test_new_returns_proxy
+ v = nil
+ assert_deprecated do
+ v = @cache.new ClassCacheTest.name
+ end
+
+ assert_deprecated do
+ assert_equal ClassCacheTest, v.get
+ end
+ end
+
+ def test_anonymous_class_fail
+ assert_raises(ArgumentError) do
+ assert_deprecated do
+ @cache.new Class.new
+ end
+ end
+
+ assert_raises(ArgumentError) do
+ x = Class.new
+ @cache[x] = x
+ end
+
+ assert_raises(ArgumentError) do
+ x = Class.new
+ @cache.store x
+ end
+ end
+ end
+ end
+end
diff --git a/activesupport/test/configurable_test.rb b/activesupport/test/configurable_test.rb
index 9c773c1944..2b28e61815 100644
--- a/activesupport/test/configurable_test.rb
+++ b/activesupport/test/configurable_test.rb
@@ -21,6 +21,12 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_equal({ :foo => :bar }, Parent.config)
end
+ test "adds a configuration hash to a module as well" do
+ mixin = Module.new { include ActiveSupport::Configurable }
+ mixin.config.foo = :bar
+ assert_equal({ :foo => :bar }, mixin.config)
+ end
+
test "configuration hash is inheritable" do
assert_equal :bar, Child.config.foo
assert_equal :bar, Parent.config.foo
@@ -57,4 +63,4 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_respond_to child.config, :bar
assert_respond_to child.new.config, :bar
end
-end \ No newline at end of file
+end
diff --git a/activesupport/test/core_ext/bigdecimal.rb b/activesupport/test/core_ext/bigdecimal.rb
deleted file mode 100644
index 9faad9146f..0000000000
--- a/activesupport/test/core_ext/bigdecimal.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'abstract_unit'
-
-class BigDecimalTest < Test::Unit::TestCase
- def test_to_yaml
- assert_equal("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml)
- assert_equal("--- .Inf\n", BigDecimal.new('Infinity').to_yaml)
- assert_equal("--- .NaN\n", BigDecimal.new('NaN').to_yaml)
- assert_equal("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml)
- end
-end \ No newline at end of file
diff --git a/activesupport/test/core_ext/bigdecimal_test.rb b/activesupport/test/core_ext/bigdecimal_test.rb
new file mode 100644
index 0000000000..b38e08a9f4
--- /dev/null
+++ b/activesupport/test/core_ext/bigdecimal_test.rb
@@ -0,0 +1,17 @@
+require 'abstract_unit'
+require 'bigdecimal'
+require 'active_support/core_ext/big_decimal'
+
+class BigDecimalTest < Test::Unit::TestCase
+ def test_to_yaml
+ assert_match("--- 100000.30020320320000000000000000000000000000001\n", BigDecimal.new('100000.30020320320000000000000000000000000000001').to_yaml)
+ assert_match("--- .Inf\n", BigDecimal.new('Infinity').to_yaml)
+ assert_match("--- .NaN\n", BigDecimal.new('NaN').to_yaml)
+ assert_match("--- -.Inf\n", BigDecimal.new('-Infinity').to_yaml)
+ end
+
+ def test_to_d
+ bd = BigDecimal.new '10'
+ assert_equal bd, bd.to_d
+ end
+end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index 342a31cdef..03b84ae2e5 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -259,7 +259,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.current - 1, Date.yesterday
end
- def test_yesterday_constructor_when_zone_default_is_not_set
+ def test_yesterday_constructor_when_zone_is_not_set
with_env_tz 'UTC' do
with_tz_default do
Time.stubs(:now).returns Time.local(2000, 1, 1)
@@ -268,7 +268,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_yesterday_constructor_when_zone_default_is_set
+ def test_yesterday_constructor_when_zone_is_set
with_env_tz 'UTC' do
with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
Time.stubs(:now).returns Time.local(2000, 1, 1)
@@ -281,7 +281,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.current + 1, Date.tomorrow
end
- def test_tomorrow_constructor_when_zone_default_is_not_set
+ def test_tomorrow_constructor_when_zone_is_not_set
with_env_tz 'UTC' do
with_tz_default do
Time.stubs(:now).returns Time.local(1999, 12, 31)
@@ -290,7 +290,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_tomorrow_constructor_when_zone_default_is_set
+ def test_tomorrow_constructor_when_zone_is_set
with_env_tz 'UTC' do
with_tz_default ActiveSupport::TimeZone['Europe/Paris'] do # UTC +1
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
@@ -303,7 +303,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,2,21,0,0,45), Date.new(2005,2,21).since(45)
end
- def test_since_when_zone_default_is_set
+ def test_since_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -317,7 +317,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,2,20,23,59,15), Date.new(2005,2,21).ago(45)
end
- def test_ago_when_zone_default_is_set
+ def test_ago_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -331,7 +331,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,2,21,0,0,0), Date.new(2005,2,21).beginning_of_day
end
- def test_beginning_of_day_when_zone_default_is_set
+ def test_beginning_of_day_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -345,7 +345,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,2,21,23,59,59,999999.999), Date.new(2005,2,21).end_of_day
end
- def test_end_of_day_when_zone_default_is_set
+ def test_end_of_day_when_zone_is_set
zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'UTC' do
with_tz_default zone do
@@ -367,7 +367,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_xmlschema_when_zone_default_is_set
+ def test_xmlschema_when_zone_is_set
with_env_tz 'UTC' do
with_tz_default ActiveSupport::TimeZone['Eastern Time (US & Canada)'] do # UTC -5
assert_match(/^1980-02-28T00:00:00-05:?00$/, Date.new(1980, 2, 28).xmlschema)
@@ -376,6 +376,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
+ if RUBY_VERSION < '1.9'
+ def test_rfc3339
+ assert_equal('1980-02-28', Date.new(1980, 2, 28).rfc3339)
+ end
+
+ def test_iso8601
+ assert_equal('1980-02-28', Date.new(1980, 2, 28).iso8601)
+ end
+ end
+
def test_today
Date.stubs(:current).returns(Date.new(2000, 1, 1))
assert_equal false, Date.new(1999, 12, 31).today?
@@ -397,7 +407,7 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal true, Date.new(2000,1,2).future?
end
- def test_current_returns_date_today_when_zone_default_not_set
+ def test_current_returns_date_today_when_zone_not_set
with_env_tz 'US/Central' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
assert_equal Date.new(1999, 12, 31), Date.today
@@ -405,15 +415,15 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
end
- def test_current_returns_time_zone_today_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_current_returns_time_zone_today_when_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Central' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23)
assert_equal Date.new(1999, 12, 31), Date.today
assert_equal Date.new(2000, 1, 1), Date.current
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_date_advance_should_not_change_passed_options_hash
@@ -431,11 +441,11 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
end
def with_tz_default(tz = nil)
- old_tz = Time.zone_default
- Time.zone_default = tz
+ old_tz = Time.zone
+ Time.zone = tz
yield
ensure
- Time.zone_default = old_tz
+ Time.zone = old_tz
end
end
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 7d993d84e2..456736cbad 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -38,6 +38,8 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0, 0).to_time
# DateTimes with offsets other than 0 are returned unaltered
assert_equal DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)), DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).to_time
+ # Fractional seconds are preserved
+ assert_equal Time.utc(2005, 2, 21, 10, 11, 12, 256), DateTime.new(2005, 2, 21, 10, 11, 12 + Rational(256, 1000000), 0).to_time
end
def test_civil_from_format
@@ -280,21 +282,21 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal true, DateTime.civil(2005,2,10,20,30,46).future?
end
- def test_current_returns_date_today_when_zone_default_not_set
+ def test_current_returns_date_today_when_zone_is_not_set
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
end
- def test_current_returns_time_zone_today_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_current_returns_time_zone_today_when_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(1999, 12, 31, 23, 59, 59)
assert_equal DateTime.new(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)), DateTime.current
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_current_without_time_zone
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index bb453b8d7f..c0b529d9f8 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'active_support/time'
+require 'active_support/json'
class DurationTest < ActiveSupport::TestCase
def test_is_a
@@ -88,8 +89,8 @@ class DurationTest < ActiveSupport::TestCase
assert_in_delta((7 * 24 * 1.7).hours.ago(t), 1.7.weeks.ago(t), 1)
end
- def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
- Time.zone_default = nil
+ def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set
+ Time.zone = nil
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -101,8 +102,8 @@ class DurationTest < ActiveSupport::TestCase
end
end
- def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -115,7 +116,7 @@ class DurationTest < ActiveSupport::TestCase
assert_equal 'Eastern Time (US & Canada)', 5.seconds.ago.time_zone.name
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_adding_hours_across_dst_boundary
@@ -138,6 +139,10 @@ class DurationTest < ActiveSupport::TestCase
assert_equal counter, 60
end
+ def test_to_json
+ assert_equal '172800', 2.days.to_json
+ end
+
protected
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 74223dd7f2..a0479d45ac 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -4,6 +4,7 @@ require 'bigdecimal'
require 'active_support/core_ext/string/access'
require 'active_support/ordered_hash'
require 'active_support/core_ext/object/conversions'
+require 'active_support/inflections'
class HashExtTest < Test::Unit::TestCase
class IndifferentHash < HashWithIndifferentAccess
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index 75404ec0e1..a95cf1591f 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -26,14 +26,10 @@ module Yz
end
end
-class De
-end
-
Somewhere = Struct.new(:street, :city)
Someone = Struct.new(:name, :place) do
delegate :street, :city, :to_f, :to => :place
- delegate :state, :to => :@place
delegate :upcase, :to => "place.city"
end
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
index 6ef4e37b26..3a2452b4b0 100644
--- a/activesupport/test/core_ext/numeric_ext_test.rb
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -89,8 +89,8 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal DateTime.civil(2005,2,28,15,15,10), DateTime.civil(2004,2,29,15,15,10) + 1.year
end
- def test_since_and_ago_anchored_to_time_now_when_time_zone_default_not_set
- Time.zone_default = nil
+ def test_since_and_ago_anchored_to_time_now_when_time_zone_is_not_set
+ Time.zone = nil
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -102,8 +102,8 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase
end
end
- def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_since_and_ago_anchored_to_time_zone_now_when_time_zone_is_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
# since
@@ -116,7 +116,7 @@ class NumericExtTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal 'Eastern Time (US & Canada)', 5.ago.time_zone.name
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
protected
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 398e6ca9b2..5d68b198f2 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -28,18 +28,6 @@ module Nested
end
end
-module Bar
- def bar; end
-end
-
-module Baz
- def baz; end
-end
-
-class Foo
- include Bar
-end
-
class ObjectTests < ActiveSupport::TestCase
class DuckTime
def acts_like_time?
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index 5701eeef28..1424fa4aca 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -62,4 +62,16 @@ class RangeTest < Test::Unit::TestCase
(1..10).step(2) {|i| array << i }
assert_equal [1,3,5,7,9], array
end
+
+ if RUBY_VERSION < '1.9'
+ def test_cover
+ assert((1..3).cover?(2))
+ assert !(1..3).cover?(4)
+ end
+ else
+ def test_cover_is_not_override
+ range = (1..3)
+ assert range.method(:include?) != range.method(:cover?)
+ end
+ end
end
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index 53d497013a..891a6badac 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -533,19 +533,9 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
Time::DATE_FORMATS.delete(:custom)
end
- def test_to_date
- assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date
- end
-
- def test_to_datetime
- assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0, 0)
- with_env_tz 'US/Eastern' do
- assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0)
- end
- with_env_tz 'NZ' do
- assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0)
- end
- assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value
+ def test_conversion_methods_are_publicized
+ assert Time.public_instance_methods.include?(:to_date) || Time.public_instance_methods.include?('to_date')
+ assert Time.public_instance_methods.include?(:to_datetime) || Time.public_instance_methods.include?('to_datetime')
end
def test_to_time
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 5579c27215..bafa335a09 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -106,11 +106,11 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_to_yaml
- assert_equal "--- 1999-12-31 19:00:00 -05:00\n", @twz.to_yaml
+ assert_match(/^--- 2000-01-01 00:00:00(\.0+)?\s*Z\n/, @twz.to_yaml)
end
def test_ruby_to_yaml
- assert_equal "--- \n:twz: 2000-01-01 00:00:00 Z\n", {:twz => @twz}.to_yaml
+ assert_match(/---\s*\n:twz: 2000-01-01 00:00:00(\.0+)?\s*Z\n/, {:twz => @twz}.to_yaml)
end
def test_httpdate
@@ -768,10 +768,10 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
def test_localtime
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
assert_equal @dt.in_time_zone.localtime, @dt.in_time_zone.utc.to_time.getlocal
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
def test_use_zone
@@ -801,7 +801,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal nil, Time.zone
end
- def test_time_zone_getter_and_setter_with_zone_default
+ def test_time_zone_getter_and_setter_with_zone_default_set
Time.zone_default = ActiveSupport::TimeZone['Alaska']
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
Time.zone = ActiveSupport::TimeZone['Hawaii']
@@ -809,6 +809,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
Time.zone = nil
assert_equal ActiveSupport::TimeZone['Alaska'], Time.zone
ensure
+ Time.zone = nil
Time.zone_default = nil
end
@@ -849,7 +850,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_nil Time.zone
end
- def test_current_returns_time_now_when_zone_default_not_set
+ def test_current_returns_time_now_when_zone_not_set
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
assert_equal false, Time.current.is_a?(ActiveSupport::TimeWithZone)
@@ -857,8 +858,8 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
end
end
- def test_current_returns_time_zone_now_when_zone_default_set
- Time.zone_default = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ def test_current_returns_time_zone_now_when_zone_set
+ Time.zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
with_env_tz 'US/Eastern' do
Time.stubs(:now).returns Time.local(2000)
assert_equal true, Time.current.is_a?(ActiveSupport::TimeWithZone)
@@ -866,7 +867,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < Test::Unit::TestCase
assert_equal Time.utc(2000), Time.current.time
end
ensure
- Time.zone_default = nil
+ Time.zone = nil
end
protected
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index bc7f597f1d..ef017d7436 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -477,15 +477,15 @@ class DependenciesTest < Test::Unit::TestCase
def test_references_should_work
with_loading 'dependencies' do
- c = ActiveSupport::Dependencies.ref("ServiceOne")
+ c = ActiveSupport::Dependencies.reference("ServiceOne")
service_one_first = ServiceOne
- assert_equal service_one_first, c.get
+ assert_equal service_one_first, c.get("ServiceOne")
ActiveSupport::Dependencies.clear
assert ! defined?(ServiceOne)
service_one_second = ServiceOne
- assert_not_equal service_one_first, c.get
- assert_equal service_one_second, c.get
+ assert_not_equal service_one_first, c.get("ServiceOne")
+ assert_equal service_one_second, c.get("ServiceOne")
end
end
diff --git a/activesupport/test/file_watcher_test.rb b/activesupport/test/file_watcher_test.rb
new file mode 100644
index 0000000000..7b4d4be24f
--- /dev/null
+++ b/activesupport/test/file_watcher_test.rb
@@ -0,0 +1,233 @@
+require 'abstract_unit'
+require 'fssm'
+require "fileutils"
+require "timeout"
+
+
+class FileWatcherTest < ActiveSupport::TestCase
+ class DumbBackend < ActiveSupport::FileWatcher::Backend
+ end
+
+ def setup
+ @watcher = ActiveSupport::FileWatcher.new
+
+ # In real life, the backend would take the path and use it to observe the file
+ # system. In our case, we will manually trigger the events for unit testing,
+ # so we can pass any path.
+ @backend = DumbBackend.new("RAILS_WOOT", @watcher)
+
+ @payload = []
+ @watcher.watch %r{^app/assets/.*\.scss$} do |pay|
+ pay.each do |status, files|
+ files.sort!
+ end
+ @payload << pay
+ end
+ end
+
+ def test_use_triple_equals
+ fw = ActiveSupport::FileWatcher.new
+ called = []
+ fw.watch("some_arbitrary_file.rb") do |file|
+ called << "omg"
+ end
+ fw.trigger(%w{ some_arbitrary_file.rb })
+ assert_equal ['omg'], called
+ end
+
+ def test_one_change
+ @backend.trigger("app/assets/main.scss" => :changed)
+ assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first)
+ end
+
+ def test_multiple_changes
+ @backend.trigger("app/assets/main.scss" => :changed, "app/assets/javascripts/foo.coffee" => :changed)
+ assert_equal([{:changed => ["app/assets/main.scss"]}], @payload)
+ end
+
+ def test_multiple_changes_match
+ @backend.trigger("app/assets/main.scss" => :changed, "app/assets/print.scss" => :changed, "app/assets/javascripts/foo.coffee" => :changed)
+ assert_equal([{:changed => ["app/assets/main.scss", "app/assets/print.scss"]}], @payload)
+ end
+
+ def test_multiple_state_changes
+ @backend.trigger("app/assets/main.scss" => :created, "app/assets/print.scss" => :changed)
+ assert_equal([{:changed => ["app/assets/print.scss"], :created => ["app/assets/main.scss"]}], @payload)
+ end
+
+ def test_more_blocks
+ payload = []
+ @watcher.watch %r{^config/routes\.rb$} do |pay|
+ payload << pay
+ end
+
+ @backend.trigger "config/routes.rb" => :changed
+ assert_equal [:changed => ["config/routes.rb"]], payload
+ assert_equal [], @payload
+ end
+
+ def test_overlapping_watchers
+ payload = []
+ @watcher.watch %r{^app/assets/main\.scss$} do |pay|
+ payload << pay
+ end
+
+ @backend.trigger "app/assets/print.scss" => :changed, "app/assets/main.scss" => :changed
+ assert_equal [:changed => ["app/assets/main.scss"]], payload
+ assert_equal [:changed => ["app/assets/main.scss", "app/assets/print.scss"]], @payload
+ end
+end
+
+module FSSM::Backends
+ class Polling
+ def initialize_with_low_latency(options={})
+ initialize_without_low_latency(options.merge(:latency => 0.1))
+ end
+ alias_method_chain :initialize, :low_latency
+ end
+end
+
+class FSSMFileWatcherTest < ActiveSupport::TestCase
+ class FSSMBackend < ActiveSupport::FileWatcher::Backend
+ def initialize(path, watcher)
+ super
+
+ monitor = FSSM::Monitor.new
+ monitor.path(path, '**/*') do |p|
+ p.update { |base, relative| trigger relative => :changed }
+ p.delete { |base, relative| trigger relative => :deleted }
+ p.create { |base, relative| trigger relative => :created }
+ end
+
+ @thread = Thread.new do
+ monitor.run
+ end
+ end
+
+ def stop
+ @thread.kill
+ end
+ end
+
+ def setup
+ Thread.abort_on_exception = true
+
+ @payload = []
+ @triggered = false
+
+ @watcher = ActiveSupport::FileWatcher.new
+
+ @path = path = File.expand_path("../tmp", __FILE__)
+ FileUtils.rm_rf path
+
+ create "app/assets/main.scss", true
+ create "app/assets/javascripts/foo.coffee", true
+ create "app/assets/print.scss", true
+ create "app/assets/videos.scss", true
+
+ @backend = FSSMBackend.new(path, @watcher)
+
+ @watcher.watch %r{^app/assets/.*\.scss$} do |pay|
+ pay.each do |status, files|
+ files.sort!
+ end
+ @payload << pay
+ trigger
+ end
+ end
+
+ def teardown
+ @backend.stop
+ Thread.abort_on_exception = false
+ end
+
+ def create(path, past = false)
+ wait(past) do
+ path = File.join(@path, path)
+ FileUtils.mkdir_p(File.dirname(path))
+
+ FileUtils.touch(path)
+ File.utime(Time.now - 100, Time.now - 100, path) if past
+ end
+ end
+
+ def change(path)
+ wait do
+ FileUtils.touch(File.join(@path, path))
+ end
+ end
+
+ def delete(path)
+ wait do
+ FileUtils.rm(File.join(@path, path))
+ end
+ end
+
+ def wait(past = false)
+ yield
+ return if past
+
+ begin
+ Timeout.timeout(1) do
+ sleep 0.05 until @triggered
+ end
+ rescue Timeout::Error
+ end
+
+ @triggered = false
+ end
+
+ def trigger
+ @triggered = true
+ end
+
+ def test_one_change
+ change "app/assets/main.scss"
+ assert_equal({:changed => ["app/assets/main.scss"]}, @payload.first)
+ end
+
+ def test_multiple_changes
+ change "app/assets/main.scss"
+ change "app/assets/javascripts/foo.coffee"
+ assert_equal([{:changed => ["app/assets/main.scss"]}], @payload)
+ end
+
+ def test_multiple_changes_match
+ change "app/assets/main.scss"
+ change "app/assets/print.scss"
+ change "app/assets/javascripts/foo.coffee"
+ assert_equal([{:changed => ["app/assets/main.scss"]}, {:changed => ["app/assets/print.scss"]}], @payload)
+ end
+
+ def test_multiple_state_changes
+ create "app/assets/new.scss"
+ change "app/assets/print.scss"
+ delete "app/assets/videos.scss"
+ assert_equal([{:created => ["app/assets/new.scss"]}, {:changed => ["app/assets/print.scss"]}, {:deleted => ["app/assets/videos.scss"]}], @payload)
+ end
+
+ def test_more_blocks
+ payload = []
+ @watcher.watch %r{^config/routes\.rb$} do |pay|
+ payload << pay
+ trigger
+ end
+
+ create "config/routes.rb"
+ assert_equal [{:created => ["config/routes.rb"]}], payload
+ assert_equal [], @payload
+ end
+
+ def test_overlapping_watchers
+ payload = []
+ @watcher.watch %r{^app/assets/main\.scss$} do |pay|
+ payload << pay
+ trigger
+ end
+
+ change "app/assets/main.scss"
+ change "app/assets/print.scss"
+ assert_equal [{:changed => ["app/assets/main.scss"]}], payload
+ assert_equal [{:changed => ["app/assets/main.scss"]}, {:changed => ["app/assets/print.scss"]}], @payload
+ end
+end
diff --git a/activesupport/test/gzip_test.rb b/activesupport/test/gzip_test.rb
index 2a24c0bd0d..f564e63f29 100644
--- a/activesupport/test/gzip_test.rb
+++ b/activesupport/test/gzip_test.rb
@@ -1,7 +1,18 @@
require 'abstract_unit'
+require 'active_support/core_ext/object/blank'
class GzipTest < Test::Unit::TestCase
def test_compress_should_decompress_to_the_same_value
assert_equal "Hello World", ActiveSupport::Gzip.decompress(ActiveSupport::Gzip.compress("Hello World"))
end
-end \ No newline at end of file
+
+ def test_compress_should_return_a_binary_string
+ compressed = ActiveSupport::Gzip.compress('')
+
+ if "".encoding_aware?
+ assert_equal Encoding.find('binary'), compressed.encoding
+ end
+
+ assert !compressed.blank?, "a compressed blank string should not be blank"
+ end
+end
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index 2990177bed..1670d9ee7d 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -22,20 +22,55 @@ class InflectorTest < Test::Unit::TestCase
assert_equal "", ActiveSupport::Inflector.pluralize("")
end
+ ActiveSupport::Inflector.inflections.uncountable.each do |word|
+ define_method "test_uncountability_of_#{word}" do
+ assert_equal word, ActiveSupport::Inflector.singularize(word)
+ assert_equal word, ActiveSupport::Inflector.pluralize(word)
+ assert_equal ActiveSupport::Inflector.pluralize(word), ActiveSupport::Inflector.singularize(word)
+ end
+ end
+
+ def test_uncountable_word_is_not_greedy
+ uncountable_word = "ors"
+ countable_word = "sponsor"
+
+ cached_uncountables = ActiveSupport::Inflector.inflections.uncountables
+
+ ActiveSupport::Inflector.inflections.uncountable << uncountable_word
+
+ assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word)
+ assert_equal uncountable_word, ActiveSupport::Inflector.pluralize(uncountable_word)
+ assert_equal ActiveSupport::Inflector.pluralize(uncountable_word), ActiveSupport::Inflector.singularize(uncountable_word)
+
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word)
+ assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word)
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word))
+
+ ensure
+ ActiveSupport::Inflector.inflections.instance_variable_set :@uncountables, cached_uncountables
+ end
+
SingularToPlural.each do |singular, plural|
- define_method "test_pluralize_#{singular}" do
+ define_method "test_pluralize_singular_#{singular}" do
assert_equal(plural, ActiveSupport::Inflector.pluralize(singular))
assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(singular.capitalize))
end
end
SingularToPlural.each do |singular, plural|
- define_method "test_singularize_#{plural}" do
+ define_method "test_singularize_plural_#{plural}" do
assert_equal(singular, ActiveSupport::Inflector.singularize(plural))
assert_equal(singular.capitalize, ActiveSupport::Inflector.singularize(plural.capitalize))
end
end
+ SingularToPlural.each do |singular, plural|
+ define_method "test_pluralize_plural_#{plural}" do
+ assert_equal(plural, ActiveSupport::Inflector.pluralize(plural))
+ assert_equal(plural.capitalize, ActiveSupport::Inflector.pluralize(plural.capitalize))
+ end
+ end
+
def test_overwrite_previous_inflectors
assert_equal("series", ActiveSupport::Inflector.singularize("series"))
ActiveSupport::Inflector.inflections.singular "series", "serie"
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 59515dad32..2b144e5931 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -44,6 +44,7 @@ module InflectorTestCases
"datum" => "data",
"medium" => "media",
+ "stadium" => "stadia",
"analysis" => "analyses",
"node_child" => "node_children",
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index d2e3efaa6b..24d9f88c09 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -19,6 +19,12 @@ class TestJSONDecoding < ActiveSupport::TestCase
%({"a": "2007-01-01 01:12:34 Z"}) => {'a' => Time.utc(2007, 1, 1, 1, 12, 34)},
# no time zone
%({"a": "2007-01-01 01:12:34"}) => {'a' => "2007-01-01 01:12:34"},
+ # invalid date
+ %({"a": "1089-10-40"}) => {'a' => "1089-10-40"},
+ # xmlschema date notation
+ %({"a": "2009-08-10T19:01:02Z"}) => {'a' => Time.utc(2009, 8, 10, 19, 1, 2)},
+ %({"a": "2009-08-10T19:01:02+02:00"}) => {'a' => Time.utc(2009, 8, 10, 17, 1, 2)},
+ %({"a": "2009-08-10T19:01:02-05:00"}) => {'a' => Time.utc(2009, 8, 11, 00, 1, 2)},
# needs to be *exact*
%({"a": " 2007-01-01 01:12:34 Z "}) => {'a' => " 2007-01-01 01:12:34 Z "},
%({"a": "2007-01-01 : it's your birthday"}) => {'a' => "2007-01-01 : it's your birthday"},
@@ -41,7 +47,11 @@ class TestJSONDecoding < ActiveSupport::TestCase
[{'d' => Date.new(1970, 1, 1), 's' => ' escape'},{'d' => Date.new(1970, 1, 1), 's' => ' escape'}],
%q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) =>
[{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'},
- {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}]
+ {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}],
+ # tests escaping of "\n" char with Yaml backend
+ %q({"a":"\n"}) => {"a"=>"\n"},
+ %q({"a":"\u000a"}) => {"a"=>"\n"},
+ %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"}
}
# load the default JSON backend
@@ -57,9 +67,7 @@ class TestJSONDecoding < ActiveSupport::TestCase
ActiveSupport.parse_json_times = true
silence_warnings do
ActiveSupport::JSON.with_backend backend do
- assert_nothing_raised do
- assert_equal expected, ActiveSupport::JSON.decode(json)
- end
+ assert_equal expected, ActiveSupport::JSON.decode(json)
end
end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index e0494de6e4..d5fcbf15b7 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -1,5 +1,6 @@
# encoding: utf-8
require 'abstract_unit'
+require 'active_support/core_ext/string/inflections'
require 'active_support/json'
class TestJSONEncoding < Test::Unit::TestCase
@@ -214,6 +215,36 @@ class TestJSONEncoding < Test::Unit::TestCase
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end
+ def test_struct_encoding
+ Struct.new('UserNameAndEmail', :name, :email)
+ Struct.new('UserNameAndDate', :name, :date)
+ Struct.new('Custom', :name, :sub)
+ user_email = Struct::UserNameAndEmail.new 'David', 'sample@example.com'
+ user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01)
+ custom = Struct::Custom.new 'David', user_birthday
+
+
+ json_strings = ""
+ json_string_and_date = ""
+ json_custom = ""
+
+ assert_nothing_raised do
+ json_strings = user_email.to_json
+ json_string_and_date = user_birthday.to_json
+ json_custom = custom.to_json
+ end
+
+ assert_equal({"name" => "David",
+ "sub" => {
+ "name" => "David",
+ "date" => "2010/01/01" }}, JSON.parse(json_custom))
+
+ assert_equal({"name" => "David", "email" => "sample@example.com"},
+ JSON.parse(json_strings))
+
+ assert_equal({"name" => "David", "date" => "2010/01/01"},
+ JSON.parse(json_string_and_date))
+ end
protected
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index 9faa11efbc..7b48b3f85b 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -3,14 +3,19 @@ require 'abstract_unit'
module Notifications
class TestCase < ActiveSupport::TestCase
def setup
- ActiveSupport::Notifications.notifier = nil
- @notifier = ActiveSupport::Notifications.notifier
+ @old_notifier = ActiveSupport::Notifications.notifier
+ @notifier = ActiveSupport::Notifications::Fanout.new
+ ActiveSupport::Notifications.notifier = @notifier
@events = []
@named_events = []
@subscription = @notifier.subscribe { |*args| @events << event(*args) }
@named_subscription = @notifier.subscribe("named.subscription") { |*args| @named_events << event(*args) }
end
+ def teardown
+ ActiveSupport::Notifications.notifier = @old_notifier
+ end
+
private
def event(*args)
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index 72088854fc..50168fa78f 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -78,20 +78,26 @@ class OrderedHashTest < Test::Unit::TestCase
def test_each_key
keys = []
- @ordered_hash.each_key { |k| keys << k }
+ assert_equal @ordered_hash, @ordered_hash.each_key { |k| keys << k }
assert_equal @keys, keys
+ expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator
+ assert_kind_of expected_class, @ordered_hash.each_key
end
def test_each_value
values = []
- @ordered_hash.each_value { |v| values << v }
+ assert_equal @ordered_hash, @ordered_hash.each_value { |v| values << v }
assert_equal @values, values
+ expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator
+ assert_kind_of expected_class, @ordered_hash.each_value
end
def test_each
values = []
- @ordered_hash.each {|key, value| values << value}
+ assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value}
assert_equal @values, values
+ expected_class = RUBY_VERSION < '1.9' ? Enumerable::Enumerator : Enumerator
+ assert_kind_of expected_class, @ordered_hash.each
end
def test_each_with_index
@@ -239,14 +245,14 @@ class OrderedHashTest < Test::Unit::TestCase
def test_each_after_yaml_serialization
values = []
- @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
@deserialized_ordered_hash.each {|key, value| values << value}
assert_equal @values, values
end
def test_order_after_yaml_serialization
- @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
assert_equal @keys, @deserialized_ordered_hash.keys
assert_equal @values, @deserialized_ordered_hash.values
@@ -255,12 +261,34 @@ class OrderedHashTest < Test::Unit::TestCase
def test_order_after_yaml_serialization_with_nested_arrays
@ordered_hash[:array] = %w(a b c)
- @deserialized_ordered_hash = YAML::load(YAML::dump(@ordered_hash))
+ @deserialized_ordered_hash = YAML.load(YAML.dump(@ordered_hash))
assert_equal @ordered_hash.keys, @deserialized_ordered_hash.keys
assert_equal @ordered_hash.values, @deserialized_ordered_hash.values
end
+ begin
+ require 'psych'
+
+ def test_psych_serialize
+ @deserialized_ordered_hash = Psych.load(Psych.dump(@ordered_hash))
+
+ values = @deserialized_ordered_hash.map { |_, value| value }
+ assert_equal @values, values
+ end
+
+ def test_psych_serialize_tag
+ yaml = Psych.dump(@ordered_hash)
+ assert_match '!omap', yaml
+ end
+ rescue LoadError
+ end
+
+ def test_has_yaml_tag
+ @ordered_hash[:array] = %w(a b c)
+ assert_match '!omap', YAML.dump(@ordered_hash)
+ end
+
def test_update_sets_keys
@updated_ordered_hash = ActiveSupport::OrderedHash.new
@updated_ordered_hash.update(:name => "Bob")
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
index bf61f9e58c..a4e2acbb32 100644
--- a/activesupport/test/safe_buffer_test.rb
+++ b/activesupport/test/safe_buffer_test.rb
@@ -1,4 +1,10 @@
require 'abstract_unit'
+begin
+ require 'psych'
+rescue LoadError
+end
+
+require 'yaml'
class SafeBufferTest < ActiveSupport::TestCase
def setup
@@ -38,4 +44,20 @@ class SafeBufferTest < ActiveSupport::TestCase
new_buffer = @buffer.to_s
assert_equal ActiveSupport::SafeBuffer, new_buffer.class
end
+
+ def test_to_yaml
+ str = 'hello!'
+ buf = ActiveSupport::SafeBuffer.new str
+ yaml = buf.to_yaml
+
+ assert_match(/^--- #{str}/, yaml)
+ assert_equal 'hello!', YAML.load(yaml)
+ end
+
+ def test_nested
+ str = 'hello!'
+ data = { 'str' => ActiveSupport::SafeBuffer.new(str) }
+ yaml = YAML.dump data
+ assert_equal({'str' => str}, YAML.load(yaml))
+ end
end
diff --git a/activesupport/test/test_case_test.rb b/activesupport/test/test_case_test.rb
index 7e65c63062..756d21b3e4 100644
--- a/activesupport/test/test_case_test.rb
+++ b/activesupport/test/test_case_test.rb
@@ -12,6 +12,10 @@ module ActiveSupport
def puke(klass, name, e)
@puked << [klass, name, e]
end
+
+ def options
+ nil
+ end
end
if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
diff --git a/activesupport/test/test_xml_mini.rb b/activesupport/test/test_xml_mini.rb
index 309fa234bf..6dbcd1f40b 100644
--- a/activesupport/test/test_xml_mini.rb
+++ b/activesupport/test/test_xml_mini.rb
@@ -1,61 +1,100 @@
require 'abstract_unit'
require 'active_support/xml_mini'
+require 'active_support/builder'
-class XmlMiniTest < Test::Unit::TestCase
- def test_rename_key_dasherizes_by_default
- assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key")
- end
+module XmlMiniTest
+ class RenameKeyTest < Test::Unit::TestCase
+ def test_rename_key_dasherizes_by_default
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key")
+ end
- def test_rename_key_does_nothing_with_dasherize_true
- assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true)
- end
+ def test_rename_key_does_nothing_with_dasherize_true
+ assert_equal "my-key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => true)
+ end
- def test_rename_key_does_nothing_with_dasherize_false
- assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false)
- end
+ def test_rename_key_does_nothing_with_dasherize_false
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :dasherize => false)
+ end
- def test_rename_key_camelizes_with_camelize_false
- assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => false)
- end
+ def test_rename_key_camelizes_with_camelize_false
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => false)
+ end
- def test_rename_key_camelizes_with_camelize_nil
- assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => nil)
- end
+ def test_rename_key_camelizes_with_camelize_nil
+ assert_equal "my_key", ActiveSupport::XmlMini.rename_key("my_key", :camelize => nil)
+ end
- def test_rename_key_camelizes_with_camelize_true
- assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true)
- end
+ def test_rename_key_camelizes_with_camelize_true
+ assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => true)
+ end
- def test_rename_key_lower_camelizes_with_camelize_lower
- assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :lower)
- end
+ def test_rename_key_lower_camelizes_with_camelize_lower
+ assert_equal "myKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :lower)
+ end
- def test_rename_key_lower_camelizes_with_camelize_upper
- assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :upper)
- end
+ def test_rename_key_lower_camelizes_with_camelize_upper
+ assert_equal "MyKey", ActiveSupport::XmlMini.rename_key("my_key", :camelize => :upper)
+ end
- def test_rename_key_does_not_dasherize_leading_underscores
- assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id")
- end
+ def test_rename_key_does_not_dasherize_leading_underscores
+ assert_equal "_id", ActiveSupport::XmlMini.rename_key("_id")
+ end
- def test_rename_key_with_leading_underscore_dasherizes_interior_underscores
- assert_equal "_my-key", ActiveSupport::XmlMini.rename_key("_my_key")
- end
+ def test_rename_key_with_leading_underscore_dasherizes_interior_underscores
+ assert_equal "_my-key", ActiveSupport::XmlMini.rename_key("_my_key")
+ end
- def test_rename_key_does_not_dasherize_trailing_underscores
- assert_equal "id_", ActiveSupport::XmlMini.rename_key("id_")
- end
+ def test_rename_key_does_not_dasherize_trailing_underscores
+ assert_equal "id_", ActiveSupport::XmlMini.rename_key("id_")
+ end
- def test_rename_key_with_trailing_underscore_dasherizes_interior_underscores
- assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_")
- end
+ def test_rename_key_with_trailing_underscore_dasherizes_interior_underscores
+ assert_equal "my-key_", ActiveSupport::XmlMini.rename_key("my_key_")
+ end
- def test_rename_key_does_not_dasherize_multiple_leading_underscores
- assert_equal "__id", ActiveSupport::XmlMini.rename_key("__id")
- end
+ def test_rename_key_does_not_dasherize_multiple_leading_underscores
+ assert_equal "__id", ActiveSupport::XmlMini.rename_key("__id")
+ end
- def test_rename_key_does_not_dasherize_multiple_leading_underscores
- assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__")
+ def test_rename_key_does_not_dasherize_multiple_leading_underscores
+ assert_equal "id__", ActiveSupport::XmlMini.rename_key("id__")
+ end
end
+ class ToTagTest < ActiveSupport::TestCase
+ def assert_xml(xml)
+ assert_equal xml, @options[:builder].target!
+ end
+
+ setup do
+ @xml = ActiveSupport::XmlMini
+ @options = {:skip_instruct => true, :builder => Builder::XmlMarkup.new}
+ end
+
+ test "#to_tag accepts a callable object and passes options with the builder" do
+ @xml.to_tag(:some_tag, lambda {|o| o[:builder].br }, @options)
+ assert_xml "<br/>"
+ end
+
+ test "#to_tag accepts a callable object and passes options and tag name" do
+ @xml.to_tag(:tag, lambda {|o, t| o[:builder].b(t) }, @options)
+ assert_xml "<b>tag</b>"
+ end
+
+ test "#to_tag accepts an object responding to #to_xml and passes the options, where :root is key" do
+ obj = Object.new
+ obj.instance_eval do
+ def to_xml(options) options[:builder].yo(options[:root].to_s) end
+ end
+
+ @xml.to_tag(:tag, obj, @options)
+ assert_xml "<yo>tag</yo>"
+ end
+
+ test "#to_tag accepts arbitrary objects responding to #to_str" do
+ @xml.to_tag(:b, "Howdy", @options)
+ assert_xml "<b>Howdy</b>"
+ end
+ # TODO: test the remaining functions hidden in #to_tag.
+ end
end
diff --git a/ci/ci_build.rb b/ci/ci_build.rb
index fd884b3b2e..964e2d4eb8 100755
--- a/ci/ci_build.rb
+++ b/ci/ci_build.rb
@@ -35,7 +35,7 @@ cd "#{root_dir}/activesupport" do
puts "[CruiseControl] Building Active Support"
puts
build_results[:activesupport] = rake 'test'
- # build_results[:activesupport_isolated] = rake 'test:isolated'
+ build_results[:activesupport_isolated] = rake 'test:isolated'
end
system "sudo rm -R #{root_dir}/railties/tmp"
@@ -51,7 +51,7 @@ cd "#{root_dir}/actionpack" do
puts "[CruiseControl] Building Action Pack"
puts
build_results[:actionpack] = rake 'test'
- # build_results[:actionpack_isolated] = rake 'test:isolated'
+ build_results[:actionpack_isolated] = rake 'test:isolated'
end
cd "#{root_dir}/actionmailer" do
@@ -59,7 +59,7 @@ cd "#{root_dir}/actionmailer" do
puts "[CruiseControl] Building Action Mailer"
puts
build_results[:actionmailer] = rake 'test'
- # build_results[:actionmailer_isolated] = rake 'test:isolated'
+ build_results[:actionmailer_isolated] = rake 'test:isolated'
end
cd "#{root_dir}/activemodel" do
@@ -67,7 +67,7 @@ cd "#{root_dir}/activemodel" do
puts "[CruiseControl] Building Active Model"
puts
build_results[:activemodel] = rake 'test'
- # build_results[:activemodel_isolated] = rake 'test:isolated'
+ build_results[:activemodel_isolated] = rake 'test:isolated'
end
rm_f "#{root_dir}/activeresource/debug.log"
@@ -76,7 +76,7 @@ cd "#{root_dir}/activeresource" do
puts "[CruiseControl] Building Active Resource"
puts
build_results[:activeresource] = rake 'test'
- # build_results[:activeresource_isolated] = rake 'test:isolated'
+ build_results[:activeresource_isolated] = rake 'test:isolated'
end
rm_f "#{root_dir}/activerecord/debug.log"
@@ -85,7 +85,7 @@ cd "#{root_dir}/activerecord" do
puts "[CruiseControl] Building Active Record with MySQL"
puts
build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'mysql:test'
- # build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test'
+ build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test'
end
cd "#{root_dir}/activerecord" do
@@ -93,7 +93,7 @@ cd "#{root_dir}/activerecord" do
puts "[CruiseControl] Building Active Record with MySQL2"
puts
build_results[:activerecord_mysql2] = rake 'mysql:rebuild_databases', 'mysql2:test'
- # build_results[:activerecord_mysql2_isolated] = rake 'mysql:rebuild_databases', 'mysql2:isolated_test'
+ build_results[:activerecord_mysql2_isolated] = rake 'mysql:rebuild_databases', 'mysql2:isolated_test'
end
cd "#{root_dir}/activerecord" do
@@ -101,7 +101,7 @@ cd "#{root_dir}/activerecord" do
puts "[CruiseControl] Building Active Record with PostgreSQL"
puts
build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'postgresql:test'
- # build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test'
+ build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test'
end
cd "#{root_dir}/activerecord" do
@@ -109,7 +109,7 @@ cd "#{root_dir}/activerecord" do
puts "[CruiseControl] Building Active Record with SQLite 3"
puts
build_results[:activerecord_sqlite3] = rake 'sqlite3:test'
- # build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test'
+ build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test'
end
diff --git a/load_paths.rb b/load_paths.rb
index 873315f978..8f37364629 100644
--- a/load_paths.rb
+++ b/load_paths.rb
@@ -4,7 +4,7 @@ rescue LoadError
begin
# bust gem prelude
if defined? Gem
- Gem.cache
+ Gem.source_index
gem 'bundler'
else
require 'rubygems'
diff --git a/railties/MIT-LICENSE b/railties/MIT-LICENSE
index 86bcb23b7c..c73d1af096 100644
--- a/railties/MIT-LICENSE
+++ b/railties/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2010 David Heinemeier Hansson
+Copyright (c) 2004-2011 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/railties/Rakefile b/railties/Rakefile
index 5137bee761..26fa0bf6a5 100755
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -18,7 +18,7 @@ namespace :test do
Dir["test/#{dir}/*_test.rb"].each do |file|
next true if file.include?("fixtures")
ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
- system(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
+ sh(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
end
end
end
@@ -46,8 +46,8 @@ task :generate_guides do
end
task :update_ujs do
- system "curl http://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js"
- system "curl http://github.com/rails/jquery-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js"
+ system "curl https://github.com/rails/prototype-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js"
+ system "curl https://github.com/rails/jquery-ujs/raw/master/src/rails.js > lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js"
end
# Validate guides -------------------------------------------------------------------------
diff --git a/railties/guides/assets/stylesheets/fixes.css b/railties/guides/assets/stylesheets/fixes.css
new file mode 100644
index 0000000000..54efa5b9b7
--- /dev/null
+++ b/railties/guides/assets/stylesheets/fixes.css
@@ -0,0 +1,16 @@
+/*
+ Fix a rendering issue affecting WebKits on Mac.
+ See https://github.com/lifo/docrails/issues#issue/16 for more information.
+*/
+.syntaxhighlighter a,
+.syntaxhighlighter div,
+.syntaxhighlighter code,
+.syntaxhighlighter table,
+.syntaxhighlighter table td,
+.syntaxhighlighter table tr,
+.syntaxhighlighter table tbody,
+.syntaxhighlighter table thead,
+.syntaxhighlighter table caption,
+.syntaxhighlighter textarea {
+ line-height: 1.2em !important;
+}
diff --git a/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb
index dfbb06cc76..feb5fe3937 100644
--- a/railties/guides/rails_guides.rb
+++ b/railties/guides/rails_guides.rb
@@ -24,14 +24,14 @@ rescue LoadError
end
begin
- gem 'RedCloth', '>= 4.1.1'
require 'redcloth'
rescue Gem::LoadError
+ # This can happen if doc:guides is executed in an application.
$stderr.puts('Generating guides requires RedCloth 4.1.1+.')
$stderr.puts(<<ERROR) if bundler?
Please add
- gem 'RedCloth', '>= 4.1.1'
+ gem 'RedCloth', '~> 4.2'
to the Gemfile, run
diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb
index 0a2170a09e..154355cac1 100644
--- a/railties/guides/rails_guides/generator.rb
+++ b/railties/guides/rails_guides/generator.rb
@@ -32,12 +32,16 @@
#
# Separate many using commas:
#
-# # generates only
+# # generates only association_basics.html and migrations.html
# ONLY=assoc,migrations ruby rails_guides.rb
#
# Note that if you are working on a guide generation will by default process
# only that one, so ONLY is rarely used nowadays.
#
+# LANGUAGE
+# Use LANGUAGE when you want to generate translated guides in <tt>source/<LANGUAGE></tt>
+# folder (such as <tt>source/es</tt>). Ignore it when generating English guides.
+#
# EDGE
# Set to "1" to indicate generated guides should be marked as edge. This
# inserts a badge and changes the preamble of the home page.
@@ -63,6 +67,7 @@ module RailsGuides
GUIDES_RE = /\.(?:textile|html\.erb)$/
def initialize(output=nil)
+ @lang = ENV['LANGUAGE']
initialize_dirs(output)
create_output_dir_if_needed
set_flags_from_environment
@@ -76,8 +81,8 @@ module RailsGuides
private
def initialize_dirs(output)
@guides_dir = File.join(File.dirname(__FILE__), '..')
- @source_dir = File.join(@guides_dir, "source")
- @output_dir = output || File.join(@guides_dir, "output")
+ @source_dir = File.join(@guides_dir, "source", @lang.to_s)
+ @output_dir = output || File.join(@guides_dir, "output", @lang.to_s)
end
def create_output_dir_if_needed
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile
index 5628d7e52f..8e2d528eee 100644
--- a/railties/guides/source/2_2_release_notes.textile
+++ b/railties/guides/source/2_2_release_notes.textile
@@ -260,15 +260,15 @@ h4. Other Action Controller Changes
* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
-* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
+* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type.
* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
h3. Action View
* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code.
-* The included Prototype javascript library has been upgraded to version 1.6.0.3.
-* +RJS#page.reload+ to reload the browser's current location via javascript
+* The included Prototype JavaScript library has been upgraded to version 1.6.0.3.
+* +RJS#page.reload+ to reload the browser's current location via JavaScript
* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions.
h3. Action Mailer
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile
index 72fe723687..67743a4797 100644
--- a/railties/guides/source/2_3_release_notes.textile
+++ b/railties/guides/source/2_3_release_notes.textile
@@ -278,7 +278,7 @@ Mime::JS =~ "text/javascript" => true
Mime::JS =~ "application/javascript" => true
</ruby>
-The other change is that the framework now uses the +Mime::JS+ when checking for javascript in various spots, making it handle those alternatives cleanly.
+The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly.
* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons
diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile
index adb1c755df..001f458fd9 100644
--- a/railties/guides/source/3_0_release_notes.textile
+++ b/railties/guides/source/3_0_release_notes.textile
@@ -22,7 +22,7 @@ To install Rails 3:
<shell>
# Use sudo if your setup requires it
-gem install rails
+$ gem install rails
</shell>
@@ -47,8 +47,8 @@ h4. script/* replaced by script/rails
The new <tt>script/rails</tt> replaces all the scripts that used to be in the <tt>script</tt> directory. You do not run <tt>script/rails</tt> directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is:
<shell>
-rails console # instead of script/console
-rails g scaffold post title:string # instead of script/generate scaffold post title:string
+$ rails console # instead of script/console
+$ rails g scaffold post title:string # instead of script/generate scaffold post title:string
</shell>
Run <tt>rails --help</tt> for a list of all the options.
@@ -64,7 +64,7 @@ To help with the upgrade process, a plugin named "Rails Upgrade":http://github.c
Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following:
<shell>
-ruby script/plugin install git://github.com/rails/rails_upgrade.git
+$ ruby script/plugin install git://github.com/rails/rails_upgrade.git
</shell>
You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin
@@ -357,15 +357,15 @@ Validations have been moved from Active Record into Active Model, providing an i
* There is now a <tt>validates :attribute, options_hash</tt> shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method.
* The +validates+ method has the following options:
- * <tt>:acceptance => Boolean</tt>.
- * <tt>:confirmation => Boolean</tt>.
- * <tt>:exclusion => { :in => Enumerable }</tt>.
- * <tt>:inclusion => { :in => Enumerable }</tt>.
- * <tt>:format => { :with => Regexp, :on => :create }</tt>.
- * <tt>:length => { :maximum => Fixnum }</tt>.
- * <tt>:numericality => Boolean</tt>.
- * <tt>:presence => Boolean</tt>.
- * <tt>:uniqueness => Boolean</tt>.
+** <tt>:acceptance => Boolean</tt>.
+** <tt>:confirmation => Boolean</tt>.
+** <tt>:exclusion => { :in => Enumerable }</tt>.
+** <tt>:inclusion => { :in => Enumerable }</tt>.
+** <tt>:format => { :with => Regexp, :on => :create }</tt>.
+** <tt>:length => { :maximum => Fixnum }</tt>.
+** <tt>:numericality => Boolean</tt>.
+** <tt>:presence => Boolean</tt>.
+** <tt>:uniqueness => Boolean</tt>.
NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API.
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 0d6919a205..be015c4f9b 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -368,6 +368,7 @@ class UsersController < ApplicationController
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users}
+ format.json { render :json => @users}
end
end
end
@@ -736,16 +737,12 @@ GET /clients/1.pdf
h3. Parameter Filtering
-Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The +filter_parameter_logging+ method can be used to filter out sensitive information from the log. It works by replacing certain values in the +params+ hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
<ruby>
-class ApplicationController < ActionController::Base
- filter_parameter_logging :password
-end
+config.filter_parameters << :password
</ruby>
-The method works recursively through all levels of the +params+ hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
-
h3. Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception.
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index b75c528a33..56da360972 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -19,7 +19,7 @@ h4. Walkthrough to Generating a Mailer
h5. Create the Mailer
<shell>
-rails generate mailer UserMailer
+$ rails generate mailer UserMailer
create app/mailers/user_mailer.rb
invoke erb
create app/views/user_mailer
@@ -144,7 +144,7 @@ This provides a much simpler implementation that does not require the registerin
The method +welcome_email+ returns a Mail::Message object which can then just be told +deliver+ to send itself out.
-NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+ however in Rails 3.0 this has been deprecated in favour of just calling the method name itself.
+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 one 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.
@@ -154,7 +154,7 @@ 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 ActionMailer 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
@@ -213,9 +213,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already
h5. Making Inline Attachments
-Inline attachments are now possible in ActionMailer. While previously in the pre 3.0 version of Rails, you could do inline attachments, it involved a lot of hacking and determination to pull it off.
-
-ActionMailer now makes inline attachments as trivial as they should be.
+ActionMailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer:
@@ -250,7 +248,7 @@ It is possible to send email to one or more recipients in one email (for e.g. in
class AdminMailer < ActionMailer::Base
default :to => Admin.all.map(&:email).join(", "),
:from => "notification@example.com"
-
+
def new_registration(user)
@user = user
mail(:subject => "New User Signup: #{@user.email}")
@@ -274,7 +272,7 @@ to format the email address in the format <tt>"Name &lt;email&gt;"</tt>.
h4. Mailer Views
-Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because it's name is the same as the mailer method. So for example, in our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
+Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
To change the default mailer view for your action you do something like:
@@ -441,7 +439,7 @@ h3. Action Mailer Configuration
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
|template_root|Determines the base from which template references will be made.|
-|logger|The logger is used for generating 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.|
+|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 :smtp delivery method:<ul><li>:address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>:port - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>:domain - If you need to specify a HELO domain, you can do it here.</li><li>:user_name - If your mail server requires authentication, set the username in this setting.</li><li>:password - If your mail server requires authentication, set the password in this setting.</li><li>:authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.</li></ul>|
|sendmail_settings|Allows you to override options for the :sendmail delivery method.<ul><li>:location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.</li><li>:arguments - The command line arguments to be passed to sendmail. Defaults to -i -t.</li></ul>|
|raise_delivery_errors|Whether or not errors should be raised if the email fails to be delivered.|
@@ -504,7 +502,7 @@ class UserMailerTest < ActionMailer::TestCase
end
</ruby>
-In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain the what we expect.
+In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect.
h3. Changelog
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
index 051baa660c..bf592c06ed 100644
--- a/railties/guides/source/action_view_overview.textile
+++ b/railties/guides/source/action_view_overview.textile
@@ -29,8 +29,8 @@ Action View works well with Action Record, but it can also be used with other Ru
Let's start by ensuring that you have the Action Pack and Rack gems installed:
<shell>
-gem install actionpack
-gem install rack
+$ gem install actionpack
+$ gem install rack
</shell>
Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support.
@@ -52,7 +52,7 @@ Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567
We can see this all come together by starting up the application and then visiting +http://localhost:4567/+
<shell>
-ruby hello_world.rb
+$ ruby hello_world.rb
</shell>
TODO needs a screenshot? I have one - not sure where to put it.
@@ -64,8 +64,8 @@ Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the sam
Let's start by ensuring that you have the Action Pack and Sinatra gems installed:
<shell>
-gem install actionpack
-gem install sinatra
+$ gem install actionpack
+$ gem install sinatra
</shell>
Now we'll create the same "Hello World" application in Sinatra.
@@ -85,7 +85,7 @@ end
Then, we can run the application:
<shell>
-ruby hello_world.rb
+$ ruby hello_world.rb
</shell>
Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+
@@ -231,7 +231,7 @@ input("post", "title") # =>
h4. AssetTagHelper
-This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds.
+This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+:
@@ -242,7 +242,7 @@ image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png
h5. register_javascript_expansion
-Register one or more javascript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register javascript files that the plugin installed in public/javascripts.
+Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in +public/javascripts+.
<ruby>
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
@@ -278,7 +278,7 @@ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS
h5. image_path
-Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
+Computes the path to an image asset in the +public/images+ directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
<ruby>
image_path("edit.png") # => /images/edit.png
@@ -286,7 +286,7 @@ image_path("edit.png") # => /images/edit.png
h5. image_tag
-Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory.
+Returns an html image tag for the source. The source can be a full path or a file that exists in your +public/images+ directory.
<ruby>
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
@@ -294,26 +294,26 @@ image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
h5. javascript_include_tag
-Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
+Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of JavaScript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
<ruby>
javascript_include_tag "common" # =>
<script type="text/javascript" src="/javascripts/common.js"></script>
</ruby>
-To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
+To include the Prototype and Scriptaculous JavaScript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
<ruby>
javascript_include_tag :defaults
</ruby>
-You can also include all javascripts in the javascripts directory using +:all+ as the source.
+You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source.
<ruby>
javascript_include_tag :all
</ruby>
-You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
+You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
<ruby>
javascript_include_tag :all, :cache => true # =>
@@ -322,7 +322,7 @@ javascript_include_tag :all, :cache => true # =>
h5. javascript_path
-Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
+Computes the path to a JavaScript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
<ruby>
javascript_path "common" # => /javascripts/common.js
@@ -352,7 +352,7 @@ stylesheet_link_tag :all, :cache => true
h5. stylesheet_path
-Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
+Computes the path to a stylesheet asset in the +public/stylesheets+ directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
<ruby>
stylesheet_path "application" # => /stylesheets/application.css
@@ -367,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example:
*config/routes.rb*
<ruby>
-map.resources :posts
+resources :posts
</ruby>
*app/controllers/posts_controller.rb*
<ruby>
def index
- @posts = Post.find(:all)
+ @posts = Post.all
respond_to do |format|
format.html
@@ -439,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
-<ruby>
+</ruby>
The captured variable can then be used anywhere else.
@@ -809,7 +809,7 @@ end
Sample usage (selecting the associated Author for an instance of Post, +@post+):
<ruby>
-collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
+collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
</ruby>
If @post.author_id is already 1, this would return:
@@ -888,7 +888,7 @@ Note: Only the +option+ tags are returned, you have to wrap this call in a regul
h5. options_from_collection_for_select
-Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
+Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
<ruby>
# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
@@ -910,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec
Example with @post.person_id => 1:
<ruby>
-select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
+select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
</ruby>
could become:
@@ -1076,7 +1076,7 @@ h4. JavaScriptHelper
Provides functionality for working with JavaScript in your views.
-Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory.
+Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the +public/javascripts+ directory.
h5. button_to_function
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
index f0081b48c0..b7926f3a3b 100644
--- a/railties/guides/source/active_record_basics.textile
+++ b/railties/guides/source/active_record_basics.textile
@@ -180,7 +180,7 @@ Active Record provides a rich API for accessing data within a database. Below ar
<ruby>
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
- users = User.all(:conditions => { :name => 'David', :occupation => 'Code Artist'}, :order => 'created_at DESC')
+ users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
</ruby>
You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index b9ad7ccbd2..64a68f7592 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -19,8 +19,6 @@ Code examples throughout this guide will refer to one or more of the following m
TIP: All of the following models use +id+ as the primary key, unless specified otherwise.
-<br />
-
<ruby>
class Client < ActiveRecord::Base
has_one :address
@@ -150,7 +148,7 @@ SQL equivalent of the above is:
SELECT * FROM clients WHERE (clients.id IN (1,10))
</sql>
-<tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
+WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
h4. Retrieving Multiple Objects in Batches
@@ -337,7 +335,7 @@ This code will generate SQL like this:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
</sql>
-h4. Ordering
+h3. Ordering
To retrieve records from the database in a specific order, you can use the +order+ method.
@@ -361,7 +359,7 @@ Or ordering by multiple fields:
Client.order("orders_count ASC, created_at DESC")
</ruby>
-h4. Selecting Specific Fields
+h3. Selecting Specific Fields
By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
@@ -397,7 +395,7 @@ You can also call SQL functions within the select option. For example, if you wo
Client.select("DISTINCT(name)")
</ruby>
-h4. Limit and Offset
+h3. Limit and Offset
To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation.
@@ -425,7 +423,7 @@ will return instead a maximum of 5 clients beginning with the 31st. The SQL look
SELECT * FROM clients LIMIT 5, 30
</sql>
-h4. Group
+h3. Group
To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find.
@@ -440,10 +438,10 @@ And this will give you a single +Order+ object for each date where there are ord
The SQL that would be executed would be something like this:
<sql>
-SELECT * FROM orders GROUP BY date(created_at)
+SELECT * FROM orders GROUP BY date(created_at) ORDER BY created_at
</sql>
-h4. Having
+h3. Having
SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find.
@@ -461,7 +459,37 @@ SELECT * FROM orders GROUP BY date(created_at) HAVING created_at > '2009-01-15'
This will return single order objects for each day, but only for the last month.
-h4. Readonly Objects
+h3. Overriding Conditions
+
+You can specify certain conditions to be excepted by using the +except+ method.
+
+For example:
+
+<ruby>
+Post.where('id > 10').limit(20).order('id asc').except(:order)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 LIMIT 20
+</sql>
+
+You can also override conditions using the +only+ method.
+
+For example:
+
+<ruby>
+Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
+</ruby>
+
+The SQL that would be executed:
+
+<sql>
+SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
+</sql>
+
+h3. Readonly Objects
Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception.
@@ -471,9 +499,9 @@ client.visits += 1
client.save
</ruby>
-As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visists_.
+As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visits_.
-h4. Locking Records for Update
+h3. Locking Records for Update
Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
@@ -482,7 +510,7 @@ Active Record provides two locking mechanisms:
* Optimistic Locking
* Pessimistic Locking
-h5. Optimistic Locking
+h4. Optimistic Locking
Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored.
@@ -517,7 +545,7 @@ class Client < ActiveRecord::Base
end
</ruby>
-h5. Pessimistic Locking
+h4. Pessimistic Locking
Pessimistic locking uses a locking mechanism provided by the underlying database. Using +lock+ when building a relation obtains an exclusive lock on the selected rows. Relations using +lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
@@ -569,9 +597,7 @@ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id =
h4. Using Array/Hash of Named Associations
-WARNING: This method only works with +INNER JOIN+,
-
-<br />
+WARNING: This method only works with +INNER JOIN+.
Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method.
@@ -666,7 +692,7 @@ Eager loading is the mechanism for loading the associated records of the objects
Consider the following code, which finds 10 clients and prints their postcodes:
<ruby>
-clients = Client.all(:limit => 10)
+clients = Client.limit(10)
clients.each do |client|
puts client.address.postcode
@@ -721,6 +747,92 @@ h4. Specifying Conditions on Eager Loaded Associations
Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead.
+h3. Scopes
+
+Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
+
+To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true)
+end
+</ruby>
+
+Just like before, these methods are also chainable:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true).joins(:category)
+end
+</ruby>
+
+Scopes are also chainable within scopes:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :published, where(:published => true)
+ scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
+end
+</ruby>
+
+To call this +published+ scope we can call it on either the class:
+
+<ruby>
+Post.published => [published posts]
+</ruby>
+
+Or on an association consisting of +Post+ objects:
+
+<ruby>
+category = Category.first
+category.posts.published => [published posts belonging to this category]
+</ruby>
+
+h4. Working with times
+
+If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
+end
+</ruby>
+
+Without the +lambda+, this +Time.zone.now+ will only be called once.
+
+h4. Passing in arguments
+
+When a +lambda+ is used for a +scope+, it can take arguments:
+
+<ruby>
+class Post < ActiveRecord::Base
+ scope :1_week_before, lambda { |time| where("created_at < ?", time)
+end
+</ruby>
+
+This may then be called using this:
+
+<ruby>
+Post.1_week_before(Time.zone.now)
+</ruby>
+
+However, this is just duplicating the functionality that would be provided to you by a class method.
+
+<ruby>
+class Post < ActiveRecord::Base
+ def self.1_week_before(time)
+ where("created_at < ?", time)
+ end
+end
+</ruby>
+
+Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
+
+<ruby>
+category.posts.1_week_before(time)
+</ruby>
+
h3. Dynamic Finders
For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods.
@@ -882,6 +994,7 @@ For options, please see the parent section, "Calculations":#calculations.
h3. Changelog
+* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":http://ryanbigg.com
* April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* February 3, 2010: Update to Rails 3 by "James Miller":credits.html#bensie
* February 7, 2009: Second version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile
index 0824ba450c..5dc6ef3774 100644
--- a/railties/guides/source/active_record_validations_callbacks.textile
+++ b/railties/guides/source/active_record_validations_callbacks.textile
@@ -314,6 +314,8 @@ class Essay < ActiveRecord::Base
end
</ruby>
+Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when +:minimum+ is 1 you should provide a personalized message or use +validates_presence_of+ instead. When +:in+ or +:within+ have a lower limit of 1, you should either provide a personalized message or call +validates_presence_of+ prior to +validates_length_of+.
+
The +validates_size_of+ helper is an alias for +validates_length_of+.
h4. +validates_numericality_of+
@@ -414,8 +416,8 @@ class Person < ActiveRecord::Base
validates_with GoodnessValidator
end
-class GoodnessValidator < ActiveRecord::Validator
- def validate
+class GoodnessValidator < ActiveModel::Validator
+ def validate(record)
if record.first_name == "Evil"
record.errors[:base] << "This person is evil"
end
@@ -425,10 +427,7 @@ end
The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class.
-The validator class has two attributes by default:
-
-* +record+ - the record to be validated
-* +options+ - the extra options that were passed to +validates_with+
+To implement the validate method, you must have an +record+ parameter defined, which is the record to be validated.
Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+:
@@ -437,8 +436,8 @@ class Person < ActiveRecord::Base
validates_with GoodnessValidator, :fields => [:first_name, :last_name]
end
-class GoodnessValidator < ActiveRecord::Validator
- def validate
+class GoodnessValidator < ActiveModel::Validator
+ def validate(record)
if options[:fields].any?{|field| record.send(field) == "Evil" }
record.errors[:base] << "This person is evil"
end
@@ -1113,7 +1112,7 @@ h4. Creating Observers
For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we could create an observer to contain this functionality.
<shell>
-rails generate observer User
+$ rails generate observer User
</shell>
<ruby>
@@ -1158,8 +1157,43 @@ In this example, the +after_create+ method would be called whenever a +Registrat
config.active_record.observers = :mailer_observer
</ruby>
+h3. Transaction Callbacks
+
+There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.
+
+Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after a record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error.
+
+<ruby>
+PictureFile.transaction do
+ picture_file_1.destroy
+ picture_file_2.save!
+end
+</ruby>
+
+By using the +after_commit+ callback we can account for this case.
+
+<ruby>
+class PictureFile < ActiveRecord::Base
+ attr_accessor :delete_file
+
+ after_destroy do |picture_file|
+ picture_file.delete_file = picture_file.filepath
+ end
+
+ after_commit do |picture_file|
+ if picture_file.delete_file && File.exist?(picture_file.delete_file)
+ File.delete(picture_file.delete_file)
+ picture_file.delete_file = nil
+ end
+ end
+end
+</ruby>
+
+The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
+
h3. Changelog
+* February 17, 2011: Add description of transaction callbacks.
* July 20, 2010: Fixed typos and rephrased some paragraphs for clarity. "Jaime Iniesta":http://jaimeiniesta.com
* May 24, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* May 15, 2010: Validation Errors section updated by "Emili Parreño":http://www.eparreno.com
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 7333a81cf9..e0b1bf6e83 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -20,7 +20,7 @@ Thus, after a simple require like:
require 'active_support'
</ruby>
-objects do not even respond to +blank?+, let's see how to load its definition.
+objects do not even respond to +blank?+. Let's see how to load its definition.
h5. Cherry-picking a Definition
@@ -42,7 +42,7 @@ h5. Loading Grouped Core Extensions
The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+.
-Thus, if that would do, to have +blank?+ available we could just load all extensions to +Object+:
+Thus, to load all extensions to +Object+ (including +blank?+):
<ruby>
require 'active_support/core_ext/object'
@@ -432,7 +432,7 @@ h4. +require_library_or_gem+
The convenience method +require_library_or_gem+ tries to load its argument with a regular +require+ first. If it fails loads +rubygems+ and tries again.
-If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. On the other hand, if +rubygems+ is available but the argument is not loadable as a gem, the method gives up and +LoadError+ is also raised.
+If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. A +LoadError+ is also raised if +rubygems+ is available but the argument is not loadable as a gem.
For example, that's the way the MySQL adapter loads the MySQL library:
@@ -498,12 +498,12 @@ h4. Attributes
h5. +alias_attribute+
-Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
+Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
<ruby>
class User < ActiveRecord::Base
# let me refer to the email column as "login",
- # much meaningful for authentication code
+ # possibly meaningful for authentication code
alias_attribute :login, :email
end
</ruby>
@@ -528,7 +528,7 @@ The default value can be also specified with a block, which is called in the con
class User
attr_accessor :name, :surname
attr_accessor_with_default(:full_name) {
- [name, surname].compact.join(" ")
+ [name, surname].compact.join(" ")
}
end
@@ -563,7 +563,7 @@ h5. Internal Attributes
When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
-Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
+Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
@@ -991,7 +991,7 @@ a2.x # => 2, overridden in a2
The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in
<ruby>
-module AcitveRecord
+module ActiveRecord
class Base
class_attribute :table_name_prefix, :instance_writer => false
self.table_name_prefix = ""
@@ -1001,7 +1001,7 @@ end
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
-For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
+For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
NOTE: Defined in +active_support/core_ext/class/attribute.rb+
@@ -1264,7 +1264,7 @@ Active Support adds that functionality to <tt>%</tt> in previous versions of Rub
NOTE: Defined in +active_support/core_ext/string/interpolation.rb+.
-h4. +starts_with?+ and +ends_width?+
+h4. +starts_with?+ and +ends_with?+
Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
@@ -1568,7 +1568,7 @@ The method +tableize+ is +underscore+ followed by +pluralize+.
"InvoiceLine".tableize # => "invoice_lines"
</ruby>
-As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes de class name and checks a few options that may affect the returned string.
+As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
@@ -1868,7 +1868,7 @@ The sum of an empty collection is zero by default, but this is customizable:
[].sum(1) # => 1
</ruby>
-If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
+If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
<ruby>
(1..5).sum {|n| n * 2 } # => 30
@@ -1896,7 +1896,7 @@ h4. +each_with_object+
The +inject+ method offers iteration with an accumulator:
<ruby>
-[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
+[2, 3, 4].inject(1) {|product, i| product*i } # => 24
</ruby>
The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:
@@ -1942,7 +1942,7 @@ The method +many?+ is shorthand for +collection.size > 1+:
<% end %>
</erb>
-If an optional block is given +many?+ only takes into account those elements that return true:
+If an optional block is given, +many?+ only takes into account those elements that return true:
<ruby>
@see_more = videos.many? {|video| video.category == params[:category]}
@@ -1952,7 +1952,7 @@ NOTE: Defined in +active_support/core_ext/enumerable.rb+.
h4. +exclude?+
-The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+:
+The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+:
<ruby>
to_visit << node if visited.exclude?(node)
@@ -2007,7 +2007,7 @@ User.exists?(:email => params[:email])
That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
-If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role.
+If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash.
@@ -2190,7 +2190,7 @@ Array.wrap(0) # => [0]
This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Arraw.wrap</tt> returns such a +nil+ right away.
+* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns +nil+ right away.
* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
* It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
@@ -2713,6 +2713,14 @@ WARNING: The original +Range#include?+ is still the one aliased to +Range#===+.
NOTE: Defined in +active_support/core_ext/range/include_range.rb+.
+h4. +cover?+
+
+Ruby 1.9 provides +cover?+, and Active Support defines it for previous versions as an alias for +include?+.
+
+The method +include?+ in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range's endpoints, it walks the range with +succ+ looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases.
+
+In Ruby 1.9 the old behavior is still available in the new +cover?+, which Active Support backports for forward compatibility. For example, Rails uses +cover?+ for ranges in +validates_inclusion_of+.
+
h4. +overlaps?+
The method +Range#overlaps?+ says whether any two given ranges have non-void intersection:
@@ -2783,6 +2791,8 @@ h5. +Date.current+
Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+.
+When making Date comparisons using methods which honor the user time zone, make sure to use +Date.current+ and not +Date.today+. There are cases where the user time zone might be in the future compared to the system time zone, which +Date.today+ uses by default. This means +Date.today+ may equal +Date.yesterday+.
+
h5. Named dates
h6. +prev_year+, +next_year+
@@ -3097,7 +3107,7 @@ h5. Named Datetimes
h6. +DateTime.current+
-Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines instance predicates +past?+, and +future?+ relative to +DateTime.current+.
+Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines +DateTime.yesterday+ and +DateTime.tomorrow+, and the instance predicates +past?+, and +future?+ relative to +DateTime.current+.
h5. Other Extensions
@@ -3274,6 +3284,12 @@ t.advance(:seconds => 1)
* If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead.
+h5. +Time.current+
+
+Active Support defines +Time.current+ to be today in the current time zone. That's like +Time.now+, except that it honors the user time zone, if defined. It also defines +Time.yesterday+ and +Time.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Time.current+.
+
+When making Time comparisons using methods which honor the user time zone, make sure to use +Time.current+ and not +Time.now+. There are cases where the user time zone might be in the future compared to the system time zone, which +Time.today+ uses by default. This means +Time.now+ may equal +Time.yesterday+.
+
h4. Time Constructors
Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+:
@@ -3359,6 +3375,49 @@ The auxiliary file is written in a standard directory for temporary files, but y
NOTE: Defined in +active_support/core_ext/file/atomic.rb+.
+h3. Extensions to +Logger+
+
+h4. +around_[level]+
+
+Takes two arguments, a +before_message+ and +after_message+ and calls the current level method on the +Logger+ instance, passing in the +before_message+, then the specified message, then the +after_message+:
+
+<ruby>
+ logger = Logger.new("log/development.log")
+ logger.around_info("before", "after") { |logger| logger.info("during") }
+</ruby>
+
+h4. +silence+
+
+Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.
+
+<ruby>
+ logger = Logger.new("log/development.log")
+ logger.silence(Logger::INFO) do
+ logger.debug("In space, no one can hear you scream.")
+ logger.info("Scream all you want, small mailman!")
+ end
+</ruby>
+
+h4. +datetime_format=+
+
+Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a +datetime_format+ method then this is ignored.
+
+<ruby>
+ class Logger::FormatWithTime < Logger::Formatter
+ cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
+
+ def self.call(severity, timestamp, progname, msg)
+ "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
+ end
+ end
+
+ logger = Logger.new("log/development.log")
+ logger.formatter = Logger::FormatWithTime
+ logger.info("<- is the current time")
+</ruby>
+
+NOTE: Defined in +active_support/core_ext/logger.rb+.
+
h3. Extensions to +NameError+
Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument.
diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile
index 972e7ea840..b80df4aa58 100644
--- a/railties/guides/source/ajax_on_rails.textile
+++ b/railties/guides/source/ajax_on_rails.textile
@@ -1,10 +1,10 @@
h2. AJAX on Rails
-This guide covers the built-in Ajax/Javascript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
+This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
* Quick introduction to AJAX and related technologies
-* Handling Javascript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
-* Testing Javascript functionality
+* Handling JavaScript the Rails way: Rails helpers, RJS, Prototype and script.aculo.us
+* Testing JavaScript functionality
endprologue.
@@ -12,7 +12,7 @@ h3. Hello AJAX - a Quick Intro
If you are a 'show me the code' type of person, you might want to skip this part and jump to the RJS section right away. However, I would really recommend to read it - you'll need the basics of DOM, http requests and other topics discussed here to really understand Ajax on Rails.
-h4. Asynchronous Javascript + XML
+h4. Asynchronous JavaScript + XML
Basic terminology, new style of creating web apps
@@ -31,7 +31,7 @@ How do 'standard' and AJAX requests differ, why does this matter for understandi
h3. Built-in Rails Helpers
-Rails' Javascript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose Javascript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other Javascript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
+Rails' JavaScript framework of choice is "Prototype":http://www.prototypejs.org. Prototype is a generic-purpose JavaScript framework that aims to ease the development of dynamic web applications by offering DOM manipulation, AJAX and other JavaScript functionality ranging from utility functions to object oriented constructs. It is not specifically written for any language, so Rails provides a set of helpers to enable seamless integration of Prototype with your Rails views.
To get access to these helpers, all you have to do is to include the prototype framework in your pages - typically in your master layout, application.html.erb - like so:
<ruby>
@@ -42,7 +42,7 @@ You are ready to add some AJAX love to your Rails app!
h4. The Quintessential AJAX Rails Helper: link_to_remote
-Let's start with the the probably most often used helper: +link_to_remote+, which has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers.
+Let's start with what is probably the most often used helper: +link_to_remote+. It has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers.
The signature of +link_to_remote+ function is the same as that of the standard +link_to+ helper:
@@ -136,7 +136,7 @@ link_to_remote "Add new item",
:before => "$('progress').show()",
:complete => "$('progress').hide()",
:success => "display_item_added(request)",
- :failure => "display_error(request)",
+ :failure => "display_error(request)"
</ruby>
** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+.
* Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though:
@@ -153,7 +153,7 @@ There are three different ways of adding AJAX forms to your view using Rails Pro
* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
-Let's se them in action one by one!
+Let's see them in action one by one!
h5. +remote_form_for+
@@ -183,7 +183,7 @@ h3. JavaScript the Rails way: RJS
In the last section we sent some AJAX requests to the server, and inserted the HTML response into the page (with the +:update+ option). However, sometimes a more complicated interaction with the page is needed, which you can either achieve with JavaScript... or with RJS! You are sending JavaScript instructions to the server in both cases, but while in the former case you have to write vanilla JavaScript, in the second you can code Rails, and sit back while Rails generates the JavaScript for you - so basically RJS is a Ruby DSL to write JavaScript in your Rails code.
-h4. Javascript without RJS
+h4. JavaScript without RJS
First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
@@ -329,9 +329,9 @@ h4. Drag and Drop
-h3. Testing Javascript
+h3. Testing JavaScript
-Javascript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with Javascript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
+JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
* (Fire)Watir
* Selenium
@@ -339,4 +339,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/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
index e3ccd6396c..7433507866 100644
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ b/railties/guides/source/api_documentation_guidelines.textile
@@ -6,7 +6,7 @@ endprologue.
h3. RDoc
-The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
+The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
h3. Wording
@@ -27,7 +27,7 @@ Communicate to the reader the current way of doing things, both explicitly and i
Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?
-The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. Historically there has been lack of consistency regarding this, but we checked with David when docrails started. All Rails documentation consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be fenomenal :).
+The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal.
Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERb. When in doubt, please have a look at some authoritative source like their official documentation.
@@ -46,10 +46,10 @@ Short docs do not need an explicit "Examples" label to introduce snippets, they
# Converts a collection of elements into a formatted string by calling
# <tt>to_s</tt> on all elements and joining them.
#
-# Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post"
+# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
</ruby>
-On the other hand big chunks of structured documentation may have a separate "Examples" section:
+On the other hand, big chunks of structured documentation may have a separate "Examples" section:
<ruby>
# ==== Examples
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index 62abc40c81..e5b8c73c43 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -65,7 +65,7 @@ To learn more about the different types of associations, read the next section o
h3. The Types of Associations
-In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
+In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations:
* +belongs_to+
* +has_one+
@@ -165,6 +165,12 @@ class Paragraph < ActiveRecord::Base
end
</ruby>
+With +:through => :sections+ specified, Rails will now understand:
+
+<ruby>
+@document.paragraphs
+</ruby>
+
h4. The +has_one :through+ Association
A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
@@ -1135,7 +1141,7 @@ h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
<ruby>
-@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
+@open_orders = @customer.orders.all(:conditions => "open = 1")
</ruby>
NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
@@ -1564,7 +1570,7 @@ h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)<
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
<ruby>
-@new_assemblies = @part.assemblies.find(:all,
+@new_assemblies = @part.assemblies.all(
:conditions => ["created_at > ?", 2.days.ago])
</ruby>
diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile
index 63c52da32a..1b5ec40d16 100644
--- a/railties/guides/source/caching_with_rails.textile
+++ b/railties/guides/source/caching_with_rails.textile
@@ -238,86 +238,95 @@ h3. Cache Stores
Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.
-Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to cache strings. Some cache store implementations, like +MemoryStore+, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that.
+h4. Configuration
-The default cache stores provided with Rails include:
-
-1) +ActiveSupport::Cache::MemoryStore+: A cache store implementation which stores everything into memory in the same process. If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won't be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using +MemoryStore+ is ok. Otherwise, consider carefully whether you should be using this cache store.
-
-+MemoryStore+ is not only able to store strings, but also arbitrary Ruby objects.
-
-+MemoryStore+ is not thread-safe. Use +SynchronizedMemoryStore+ instead if you need thread-safety.
+You can set up your application's default cache store by calling +config.cache_store=+ in the Application definition inside your +config/application.rb+ file or in an Application.configure block in an environment specific configuration file (i.e. +config/environments/*.rb+). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.
<ruby>
-ActionController::Base.cache_store = :memory_store
+config.cache_store = :memory_store
</ruby>
-2) +ActiveSupport::Cache::FileStore+: Cached data is stored on the disk, this is the default store and the default path for this store is +tmp/cache+. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If +tmp/cache+ does not exist, the default store becomes +MemoryStore+.
+Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block.
-<ruby>
-ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
-</ruby>
+You can access the cache by calling +Rails.cache+.
-3) +ActiveSupport::Cache::DRbStore+: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.
+h4. ActiveSupport::Cache::Store
-<ruby>
-ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
-</ruby>
+This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
+
+The main methods to call are +read+, +write+, +delete+, +exist?+, and +fetch+. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.
-4) +ActiveSupport::Cache::MemCacheStore+: Works like +DRbStore+, but uses Danga's +memcached+ instead. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites.
+There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.
-Special features:
+* +:namespace+ - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment.
-* Clustering and load balancing. One can specify multiple memcached servers, and +MemCacheStore+ will load balance between all available servers. If a server goes down, then +MemCacheStore+ will ignore it until it goes back online.
-* Time-based expiry support. See +write+ and the +:expires_in+ option.
-* Per-request in memory cache for all communication with the +memcached+ server(s).
+* +:compress+ - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.
-It also accepts a hash of additional options:
+* +:compress_threshold+ - This options is used in conjunction with the +:compress+ option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.
-* +:namespace+: specifies a string that will automatically be prepended to keys when accessing the memcached store.
-* +:readonly+: a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
-* +:multithread+: a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality.
+* +:expires_in+ - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
-The read and write methods of the +MemCacheStore+ accept an options hash too. When reading you can specify +:raw => true+ to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to +Marshal.load+ before being returned to you.)
+* +:race_condition_ttl+ - This option is used in conjunction with the +:expires_in+ option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the +:expires_in+ option.
-When writing to the cache it is also possible to specify +:raw => true+ means the value is not passed to +Marshal.dump+ before being stored in the cache (by default this is false).
+h4. ActiveSupport::Cache::MemoryStore
-The write method also accepts an +:unless_exist+ flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an +:expires_in+ option that specifies the time-to-live for the cached item in seconds.
+This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the +:size+ options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
<ruby>
-ActionController::Base.cache_store = :mem_cache_store, "localhost"
+ActionController::Base.cache_store = :memory_store, :size => 64.megabytes
</ruby>
-5) +ActiveSupport::Cache::SynchronizedMemoryStore+: Like +MemoryStore+ but thread-safe.
+If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
+
+This is the default cache store implementation.
+
+h4. ActiveSupport::Cache::FileStore
+
+This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
<ruby>
-ActionController::Base.cache_store = :synchronized_memory_store
+ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
</ruby>
-6) +ActiveSupport::Cache::CompressedMemCacheStore+: Works just like the regular +MemCacheStore+ but uses GZip to decompress/compress on read/write.
+With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
+
+Note that the cache will grow until the disk is full unless you periodically clear out old entries.
+
+h4. ActiveSupport::Cache::MemCacheStore
+
+This cache store uses Danga's +memcached+ server to provide a centralized cache for your application. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy.
+
+When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
+
+The +write+ and +fetch+ methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify +:raw+ to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like +increment+ and +decrement+ only on raw values. You can also specify +:unless_exist+ if you don't want memcached to overwrite an existing entry.
<ruby>
-ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost"
+ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
</ruby>
-7) Custom store: You can define your own cache store (new in Rails 2.1).
+h4. Custom Cache Stores
+
+You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
+
+To use a custom cache store, simple set the cache store to a new instance of the class.
<ruby>
-ActionController::Base.cache_store = MyOwnStore.new("parameter")
+ActionController::Base.cache_store = MyCacheStore.new
</ruby>
-NOTE: +config.cache_store+ can be used in place of +ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in +environment.rb+
+h4. Cache Keys
-In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available).
+The keys used in a cache can be any object that responds to either +:cache_key+ or to +:to_param+. You can implement the +:cache_key+ method on your classes if you need to generate custom keys. ActiveRecord will generate keys based on the class name and record id.
-You can access these cache stores at a low level for storing queries and other objects. Here's an example:
+You can use Hashes and Arrays of values as cache keys.
<ruby>
-Rails.cache.read("city") # => nil
-Rails.cache.write("city", "Duckburgh")
-Rails.cache.read("city") # => "Duckburgh"
+# This is a legal cache key
+Rails.cache.read(:site => "mysite", :owners => [owner_1, owner2])
</ruby>
+The keys you use on +Rails.cache+ will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with +Rails.cache+ and then try to pull them out with the +memcache-client+ gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
+
h3. Conditional GET support
Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
@@ -369,6 +378,7 @@ h3. Further reading
h3. Changelog
+* Feb 17, 2011: Document 3.0.0 changes to ActiveSupport::Cache
* May 02, 2009: Formatting cleanups
* April 26, 2009: Clean up typos in submitted patch
* April 1, 2009: Made a bunch of small fixes
diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile
index 11ce3a5003..581fece1ab 100644
--- a/railties/guides/source/command_line.textile
+++ b/railties/guides/source/command_line.textile
@@ -31,7 +31,7 @@ h4. +rails new+
The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails.
-WARNING: You know you need the rails gem installed by typing +gem install rails+ first, if you don't have this installed, follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html
+WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html
<shell>
$ rails new commandsapp
@@ -73,7 +73,7 @@ $ rails server
[2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000
</shell>
-With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic rails app running.
+With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running.
h4. +rails generate+
@@ -81,7 +81,7 @@ The +rails generate+ command uses templates to create a whole lot of things. You
<shell>
$ rails generate
-Usage: rails generate generator [options] [args]
+Usage: rails generate generator [args] [options]
...
...
@@ -101,11 +101,11 @@ Using generators will save you a large amount of time by writing *boilerplate co
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
-INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+.
+INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+.
<shell>
$ rails generate controller
-Usage: rails generate controller ControllerName [options]
+Usage: rails generate controller NAME [action action] [options]
...
...
@@ -122,7 +122,7 @@ Example:
Modules Example:
rails generate controller 'admin/credit_card' suspend late_fee
- Credit card admin controller with URLs /admin/credit_card/suspend.
+ Credit card admin controller with URLs like /admin/credit_card/suspend.
Controller: app/controllers/admin/credit_card_controller.rb
Views: app/views/admin/credit_card/debit.html.erb [...]
Helper: app/helpers/admin/credit_card_helper.rb
@@ -134,13 +134,17 @@ The controller generator is expecting parameters in the form of +generate contro
<shell>
$ rails generate controller Greetings hello
create app/controllers/greetings_controller.rb
+ route get "greetings/hello"
invoke erb
create app/views/greetings
create app/views/greetings/hello.html.erb
- error rspec [not found]
+ invoke test_unit
+ create test/functional/greetings_controller_test.rb
invoke helper
create app/helpers/greetings_helper.rb
- error rspec [not found]
+ invoke test_unit
+ create test/unit/helpers/greetings_helper_test.rb
+
</shell>
What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file.
@@ -152,7 +156,6 @@ class GreetingsController < ApplicationController
def hello
@message = "Hello, how are you today?"
end
-
end
</ruby>
@@ -163,7 +166,7 @@ Then the view, to display our message (in +app/views/greetings/hello.html.erb+):
<p><%= @message %></p>
</html>
-Deal. Go check it out in your browser. Fire up your server. Remember? +rails server+ at the root of your Rails application should do it.
+Deal. Go check it out in your browser. Fire up your server using +rails server+.
<shell>
$ rails server
@@ -180,7 +183,7 @@ Rails comes with a generator for data models too:
<shell>
$ rails generate model
-Usage: rails generate model ModelName [field:type, field:type]
+Usage: rails generate model NAME [field:type field:type] [options]
...
@@ -222,7 +225,7 @@ $ rails generate scaffold HighScore game:string score:integer
create app/controllers/high_scores_controller.rb
create test/functional/high_scores_controller_test.rb
create app/helpers/high_scores_helper.rb
- route map.resources :high_scores
+ route resources :high_scores
dependency model
exists app/models/
exists test/unit/
@@ -261,6 +264,15 @@ h4. +rails console+
The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
+If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+.
+
+<shell>
+$ rails console --sandbox
+Loading development environment in sandbox (Rails 3.0.0)
+Any modifications you make will be rolled back on exit
+irb(main):001:0>
+</shell>
+
h4. +rails dbconsole+
+rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
@@ -274,14 +286,14 @@ Let's say you're creating a website for a client who wants a small accounting sy
There is such a thing! The plugin we're installing is called +acts_as_paranoid+, and it lets models implement a +deleted_at+ column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things.
<shell>
-$ rails plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid
+$ rails plugin install https://github.com/technoweenie/acts_as_paranoid.git
+ ./CHANGELOG
+ ./MIT-LICENSE
...
...
</shell>
-h4. +runner+
+h4. +rails runner+
<tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance:
@@ -289,7 +301,7 @@ h4. +runner+
$ rails runner "Model.long_running_method"
</shell>
-h4. +destroy+
+h4. +rails destroy+
Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times!
@@ -318,7 +330,7 @@ $ rails destroy model Oops
notempty app
</shell>
-h4. +about+
+h4. +rake about+
Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
@@ -341,7 +353,7 @@ Environment development
h3. The Rails Advanced Command Line
-The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
+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.
h4. Rails with Databases and SCM
@@ -366,8 +378,8 @@ $ rails new . --git --database=postgresql
add 'Rakefile'
create README
add 'README'
- create app/controllers/application_controller_.rb
-add 'app/controllers/application_controller_.rb'
+ create app/controllers/application_controller.rb
+add 'app/controllers/application_controller.rb'
create app/helpers/application_helper.rb
...
create log/test.log
@@ -439,7 +451,7 @@ The Rails generator by default looks in these places for available generators, w
* Inside any plugin with a directory like "generators" or "rails_generators"
* ~/.rails/generators
* Inside any Gem you have installed with a name ending in "_generator"
-* Inside *any* Gem installed with a "rails_generators" path, and a file ending in "_generator.rb"
+* Inside any Gem installed with a "rails_generators" path, and a file ending in "_generator.rb"
* Finally, the builtin Rails generators (controller, model, mailer, etc.)
Let's try the fourth option (in our home directory), which will be easy to clean up later:
@@ -474,7 +486,7 @@ We take whatever args are supplied, save them to an instance variable, and liter
* Check there's a *public* directory. You bet there is.
* Run the ERb template called "tutorial.erb".
* Save it into "Rails.root/public/tutorial.txt".
-* Pass in the arguments we saved through the +:assign+ parameter.
+* Pass in the arguments we saved through the +:assigns+ parameter.
Next we'll build the template:
@@ -527,7 +539,7 @@ Rake is a standalone Ruby utility that replaces the Unix utility 'make', and use
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need.
<shell>
- rake --tasks
+$ rake --tasks
(in /home/foobar/commandsapp)
rake db:abort_if_pending_migrations # Raises an error if there are pending migrations
rake db:charset # Retrieves the charset for the current environment's database
@@ -540,8 +552,6 @@ rake tmp:sessions:clear # Clears all files in tmp/sessions
rake tmp:sockets:clear # Clears all files in tmp/sockets
</shell>
-Let's take a look at some of these 80 or so rake tasks.
-
h5. +db:+ Database
The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database.
@@ -550,24 +560,10 @@ h5. +doc:+ Documentation
If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
-h5. +gems:+ Ruby gems
-
-You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive.
-
-NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses.
-
h5. +notes:+ Code note enumeration
These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them.
-h5. +rails:+ Rails-specific tasks
-
-In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version.
-
-When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+.
-
-After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous).
-
h5. +test:+ Rails tests
INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
@@ -582,13 +578,13 @@ You can list all the timezones Rails knows about with +rake time:zones:all+, whi
h5. +tmp:+ Temporary files
-The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of an +rm -rf *+ gone awry.
+The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of deletions gone awry.
h5. Miscellaneous Tasks
+rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
- +rake secret+ will give you a psuedo-random key to use for your session secret.
+ +rake secret+ will give you a pseudo-random key to use for your session secret.
+rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index 44f7a61a77..62b846e871 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -42,9 +42,9 @@ h4. Rails General Configuration
* +config.after_initialize+ takes a block which will be ran _after_ Rails has finished initializing. Useful for configuring values set up by other initializers:
<ruby>
- config.after_initialize do
- ActionView::Base.sanitized_allowed_tags.delete 'div'
- end
+config.after_initialize do
+ ActionView::Base.sanitized_allowed_tags.delete 'div'
+end
</ruby>
* +config.allow_concurrency+ should be set to +true+ to allow concurrent (threadsafe) action processing. Set to +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!+.
@@ -63,6 +63,8 @@ h4. Rails General Configuration
* +config.cache_classes+ controls whether or not application classes should be reloaded on each request. Defaults to _true_ in development, _false_ in test and production. Can also be enabled with +threadsafe!+.
+* +config.action_view.cache_template_loading+ controls whether or not templates should be reloaded on each request. Defaults to whatever is set for config.cache_classes.
+
* +config.cache_store+ configures which cache store to use for Rails caching. Options include +:memory_store+, +:file_store+, +:mem_cache_store+ or the name of your own custom class. Defaults to +:file_store+.
* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to _true_.
@@ -115,7 +117,7 @@ WARNING: Threadsafe operation is incompatible with the normal workings of develo
* +config.time_zone+ sets the default time zone for the application and enables time zone awareness for Active Record.
-* +config.whiny_nils+ enables or disabled warnings when an methods of nil are invoked. Defaults to _false_.
+* +config.whiny_nils+ enables or disables warnings when any methods of nil are invoked. Defaults to _true_ in development and test environments.
h4. Configuring Generators
@@ -131,12 +133,12 @@ Rails 3 allows you to alter what generators are used with the +config.generators
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_
+* +helper+ defines whether or not to generate helpers. Defaults to _true_.
* +orm+ defines which orm to use. Defaults to _nil_, so will use Active Record by default.
-* +integration_tool+ defines which integration tool to use. Defaults to _nil_
-* +performance_tool+ defines which performance tool to use. Defaults to _nil_
+* +integration_tool+ defines which integration tool to use. Defaults to _nil_.
+* +performance_tool+ defines which performance tool to use. Defaults to _nil_.
* +resource_controller+ defines which generator to use for generating a controller when using +rails generate resource+. Defaults to +:controller+.
-* +scaffold_controller+ different from +resource_controller+, defines which generator to use for generating a _scaffolded_ controller when using +rails generate scaffold+. Defaults to +:scaffold_controller+
+* +scaffold_controller+ different from +resource_controller+, defines which generator to use for generating a _scaffolded_ controller when using +rails generate scaffold+. Defaults to +:scaffold_controller+.
* +stylesheets+ turns on the hook for stylesheets in generators. Used in Rails for when the +scaffold+ generator is ran, but this hook can be used in other generates as well.
* +test_framework+ defines which test framework to use. Defaults to _nil_, so will use Test::Unit by default.
* +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+.
@@ -152,7 +154,7 @@ Every Rails application comes with a standard set of middleware which it uses in
* +Rails::Rack::Logger+ Will notify the logs that the request has began. After request is complete, flushes all the logs.
* +ActionDispatch::ShowExceptions+ rescues any exception returned by the application and renders nice exception pages if the request is local or if +config.consider_all_requests_local+ is set to _true_. If +config.action_dispatch.show_exceptions+ is set to _false_, exceptions will be raised regardless.
* +ActionDispatch::RemoteIp+ checks for IP spoofing attacks. Configurable with the +config.action_dispatch.ip_spoofing_check+ and +config.action_dispatch.trusted_proxies+ settings.
-* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch_
+* +Rack::Sendfile+ The Sendfile middleware intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch.x_sendfile_header+
* +ActionDispatch::Callbacks+ Runs the prepare callbacks before serving the request.
* +ActiveRecord::ConnectionAdapters::ConnectionManagement+ cleans active connections after each request, unless the +rack.test+ key in the request environment is set to _true_.
* +ActiveRecord::QueryCache+ caches all +SELECT+ queries generated in a request. If an +INSERT+ or +UPDATE+ takes place then the cache is cleaned.
@@ -188,6 +190,12 @@ Middlewares can also be completely swapped out and replaced with others:
config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns
</ruby>
+They can also be removed from the stack completely:
+
+<ruby>
+ config.middleware.delete ActionDispatch::BestStandardsSupport
+</ruby>
+
h4. Configuring i18n
* +config.i18n.default_locale+ sets the default locale of an application used for i18n. Defaults to +:en+.
@@ -210,7 +218,7 @@ h4. Configuring Active Record
* +config.active_record.pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to +true+ (the default), then the Customer class will use the +customers+ table. If set to +false+, then the Customers class will use the +customer+ table.
-* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:local+.
+* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:utc+ for Rails, although ActiveRecord defaults to +:local+ when used outside of Rails.
* +config.active_record.schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements.
@@ -234,7 +242,7 @@ h4. Configuring Action Controller
* +config.action_controller.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+.
-* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to Rails.public_path (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files.
+* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files.
* +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+
@@ -252,7 +260,7 @@ h4. Configuring Action Controller
The caching code adds two additional settings:
-* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to +Rails.root + "/public"+).
+* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>).
* +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+.
@@ -270,17 +278,17 @@ h4. Configuring Action Dispatch
* +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.
+* +ActionDispatch::Callbacks.before+ takes a block of code to run before the request.
* +ActionDispatch::Callbacks.to_prepare+ takes a block to run after +ActionDispatch::Callbacks.before+, but before the request. Runs for every request in +development+ mode, but only once for +production+ or environments with +cache_classes+ set to +true+.
-* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request.
+* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request.
h4. Configuring Action View
There are only a few configuration options for Action View, starting with four on +ActionView::Base+:
-* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+.
+* +config.action_view.debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alerts the caught exception (and then re-raises it). The default is +false+.
* +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is <tt>Proc.new{ |html_tag, instance| %Q(%&lt;div class=&quot;field_with_errors&quot;&gt;#{html_tag}&lt;/div&gt;).html_safe }</tt>
@@ -290,7 +298,7 @@ There are only a few configuration options for Action View, starting with four o
* +config.action_view.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information.
-* +config.action_view.javascript_expansions+ a hash containining expansions that can be used for javascript include tag. By default, this is defined as:
+* +config.action_view.javascript_expansions+ is a hash containing expansions that can be used for the JavaScript include tag. By default, this is defined as:
<ruby>
config.action_view.javascript_expansions = { :defaults => ['prototype', 'effects', 'dragdrop', 'controls', 'rails'] }
@@ -302,7 +310,7 @@ However, you may add to this by defining others:
config.action_view.javascript_expansions[:jquery] = ["jquery", "jquery-ui"]
</ruby>
-Then this can be referenced in the view with the following code:
+And can reference in the view with the following code:
<ruby>
<%= javascript_include_tag :jquery %>
@@ -368,20 +376,36 @@ There are a few configuration options available in Active Support:
* +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations.
+* +ActiveSupport::Deprecation.behavior+ alternative setter to +config.active_support.deprecation+ which configures the behavior of deprecation warnings for Rails.
+
+* +ActiveSupport::Deprecation.silence+ takes a block in which all deprecation warnings are silenced.
+
+* +ActiveSupport::Deprecation.silenced+ sets whether or not to display deprecation warnings.
+
* +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
+
h3. Rails Environment Settings
Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails:
-* +ENV['RAILS_ENV']+ defines the Rails environment (production, development, test, and so on) that Rails will run under.
+* +ENV["RAILS_ENV"]+ defines the Rails environment (production, development, test, and so on) that Rails will run under.
-* +ENV['RAILS_RELATIVE_URL_ROOT']+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory.
+* +ENV["RAILS_RELATIVE_URL_ROOT"]+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory.
* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets.
* +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.
+
+h3. Using Initializer Files
+
+After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any file of Ruby code stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts.
+
+NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
+
+TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+.
+
h3. Initialization events
Rails has 5 initialization events which can be hooked into (listed in order that they are ran):
@@ -390,7 +414,7 @@ Rails has 5 initialization events which can be hooked into (listed in order that
* +before_initialize+: This is run directly before the initialization process of the application occurs with the +:bootstrap_hook+ initializer near the beginning of the Rails initialization process.
-* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built.
+* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built.
* +before_eager_load+: This is run directly before eager loading occurs, which is the default behaviour for the _production_ environment and not for the +development+ enviroment.
@@ -404,12 +428,12 @@ h4. +Rails::Railtie#initializer+
Rails has several initializers that run on startup that are all defined by using the +initializer+ method from +Rails::Railtie+. Here's an example of the +initialize_whiny_nils+ initializer from Active Support:
<ruby>
- initializer "active_support.initialize_whiny_nils" do |app|
- require 'active_support/whiny_nil' if app.config.whiny_nils
- end
+initializer "active_support.initialize_whiny_nils" do |app|
+ require 'active_support/whiny_nil' if app.config.whiny_nils
+end
</ruby>
-The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_.
+The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_.
Initializers defined using the +initializer+ method will be ran in the order they are defined in, with the exception of ones that use the +:before+ or +:after+ methods.
@@ -442,7 +466,7 @@ Serves as a placeholder so that +:load_environment_config+ can be defined to run
*+i18n.callbacks+* In the development environment, sets up a +to_prepare+ callback which will call +I18n.reload!+ if any of the locales have changed since the last request. In production mode this callback will only run on the first request.
-*+active_support.initialize_whiny_nils+* Will require +active_support/whiny_nil+ if +config.whiny_nil+ is set to +true+. This file will output errors such as:
+*+active_support.initialize_whiny_nils+* Will require +active_support/whiny_nil+ if +config.whiny_nils+ is set to +true+. This file will output errors such as:
<plain>
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
@@ -456,7 +480,7 @@ You might have expected an instance of Array.
The error occurred while evaluating nil.each
</plain>
-*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +log+ for development, +notify+ for production and +stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file.
+*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +:log+ for development, +:notify+ for production and +:stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. Can be set to an array of values.
*+active_support.initialize_time_zone+* Sets the default time zone for the application based off the +config.time_zone+ setting, which defaults to "UTC".
@@ -536,8 +560,7 @@ TIP: If you have any ordering dependency in your initializers, you can control t
*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
-*+disable_dependency_loading+*
-
+*+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+.
h3. Changelog
diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile
index 3d4607de1d..8d19d78324 100644
--- a/railties/guides/source/contribute.textile
+++ b/railties/guides/source/contribute.textile
@@ -13,8 +13,8 @@ h3. How to Contribute?
* Assets are stored in the +railties/guides/assets+ directory.
* Sample format : "Active Record Associations":http://github.com/lifo/docrails/blob/3e56a3832415476fdd1cb963980d0ae390ac1ed3/railties/guides/source/association_basics.textile.
* Sample output : "Active Record Associations":association_basics.html.
-* You can build the Guides during testing by running +rake generate_guides+ in the +railties+ directory.
-* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +rake validate_guides+ in the +railties+ directory.
+* You can build the Guides during testing by running +bundle exec rake generate_guides+ in the +railties+ directory.
+* You're encouraged to validate XHTML for the generated guides before commiting your changes by running +bundle exec rake validate_guides+ in the +railties+ directory.
* Edge guides "can be consulted online":http://edgeguides.rubyonrails.org/. That website is generated periodically from docrails.
h3. What to Contribute?
diff --git a/railties/guides/source/contributing_to_rails.textile b/railties/guides/source/contributing_to_rails.textile
deleted file mode 100644
index 1a1f4e9858..0000000000
--- a/railties/guides/source/contributing_to_rails.textile
+++ /dev/null
@@ -1,311 +0,0 @@
-h2. Contributing to Rails
-
-This guide covers ways in which _you_ can become a part of the ongoing development of Rails. After reading it, you should be familiar with:
-
-* Using Lighthouse to report issues with Rails
-* Cloning edge Rails and running the test suite
-* Helping to resolve existing issues
-* Contributing to the Rails documentation
-* Contributing to the Rails code
-
-Rails is not "someone else's framework." Over the years, hundreds of people have contributed code ranging from a single character to massive architectural changes, all with the goal of making Rails better for everyone. Even if you don't feel up to writing code yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches to contributing documentation.
-
-endprologue.
-
-h3. Reporting a Rails Issue
-
-Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload tests or patches.
-
-NOTE: Bugs in the most recent released version of Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this Guide you'll find out how to get edge Rails for testing.
-
-h4. Creating a Bug Report
-
-If you've found a problem in Rails, you can start by "adding a new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new to the Rails Lighthouse. At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
-
-You shouldn't assign the bug to a particular core developer (through the *Who's Responsible* select list) unless you know for sure which developer will be handling any patch. The core team periodically reviews issues and assigns developers and milestones to them.
-
-You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the *Choose some tags* textbox), rather than creating new tags.
-
-Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
-
-h4. Special Treatment for Security Issues
-
-If you've found a security vulnerability in Rails, please do *not* report it via a Lighthouse ticket. Lighthouse tickets are public as soon as they are entered. Instead, you should use the dedicated email address "security@rubyonrails.org":mailto:security@rubyonrails.org to report any vulnerabilities. This alias is monitored and the core team will work with you to quickly and completely address any such vulnerabilities.
-
-WARNING: Just to emphasize the point, _please do not report security vulnerabilities on public Lighthouse tickets_. This will only expose your fellow Rails developers to needless risks.
-
-You should receive an acknowledgement and detailed response to any reported security issue within 48 hours. If you don't think you're getting adequate response from the security alias, refer to the "Rails security policy page":http://rubyonrails.org/security for direct emails for the current Rails security coordinators.
-
-h4. What About Feature Requests?
-
-Please don't put "feature request" tickets into Lighthouse. If there's a new feature that you want to see added to 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 Rails. If you enter a wishlist item in Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
-
-h3. Running the Rails Test Suite
-
-To move on from submitting bugs to helping resolve existing issues or contributing your own code to Rails, you _must_ be able to run the Rails test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
-
-h4. Install git
-
-Rails uses git for source code control. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The "git homepage":http://git-scm.com/ has installation instructions. If you’re on OS X, use the "Git for OS X":http://code.google.com/p/git-osx-installer/ installer. If you're unfamiliar with git, there are a variety of resources on the net that will help you learn more:
-
-* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/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://github.com/guides/home 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.
-
-h4. Get the Rails Source Code
-
-Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run:
-
-<shell>
-git clone git://github.com/rails/rails.git
-cd rails
-</shell>
-
-h4. Set up and Run the Tests
-
-All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. First, you need to install all Rails dependencies with bundler:
-
-NOTE: Ensure you install bundler v1.0
-
-<shell>
-gem install bundler
-bundle install --without db
-</shell>
-
-The second command will install all dependencies, except MySQL and PostgreSQL. We will come back at these soon. With dependencies installed, you can run the whole Rails test suite with:
-
-<shell>
-rake test
-</shell>
-
-You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command:
-
-<shell>
-cd actionpack
-rake test
-</shell>
-
-h4. Testing Active Record
-
-By default, when you run Active Record tests, it will execute the test suite three times, one for each of the main databases: SQLite3, MySQL and PostgreSQL. If you are adding a feature that is not specific to the database, you can run the test suite (or just one file) for just one of them. Here is an example for SQLite3:
-
-<shell>
-cd activerecord
-rake test_sqlite3
-rake test_sqlite3 TEST=test/cases/validations_test.rb
-</shell>
-
-If you want to use another database, as MySQL, you need to create a user named +rails+ with privileges on the test databases.
-
-<shell>
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
- to 'rails'@'localhost';
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
- to 'rails'@'localhost';
-</shell>
-
-Now you'll have to install Active Record dependencies. This step is a little tricky because just running +bundle install+ without the +--without db+ parameter won't get those dependencies installed. It turns out that bundler remembers the +--without db+ parameter between calls so you'll have to manually override this. (See the "+bundle_install+ man page":http://gembundler.com/man/bundle-install.1.html for details)
-
-The easiest way to do this is to remove bundler's config file and then run +install+ again:
-
-<shell>
-rm .bundle/config
-bundle install
-</shell>
-
-INFO: If you don't feel comfortable deleting bundler's config file, you can achieve the same effect by manually removing the "+BUNDLE_WITHOUT: db+" line on +.bundle/config+.
-
-Finally, enter this from the +activerecord+ directory to create the test databases:
-
-<shell>
-rake mysql:build_databases
-</shell>
-
-NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
-
-If you’re using another database, check the files under +activerecord/test/connections+ in the Rails source code for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
-
-You can now run tests as you did for +sqlite3+:
-
-<shell>
-rake test_mysql
-</shell>
-
-You can also replace +mysql+ with +postgresql+, +jdbcmysql+, +jdbcsqlite3+ or +jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the Rails continuous integration server runs.
-
-NOTE: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite 3. Subtle differences between the various Active Record database adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
-
-h4. Older versions of Rails
-
-If you want to work add a fix to older versions of Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to Rails 2.3 branch:
-
-<shell>
-git branch --track 2-3-stable origin/2-3-stable
-git checkout 2-3-stable
-</shell>
-
-TIP: You may want to "put your git branch name in your shell prompt":http://github.com/guides/put-your-git-branch-name-in-your-shell-prompt to make it easier to remember which version of the code you're working with.
-
-h3. Helping to Resolve Existing Issues
-
-As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find hundreds of issues already requiring attention. What can you do for these? Quite a bit, actually:
-
-h4. Verifying Bug Reports
-
-For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
-
-If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
-
-If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the Rails source: looking at the existing test files will teach you how to write more tests for Rails. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
-
-Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
-
-h4. Testing Patches
-
-You can also help out by examining patches that have been submitted to Rails via Lighthouse. To apply someone's changes you need to first create a branch of the Rails source code:
-
-<shell>
-git checkout -b testing_branch
-</shell>
-
-Then you can apply their patch:
-
-<shell>
-git apply their-patch-file.diff
-</shell>
-
-After applying a patch, test it out! Here are some things to think about:
-
-* Does the patch actually work?
-* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
-* Does the documentation still seem right to you?
-* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
-
-Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
-
-<blockquote>
-I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
-</blockquote>
-
-If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things.
-
-h3. Contributing to the Rails Documentation
-
-Another area where you can help out if you're not yet ready to take the plunge to writing Rails core code is with Rails documentation. You can help with the Rails Guides or the Rails API documentation.
-
-TIP: "docrails":http://github.com/lifo/docrails/tree/master is the documentation branch for Rails with an *open commit policy*, it has public write access. Documentation changes made as part of the "docrails":http://github.com/lifo/docrails/tree/master project are merged back to the Rails master code from time to time. Check out the "original announcement":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch for more details.
-
-h4. The Rails Guides
-
-The "Rails Guides":http://guides.rubyonrails.org/ are a set of online resources that are designed to make people productive with Rails and to understand how all of the pieces fit together. These guides (including this one!) are written as part of the "docrails":http://github.com/lifo/docrails/tree/master project. If you have an idea for a new guide, or improvements for an existing guide, you can refer to the "contribution page":contribute.html for instructions on getting involved.
-
-h4. The Rails API Documentation
-
-The "Rails API documentation":http://api.rubyonrails.org/ is automatically generated from the Rails source code via "RDoc":http://rdoc.rubyforge.org/. If you find some part of the documentation to be incomplete, confusing, or just plain wrong, you can step in and fix it.
-
-To contribute an update to the API documentation, you can contact "lifo":http://github.com/lifo on GitHub and ask for commit rights to the docrails repository and push your changes to the docrails repository. Please follow the "docrails RDoc conventions":http://wiki.github.com/lifo/docrails/rails-api-documentation-conventions when contributing the changes.
-
-h3. The Rails Wiki
-
-The "Rails wiki":http://wiki.rubyonrails.org/ is a collection of user-generated and freely-editable information about Rails. It covers everything from getting started to FAQs to how-tos and popular plugins. To contribute to the wiki, just find some useful information that isn't there already and add it. There are style guidelines to help keep the wiki a coherent resources; see the section on "contributing to the wiki":http://wiki.rubyonrails.org/#contributing_to_the_wiki for more details.
-
-h3. Contributing to the Rails Code
-
-When you're ready to take the plunge, one of the most helpful ways to contribute to Rails is to actually submit source code. Here's a step-by-step listing of the things you need to do to make this a successful experience.
-
-h4. Learn the Language and the Framework
-
-Learn at least _something_ about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) "The Ruby Programming Language":http://www.amazon.com/gp/product/0596516177?ie=UTF8&linkCode=as2&camp=1789&creative=390957&creativeASIN=0596516177 and have browsed the Rails source code.
-
-h4. Fork the Rails Source Code
-
-Fork Rails. You’re not going to put your patches right into the master branch, OK? This is where you need that copy of Rails that you cloned earlier. Think of a name for your new branch and run
-
-<shell>
-git checkout -b my_new_branch
-</shell>
-
-It doesn’t really matter what name you use, because this branch will only exist on your local computer.
-
-h4. Write Your Code
-
-Now get busy and add your code to Rails (or edit the existing code). You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
-
-* Get the code right
-* Use Rails idioms and helpers
-* Include tests that fail without your code, and pass with it
-* Update the documentation
-
-h4. Follow the Coding Conventions
-
-Rails follows a simple set of coding style conventions.
-
-* Two spaces, no tabs
-* Prefer +&amp;&amp;+/+||+ over +and+/+or+
-* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+
-* Follow the conventions you see used in the source already
-
-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.
-
-You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
-
-h4. Commit Your Changes
-
-When you're happy with the code on your computer, you need to commit the changes to git:
-
-<shell>
-git commit -a -m "Here is a commit message"
-</shell>
-
-h4. Update Rails
-
-Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them:
-
-<shell>
-git checkout master
-git pull
-</shell>
-
-Now reapply your patch on top of the latest changes:
-
-<shell>
-git checkout my_new_branch
-git rebase master
-</shell>
-
-No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
-
-h4. Create a Patch
-
-Now you can create a patch file to share with other developers (and with the Rails core team). Still in your branch, run
-
-<shell>
-git commit -a
-git format-patch master --stdout > my_new_patch.diff
-</shell>
-
-Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in.
-
-h4. Create a Lighthouse Ticket
-
-Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
-
-h4. Get Some Feedback
-
-Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
-
-h4. Iterate as Necessary
-
-It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
-
-And then...think about your next contribution!
-
-h3. Changelog
-
-* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
-* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
-
diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile
new file mode 100644
index 0000000000..1977f8d0ce
--- /dev/null
+++ b/railties/guides/source/contributing_to_ruby_on_rails.textile
@@ -0,0 +1,370 @@
+h2. Contributing to Ruby on Rails
+
+This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with:
+
+* Using Lighthouse to report issues
+* Cloning master and running the test suite
+* Helping to resolve existing issues
+* Contributing to the Ruby on Rails documentation
+* Contributing to the Ruby on Rails code
+
+Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation. All with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
+
+endprologue.
+
+h3. Reporting an Issue
+
+Ruby on Rails uses a "Lighthouse project":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/ to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) Lighthouse account in order to comment on issues or to upload patches.
+
+NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
+
+h4. Creating a Bug Report
+
+If you've found a problem in Ruby on Rails which is not a security risk do a search in Lighthouse in case it was already reported. If you find no ticket addressing it you can "add a new one":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new. (See the next section for reporting security issues.)
+
+At the minimum, your ticket needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
+
+You shouldn't assign the bug to a particular core developer unless you know for sure which developer will be handling that issue. The core team periodically reviews issues and assigns developers and milestones to them.
+
+You should set tags for your issue. Use the "bug" tag for a bug report, and add the "patch" tag if you are attaching a patch. Try to find some relevant tags from the existing tag list (which will appear as soon as you start typing in the "Choose some tags" textbox), rather than creating new tags.
+
+Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
+
+h4. Special Treatment for Security Issues
+
+WARNING: Please do not report security vulnerabilities on public Lighthouse tickets. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
+
+h4. What About Feature Requests?
+
+Please don't put "feature request" tickets into Lighthouse. 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 Lighthouse with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
+
+h3. Running the Test Suite
+
+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
+
+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://www.kernel.org/pub/software/scm/git/docs/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://github.com/guides/home 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.
+
+h4. 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:
+
+<shell>
+$ git clone git://github.com/rails/rails.git
+$ cd rails
+</shell>
+
+h4. 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.
+
+Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's
+
+<shell>
+$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev
+</shell>
+
+Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with
+
+<shell>
+$ sudo apt-get install sqlite3 libsqlite3-dev
+</shell>
+
+Get a recent version of "Bundler":http://gembundler.com/:
+
+<shell>
+$ gem install bundler
+</shell>
+
+and run:
+
+<shell>
+$ bundle install --without db
+</shell>
+
+This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with:
+
+<shell>
+$ rake test
+</shell>
+
+You can also run tests for an specific framework, like Action Pack, by going into its directory and executing the same command:
+
+<shell>
+$ cd actionpack
+$ rake test
+</shell>
+
+h4. Warnings
+
+The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no warning, but there may be a few, and also 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 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 rake test
+</shell>
+
+h4. Testing Active Record
+
+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 setup 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. SQLite3
+
+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:
+
+<shell>
+$ cd activerecord
+$ rake test_sqlite3
+</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
+
+<shell>
+$ sudo apt-get install mysql-server libmysqlclient15-dev
+$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
+</shell>
+
+After that run:
+
+<shell>
+$ rm .bundle/config
+$ bundle install
+</shell>
+
+We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file).
+
+In order to be able to run the test suite against MySQL you need to create a user named +rails+ with privileges on the test databases:
+
+<shell>
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
+ to 'rails'@'localhost';
+mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
+ to 'rails'@'localhost';
+</shell>
+
+and create the test databases:
+
+<shell>
+$ cd activerecord
+$ rake mysql:build_databases
+</shell>
+
+PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account
+
+<shell>
+$ sudo -u postgres createuser --superuser $USER
+</shell>
+
+and after that create the test databases with
+
+<shell>
+$ cd activerecord
+$ rake postgresql:build_databases
+</shell>
+
+NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
+
+If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
+
+You can now run tests as you did for +sqlite3+, the tasks are
+
+<shell>
+test_mysql
+test_mysql2
+test_postgresql
+</shell>
+
+respectively. As we mentioned before
+
+<shell>
+$ rake test
+</shell>
+
+will now run the four of them in turn.
+
+You can also invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the continuous integration server runs.
+
+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 2-3-stable branch:
+
+<shell>
+$ git branch --track 2-3-stable origin/2-3-stable
+$ git checkout 2-3-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.
+
+h3. Helping to Resolve Existing Issues
+
+As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "open tickets":https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets?q=state%3Aopen list in Lighthouse, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+
+h4. Verifying Bug Reports
+
+For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the ticket saying that you're seeing the same thing.
+
+If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
+
+If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
+
+Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
+
+h4. Testing Patches
+
+You can also help out by examining patches that have been submitted to Ruby on Rails via Lighthouse. To apply someone's changes you need to first create a dedicated branch:
+
+<shell>
+$ git checkout -b testing_branch
+</shell>
+
+Then you can apply their patch:
+
+<shell>
+$ git am their-patch-file.diff
+</shell>
+
+After applying a patch, test it out! Here are some things to think about:
+
+* Does the patch actually work?
+* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
+* Does it have proper documentation coverage? Should documentation elsewhere be updated?
+* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
+
+Once you're happy that the patch contains a good change, comment on the Lighthouse ticket indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
+
+<blockquote>
+I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
+</blockquote>
+
+If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the patch. Once three people have approved it, add the "verified" tag. This will bring it to the attention of a core team member who will review the changes looking for the same kinds of things.
+
+h3. Contributing to the Rails Documentation
+
+Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference.
+
+You can create a ticket in Lighthouse to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":http://github.com/lifo/docrails/tree/master. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
+
+When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html.
+
+NOTE: As explained above, ordinary code patches should have proper documentation coverage. docrails is only used for isolated documentation improvements.
+
+WARNING: docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails.
+
+If you have an idea for a new guide you can refer to the "contribution page":contribute.html for instructions on getting involved.
+
+h3. Contributing to the Rails Code
+
+h4. Clone the Rails Repository
+
+The first thing you need to do to be able to contribute code is to clone the repository:
+
+<shell>
+$ git clone git://github.com/rails/rails.git
+</shell>
+
+and create a dedicated branch:
+
+<shell>
+$ cd rails
+$ git checkout -b my_new_branch
+</shell>
+
+It doesn’t really matter what name you use, because this branch will only exist on your local computer.
+
+h4. Write Your Code
+
+Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
+
+* Get the code right
+* Use Rails idioms and helpers
+* Include tests that fail without your code, and pass with it
+* Update the documentation, the surrounding one, examples elsewhere, guides, whatever is affected by your contribution
+
+h4. Follow the Coding Conventions
+
+Rails follows a simple set of coding style conventions.
+
+* Two spaces, no tabs
+* Prefer +&amp;&amp;+/+||+ over +and+/+or+
+* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+
+* Follow the conventions you see used in the source already
+
+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.
+
+You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
+
+h4. Commit Your Changes
+
+When you're happy with the code on your computer, you need to commit the changes to git:
+
+<shell>
+$ git commit -a -m "Here is a commit message"
+</shell>
+
+h4. Update master
+
+It’s pretty likely that other changes to master have happened while you were working. Go get them:
+
+<shell>
+$ git checkout master
+$ git pull
+</shell>
+
+Now reapply your patch on top of the latest changes:
+
+<shell>
+$ git checkout my_new_branch
+$ git rebase master
+</shell>
+
+No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
+
+h4. Create a Patch
+
+Now you can create a patch file to share with other developers (and with the core team). Still in your branch, run
+
+<shell>
+$ git commit -a
+$ git format-patch master --stdout > my_new_patch.diff
+</shell>
+
+Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in.
+
+h4. Create a Lighthouse Ticket
+
+Now create a ticket with your patch. Go to the "new ticket":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/new page at Lighthouse. Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
+
+h4. Get Some Feedback
+
+Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
+
+h4. Iterate as Necessary
+
+It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
+
+And then...think about your next contribution!
+
+h3. Rails Contributors
+
+All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org.
+
+h3. Changelog
+
+* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn
+* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
+* August 1, 2009: Updates/amplifications by "Mike Gunderloy":credits.html#mgunderloy
+* March 2, 2009: Initial draft by "Mike Gunderloy":credits.html#mgunderloy
+
diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb
index 825e042628..8c2f1ffeb6 100644
--- a/railties/guides/source/credits.html.erb
+++ b/railties/guides/source/credits.html.erb
@@ -20,7 +20,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('Xavier Noria', 'fxn', 'fxn.png') do %>
- Xavier has been into Rails since 2005, he is currently a Rails consultant. Xavier is Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
+ Xavier Noria has been into Ruby on Rails since 2005. He is a Rails committer and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently a Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
<% end %>
<h3 class="section">Rails Guides Designers</h3>
@@ -52,7 +52,7 @@ Ruby on Rails Guides: Credits
<% end %>
<%= author('James Miller', 'bensie') do %>
- James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. Find me on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
+ James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
<% end %>
<%= author('Emilio Tagua', 'miloops') do %>
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index 6613fad406..d51cdf5169 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -48,7 +48,7 @@ Title: Rails debugging guide
h4. +to_yaml+
-Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:
+Displaying an instance variable, or any other object or method, in YAML format can be achieved this way:
<html>
<%= simple_format @post.to_yaml %>
@@ -122,7 +122,7 @@ It can also be useful to save information to log files at runtime. Rails maintai
h4. What is the Logger?
-Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4R+ if you wish.
+Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish.
You can specify an alternative logger in your +environment.rb+ or any environment file:
@@ -178,7 +178,7 @@ class PostsController < ApplicationController
if @post.save
flash[:notice] = 'Post was successfully created.'
- logger.debug "The post was saved and now is the user is going to be redirected..."
+ logger.debug "The post was saved and now the user is going to be redirected..."
redirect_to(@post)
else
render :action => "new"
@@ -204,7 +204,7 @@ Post should be valid: true
Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
"created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
-The post was saved and now is the user is going to be redirected...
+The post was saved and now the user is going to be redirected...
Redirected to #<Post:0x20af760>
Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
</shell>
@@ -251,7 +251,7 @@ If you see the message in the console or logs:
Make sure you have started your web server with the option +--debugger+:
<shell>
-~/PathTo/rails_project$ rails server --debugger
+$ rails server --debugger
=> Booting WEBrick
=> Rails 3.0.0 application starting on http://0.0.0.0:3000
=> Debugger enabled
@@ -269,7 +269,7 @@ If you got there by a browser request, the browser tab containing the request wi
For example:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:7)
</shell>
@@ -302,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a
3 # GET /posts.xml
4 def index
5 debugger
-=> 6 @posts = Post.find(:all)
+=> 6 @posts = Post.all
7
8 respond_to do |format|
9 format.html # index.html.erb
@@ -380,7 +380,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio
This example shows how you can print the instance_variables defined within the current context:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:11) instance_variables
["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
</shell>
@@ -477,7 +477,7 @@ end
TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method.
<shell>
-/PathTo/project $ rails console
+$ rails console
Loading development environment (Rails 2.1.0)
>> require "ruby-debug"
=> []
@@ -601,7 +601,7 @@ There are some settings that can be configured in ruby-debug to make it easier t
You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command.
-TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded. and configure itself accordingly.
+TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly.
Here's a good start for an +.rdebugrc+:
@@ -615,7 +615,7 @@ h3. Debugging Memory Leaks
A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
-In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.
+In this section, you will learn how to find and fix such leaks by using tools such as BleakHouse and Valgrind.
h4. BleakHouse
@@ -626,7 +626,7 @@ If a Ruby object does not go out of scope, the Ruby Garbage Collector won't swee
To install it run:
<shell>
-sudo gem install bleak_house
+$ sudo gem install bleak_house
</shell>
Then setup your application for profiling. Then add the following at the bottom of config/environment.rb:
@@ -638,7 +638,7 @@ require 'bleak_house' if ENV['BLEAK_HOUSE']
Start a server instance with BleakHouse integration:
<shell>
-RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server
+$ RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server
</shell>
Make sure to run a couple hundred requests to get better data samples, then press +CTRL-C+. The server will stop and Bleak House will produce a dumpfile in +/tmp+:
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index e178a60307..ace433e30c 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -9,6 +9,7 @@ In this guide you will:
* Generate select boxes from multiple types of data
* 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
endprologue.
@@ -187,7 +188,7 @@ output:
Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript.
-TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating +filter_parameter_logging(:password)+ in your ApplicationController.
+TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged.
h3. Dealing with Model Objects
@@ -594,7 +595,7 @@ NOTE: If the user has not selected a file the corresponding parameter will be an
h4. Dealing with Ajax
-Unlike other forms making an asynchronous file upload form is not as simple as replacing +form_for+ with +remote_form_for+. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
+Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with <tt>:remote => true</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
h3. Customizing Form Builders
@@ -644,7 +645,7 @@ Fundamentally HTML forms don't know about any sort of structured data, all they
TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example,
<ruby>
-ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
+ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
# => {"name"=>"fred", "phone"=>"0123456789"}
</ruby>
@@ -763,6 +764,40 @@ As a shortcut you can append [] to the name and omit the +:index+ option. This i
produces exactly the same output as the previous example.
+h3. Forms to external resources
+
+If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an +authenticity_token+ for this resource. You can do it by passing an +:authenticity_token => 'your_external_token'+ parameter to the +form_tag+ options:
+
+<erb>
+<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
+ Form contents
+<% end %>
+</erb>
+
+Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an +authenticity_token+ hidden field at all. For doing this just pass +false+ to the +:authenticity_token+ option:
+
+<erb>
+<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
+ Form contents
+<% end %>
+</erb>
+
+The same technique is available for the +form_for+ too:
+
+<erb>
+<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
+ Form contents
+<% end %>
+</erb>
+
+Or if you don't want to render an +authenticity_token+ field:
+
+<erb>
+<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
+ Form contents
+<% end %>
+</erb>
+
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:
@@ -776,6 +811,7 @@ Many apps grow beyond simple forms editing a single object. For example when cre
h3. Changelog
+* February 5, 2011: Added 'Forms to external resources' section. Timothy N. Tsvetkov <timothy.tsvetkov@gmail.com>
* April 6, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
h3. Authors
diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile
index ee3891c43b..41a96b487d 100644
--- a/railties/guides/source/generators.textile
+++ b/railties/guides/source/generators.textile
@@ -208,16 +208,16 @@ end
If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators.
-To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator:
+To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks:
<shell>
-$ rails generate generator my_helper
+$ rails generate generator rails/my_helper
</shell>
After that, we can delete both the +templates+ directory and the +source_root+ class method from our new generators, because we are not going to need them. So our new generator looks like the following:
<ruby>
-class MyHelperGenerator < Rails::Generators::NamedBase
+class Rails::MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
@@ -270,7 +270,7 @@ Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper doe
To do that, we can change the generator this way:
<ruby>
-class MyHelperGenerator < Rails::Generators::NamedBase
+class Rails::MyHelperGenerator < Rails::Generators::NamedBase
def create_helper_file
create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
module #{class_name}Helper
@@ -283,7 +283,7 @@ end
end
</ruby>
-Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +MyHelper::Generators::TestUnitGenerator+ and +TestUnit::Generators::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
+Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
<ruby>
# Search for :helper instead of :my_helper
@@ -371,16 +371,16 @@ h3. Application templates
Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template".
<ruby>
- gem("rspec-rails", :group => "test")
- gem("cucumber-rails", :group => "test")
+gem("rspec-rails", :group => "test")
+gem("cucumber-rails", :group => "test")
- if yes?("Would you like to install Devise?")
- gem("devise")
- generate("devise:install")
- model_name = ask("What would you like the user model to be called? [user]")
- model_name = "user" if model_name.blank?
- generate("devise", model_name)
- end
+if yes?("Would you like to install Devise?")
+ gem("devise")
+ generate("devise:install")
+ model_name = ask("What would you like the user model to be called? [user]")
+ model_name = "user" if model_name.blank?
+ generate("devise", model_name)
+end
</ruby>
In the above template we specify that the application relies on the +rspec-rails+ and +cucumber-rails+ gem so these two will be added to the +test+ group in the +Gemfile+. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the +Gemfile+ outside of any group and then runs the +devise:install+ generator. This template then takes the users input and runs the +devise+ generator, with the user's answer from the last question being passed to this generator.
@@ -388,7 +388,7 @@ In the above template we specify that the application relies on the +rspec-rails
Imagine that this template was in a file called +template.rb+. We can use it to modify the outcome of the +rails new+ command by using the +-m+ option and passing in the filename:
<shell>
- rails new thud -m template.rb
+$ rails new thud -m template.rb
</shell>
This command will generate the +Thud+ application, and then apply the template to the generated output.
@@ -396,14 +396,14 @@ This command will generate the +Thud+ application, and then apply the template t
Templates don't have to be stored on the local system, the +-m+ option also supports online templates:
<shell>
- rails new thud -m https://gist.github.com/722911
+$ rails new thud -m https://gist.github.com/722911.txt
</shell>
Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.
h3. Generator methods
-The following are methods available for both generators and templates for Rails.
+The following are methods available for both generators and templates for Rails.
NOTE: Methods provided by Thor are not covered this guide and can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html
@@ -428,8 +428,8 @@ h4. +gem+
Specifies a gem dependency of the application.
<ruby>
- gem("rspec", :group => "test", :version => "2.1.0")
- gem("devise", "1.1.5")
+gem("rspec", :group => "test", :version => "2.1.0")
+gem("devise", "1.1.5")
</ruby>
Available options are:
@@ -470,10 +470,9 @@ Adds a line to +config/application.rb+ directly after the application class defi
This method can also take a block:
<ruby>
- application do
- "config.asset_host = 'http://example.com'"
- end
- end
+application do
+ "config.asset_host = 'http://example.com'"
+end
</ruby>
Available options are:
@@ -481,9 +480,9 @@ Available options are:
* +:env+ - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows:
<ruby>
- application(nil, :env => "development") do
- "config.asset_host = 'http://localhost:3000'"
- end
+application(nil, :env => "development") do
+ "config.asset_host = 'http://localhost:3000'"
+end
</ruby>
h4. +git+
@@ -526,9 +525,9 @@ Places a file into +lib+ which contains the specified code.
This method also takes a block:
<ruby>
- lib("super_special.rb") do
- puts "Super special!"
- end
+lib("super_special.rb") do
+ puts "Super special!"
+end
</ruby>
h4. +rakefile+
@@ -542,13 +541,13 @@ Creates a Rake file in the +lib/tasks+ directory of the application.
This method also takes a block:
<ruby>
- rakefile("test.rake") do
- %Q{
- task :rock => :environment do
- puts "Rockin'"
- end
- }
- end
+rakefile("test.rake") do
+ %Q{
+ task :rock => :environment do
+ puts "Rockin'"
+ end
+ }
+end
</ruby>
h4. +initializer+
@@ -562,9 +561,9 @@ Creates an initializer in the +config/initializers+ directory of the application
This method also takes a block:
<ruby>
- initializer("begin.rb") do
- puts "Almost done!"
- end
+initializer("begin.rb") do
+ puts "Almost done!"
+end
</ruby>
h4. +generate+
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index 902b7353c0..6fb54bfd49 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -163,7 +163,7 @@ $ rails new blog
This will create a Rails application called Blog in a directory called blog.
-TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>.
+TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails new -h</tt>.
After you create the blog application, switch to its folder to continue work directly in that application:
@@ -184,7 +184,7 @@ In any case, Rails will create a folder in your working directory called <tt>blo
|doc/|In-depth documentation for your application.|
|lib/|Extended modules for your application (not covered in this guide).|
|log/|Application log files.|
-|public/|The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.|
+|public/|The only folder seen to the world as-is. This is where your images, JavaScript files, stylesheets (CSS), and other static files go.|
|script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
|test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html|
|tmp/|Temporary files|
@@ -195,7 +195,7 @@ h4. Installing the Required Gems
Rails applications manage gem dependencies with "Bundler":http://gembundler.com/v1.0/index.html by default. As we don't need any other gems beyond the ones in the generated +Gemfile+ we can directly run
<shell>
-# bundle install
+$ bundle install
</shell>
to have them ready.
@@ -227,7 +227,7 @@ NOTE: In this guide we are using an SQLite3 database for data storage, because i
h5. Configuring a MySQL Database
-If you choose to use MySQL instead of the shipped Sqlite3 database, your +config/database.yml+ will look a little different. Here's the development section:
+If you choose to use MySQL instead of the shipped SQLite3 database, your +config/database.yml+ will look a little different. Here's the development section:
<yaml>
development:
@@ -258,6 +258,8 @@ development:
Change the username and password in the +development+ section as appropriate.
+TIP: You don't have to update the database configurations manually. If you had a look at the options of application generator, you have seen that one of them is named <tt>--database</tt>. It lets you choose an adapter for couple of most used relational databases. You can even run the generator repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite.
+
h4. Creating the Database
Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command:
@@ -272,7 +274,7 @@ TIP: Rake is a general-purpose command-runner that Rails uses for many things. Y
h3. Hello, Rails!
-One of the traditional places to start with a new language is by getting some text up on screen quickly, to do this, you need to get your Rails application server running.
+One of the traditional places to start with a new language is by getting some text up on screen quickly. To do this, you need to get your Rails application server running.
h4. Starting up the Web Server
@@ -298,7 +300,7 @@ To get Rails saying "Hello", you need to create at minimum a controller and a vi
$ rails generate controller home index
</shell>
-TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: +ruby \path\to\rails controller home index+.
+TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: <tt>ruby \path\to\your\application\script\rails generate controller home index</tt>.
Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code:
@@ -347,7 +349,7 @@ In the case of the blog application, you can start by generating a scaffolded Po
$ rails generate scaffold Post name:string title:string content:text
</shell>
-NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
+NOTE. While scaffolding will get you up and running quickly, the code it generates is unlikely to be a perfect fit for your application. You'll most probably want to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. Rails, however, makes it really simple to customize templates for generated models, controllers, views and other source files. You'll find more information in the "Creating and Customizing Rails Generators & Templates":generators.html guide.
The scaffold generator will build 15 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
@@ -409,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl
== CreatePosts: migrated (0.0020s) ===========================================
</shell>
-NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file.
+NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitly pass it when invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
h4. Adding a Link
@@ -467,6 +469,8 @@ To see your validations in action, you can use the console. The console is a com
$ rails console
</shell>
+TIP: The default console will make changes to your database. You can instead open a console that will roll back any changes you make by using +rails console --sandbox+.
+
After the console loads, you can use it to work with your application's models:
<shell>
@@ -811,6 +815,8 @@ class CreateComments < ActiveRecord::Migration
t.timestamps
end
+
+ add_index :comments, :post_id
end
def self.down
@@ -819,7 +825,7 @@ class CreateComments < ActiveRecord::Migration
end
</ruby>
-The +t.references+ line sets up a foreign key column for the association between the two models. Go ahead and run the migration:
+The +t.references+ line sets up a foreign key column for the association between the two models. And the +add_index+ line sets up an index for this association column. Go ahead and run the migration:
<shell>
$ rake db:migrate
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 8a39bdf3c1..ac05e1c6c7 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -1,4 +1,4 @@
-h2. Rails Internationalization (I18n) API
+lh2. Rails Internationalization (I18n) API
The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application.
@@ -10,7 +10,7 @@ So, in the process of _internationalizing_ your Rails application you have to:
* Tell Rails where to find locale dictionaries
* Tell Rails how to set, preserve and switch locale
-In the process of _localizing_ your application you'll probably want to do following three things:
+In the process of _localizing_ your application you'll probably want to do the following three things:
* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc
* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc.
@@ -305,12 +305,12 @@ end
# app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
- flash[:notice] = "Hello flash!"
+ flash[:notice] = "Hello Flash"
end
end
# app/views/home/index.html.erb
-<h1>Hello world!</h1>
+<h1>Hello World</h1>
<p><%= flash[:notice] %></p>
</ruby>
@@ -344,8 +344,8 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo
<ruby>
# config/locales/en.yml
en:
- hello_world: Hello World
- hello_flash: Hello Flash
+ hello_world: Hello world!
+ hello_flash: Hello flash!
# config/locales/pirate.yml
pirate:
@@ -586,7 +586,7 @@ I18n.t :foo
I18n.l Time.now
</ruby>
-Explicitely passing a locale:
+Explicitly passing a locale:
<ruby>
I18n.t :foo, :locale => :de
@@ -623,7 +623,7 @@ pt:
bar: baz
</ruby>
-As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
+As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
Here is a "real" example from the Active Support +en.yml+ translations YAML file:
@@ -649,7 +649,7 @@ Generally we recommend using YAML as a format for storing translations. There ar
h4. Translations for Active Record Models
-You can use the methods +Model.human_name+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names.
+You can use the methods +Model.model_name.human+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names.
For example when you add the following translations:
@@ -664,7 +664,7 @@ en:
# will translate User attribute "login" as "Handle"
</ruby>
-Then +User.human_name+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle".
+Then +User.model_name.human+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle".
h5. Error Message Scopes
@@ -713,12 +713,12 @@ end
Then Active Record will look for messages in this order:
<ruby>
-activerecord.errors.models.admin.attributes.title.blank
+activerecord.errors.models.admin.attributes.name.blank
activerecord.errors.models.admin.blank
-activerecord.errors.models.user.attributes.title.blank
+activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
-errors.attributes.title.blank
+errors.attributes.name.blank
errors.messages.blank
</ruby>
@@ -780,15 +780,15 @@ h5. Action View Helper Methods
* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations.
-* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitely). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable.
+* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the "datetime.prompts":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable.
* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope.
h5. Active Record Methods
-* +human_name+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
+* +model_name.human+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":http://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
-* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +human_name+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
+* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +model_name.human+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":http://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +'&nbsp;'+).
@@ -809,6 +809,12 @@ That does not mean you're stuck with these limitations, though. The Ruby I18n ge
I18n.backend = Globalize::Backend::Static.new
</ruby>
+You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the ActiveRecord backend and fall back to the (default) Simple backend:
+
+<ruby>
+I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
+</ruby>
+
h4. Using Different Exception Handlers
The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
@@ -852,7 +858,7 @@ h3. Conclusion
At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
-If you find anything missing or wrong in this guide please file a ticket on "our issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions please sign up to our "mailinglist":http://groups.google.com/group/rails-i18n.
+If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n.
h3. Contributing to Rails I18n
@@ -867,10 +873,10 @@ If you find your own locale (language) missing from our "example translations da
h3. Resources
* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
-* "rails-i18n Google group":http://groups.google.com/group/rails-i18n - The project's mailing list.
+* "Google group: rails-i18n":http://groups.google.com/group/rails-i18n - The project's mailing list.
* "Github: rails-i18n":http://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
-* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
* "Github: i18n":http://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
+* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
* "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem.
@@ -879,7 +885,7 @@ h3. Authors
* "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author)
* "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k
-If you found this guide useful please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
+If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
h3. Footnotes
diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb
index 84fbc53a69..933bf66b3f 100644
--- a/railties/guides/source/index.html.erb
+++ b/railties/guides/source/index.html.erb
@@ -151,17 +151,17 @@ Ruby on Rails Guides
<% end %>
</dl>
-<h3>Contributing to Rails</h3>
+<h3>Contributing to Ruby on Rails</h3>
<dl>
- <%= guide("Contributing to Rails", 'contributing_to_rails.html') do %>
+ <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %>
<p>Rails is not &quot;somebody else's framework.&quot; This guide covers a variety of ways that you can get involved in the ongoing development of Rails.</p>
<% end %>
<%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %>
<p>This guide documents the Ruby on Rails API documentation guidelines.</p>
<% end %>
-
+
<%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %>
<p>This guide documents the Ruby on Rails guides guidelines.</p>
<% end %>
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index 4cc5f3843f..0cbbe1f389 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -1,2013 +1,425 @@
h2. The Rails Initialization Process
-This guide explains how the initialization process in Rails works as of Rails 3.
+This guide explains the internals of the initialization process in Rails works as of Rails 3.1. It is an extremely in-depth guide and recommended for advanced Rails developers.
* Using +rails server+
* Using Passenger
endprologue.
-This guide first describes the process of +rails server+ then explains the Passenger + Rack method, before delving into the common initialize pattern these two go through.
+This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail a long the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application.
+
+NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified.
h3. Launch!
As of Rails 3, +script/server+ has become +rails server+. This was done to centralize all rails related commands to one common file.
-The actual +rails+ command is kept in _railties/bin/rails_ and goes like this:
+h4. +bin/rails+
-<ruby>
- require 'rbconfig'
-
- module Rails
- module ScriptRailsLoader
- RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
- SCRIPT_RAILS = File.join('script', 'rails')
-
- def self.exec_script_rails!
- cwd = Dir.pwd
- exec RUBY, SCRIPT_RAILS, *ARGV if File.exists?(SCRIPT_RAILS)
- Dir.chdir("..") do
- # Recurse in a chdir block: if the search fails we want to be sure
- # the application is generated in the original working directory.
- exec_script_rails! unless cwd == Dir.pwd
- end
- rescue SystemCallError
- # could not chdir, no problem just return
- end
- end
- end
-
- Rails::ScriptRailsLoader.exec_script_rails!
-
- railties_path = File.expand_path('../../lib', __FILE__)
- $:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path)
-
- require 'rails/ruby_version_check'
- Signal.trap("INT") { puts; exit }
-
- require 'rails/commands/application'
-</ruby>
-
-The +Rails::ScriptRailsLoader+ module here defines two constants: +RUBY+ and +SCRIPT_RAILS+. +RUBY+ is the full path to your ruby executable, on a Snow Leopard system it's _/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby_. +SCRIPT_RAILS+ is simply _script/rails_. When +exec_script_rails+ is invoked, this will attempt to +exec+ the _rails_ file in the _script_ directory using the path to your Ruby executable, +RUBY+. If +exec+ is invoked, the program will stop at this point. If the _script/rails_ file doesn't exist in the current directory, Rails will recurse upwards until it finds it by calling +exec_script_rails+ from inside the +Dir.chdir("..")+. This is handy if you're currently in one of the sub-directories of the rails application and wish to launch a server or a console.
-
-If Rails cannot execute _script/rails_ then it will fall back to the standard +rails+ command task of generating an application.
-
-In +script/rails+ we see the following:
+The actual +rails+ command is kept in _bin/rails_ at the and goes like this:
<ruby>
#!/usr/bin/env ruby
- # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
-
- APP_PATH = File.expand_path('../../config/application', __FILE__)
- require File.expand_path('../../config/boot', __FILE__)
- require 'rails/commands'
-</ruby>
-
-This obviously defines a couple of constants to some pretty important files, _config/environment.rb_, _config/boot.rb_ and _config/application.rb_ all within the context of +__FILE__+ which is of course +script/rails+ in the root of your application. Then it goes on to +require BOOT_PATH+ which leads us onto _config/boot.rb_.
-h3. Passenger
-
-Before we dive into what _config/boot.rb_ encompasses, we'll just glimpse at what Passenger does enough to get an understanding of how it requires a Rails application.
-
-Passenger will require _config/environment.rb_ by way of its +PhusionPassenger::Railz::ApplicationSpawner#preload_application+ method. _config/environment.rb_ requires _config/application.rb_ which requires _config/boot.rb_. That's how the Rails boot process begins with Passenger in a nutshell.
-
-h3. _config/boot.rb_
-
-_config/boot.rb_ is the first stop for everything for initializing your application. This boot process does quite a bit of work for you and so this section attempts to go in-depth enough to explain what each of the pieces does.
-
-<ruby>
- require 'rubygems'
-
- # Set up gems listed in the Gemfile.
- gemfile = File.expand_path('../../Gemfile', __FILE__)
begin
- ENV['BUNDLE_GEMFILE'] = gemfile
- require 'bundler'
- Bundler.setup
- rescue Bundler::GemNotFound => e
- STDERR.puts e.message
- STDERR.puts "Try running `bundle install`."
- exit!
- end if File.exist?(gemfile)
-</ruby>
-
-h3. Bundled Rails (3.x)
-
-
-Rails 3 now uses Bundler and the README for the project explains it better than I could:
-
-> "Bundler is a tool that manages gem dependencies for your ruby application. It takes a gem manifest file and is able to fetch, download, and install the gems and all child dependencies specified in this manifest. It can manage any update to the gem manifest file and update the bundle's gems accordingly. It also lets you run any ruby code in context of the bundle's gem environment."
-
-Now with Rails 3 we have a Gemfile which defines the basics our application needs to get going:
-
-<ruby>
- source 'http://rubygems.org'
-
- gem 'rails', '3.0.0'
-
- # Bundle edge Rails instead:
- # gem 'rails', :git => 'git://github.com/rails/rails.git'
-
- gem 'sqlite3-ruby', :require => 'sqlite3'
-
- # Use unicorn as the web server
- # gem 'unicorn'
-
- # Deploy with Capistrano
- # gem 'capistrano'
-
- # Bundle the extra gems:
- # gem 'bj'
- # gem 'nokogiri'
- # gem 'sqlite3-ruby', :require => 'sqlite3'
- # gem 'aws-s3', :require => 'aws/s3'
-
- # Bundle gems for certain environments:
- # gem 'rspec', :group => :test
- # group :test do
- # gem 'webrat'
- # end
-
-</ruby>
-
-Here the only two gems we need are +rails+ and +sqlite3-ruby+, so it seems. This is until you run +bundle pack+. This command freezes all the gems required by your application into _vendor/cache_. The gems installed by default are:
-
-* abstract-1.0.0.gem
-* actionmailer-3.0.0.gem
-* actionpack-3.0.0.gem
-* activemodel-3.0.0.gem
-* activerecord-3.0.0.gem
-* activeresource-3.0.0.gem
-* activesupport-3.0.0.gem
-* arel-0.4.0.gem
-* builder-2.1.2.gem
-* bundler-1.0.3.gem
-* erubis-2.6.6.gem
-* i18n-0.4.1.gem
-* mail-2.2.5.gem
-* memcache-client-1.8.5.gem
-* mime-types-1.16.gem
-* nokogiri-1.4.3.1.gem
-* polyglot-0.3.1.gem
-* rack-1.2.1.gem
-* rack-mount-0.6.12.gem
-* rack-test-0.5.4.gem
-* rails-3.0.0.gem
-* railties-3.0.0.gem
-* rake-0.8.7.gem
-* sqlite3-ruby-1.3.1.gem
-* text-format-1.0.0.gem
-* text-hyphen-1.0.0.gem
-* thor-0.13.7.gem
-* treetop-1.4.8.gem
-* tzinfo-0.3.23.gem
-
-TODO: Prettify when it becomes more stable.
-
-I won't go into what each of these gems are, as that is really something that needs covering on a case-by-case basis. We will however just dig a little under the surface of Bundler.
-
-Back in _config/boot.rb_, we call +Bundler.setup+ which will load and parse the +Gemfile+ and add the _lib_ directory of the gems mentioned **and** their dependencies (**and** their dependencies' dependencies, and so on) to the +$LOAD_PATH+.
-
-h3. Requiring Rails
-
-After _config/boot.rb_ is loaded, there's this +require+:
-
-<ruby>
- require 'rails/commands'
-</ruby>
-
-In this file, _railties/lib/rails/commands.rb_, there is a case statement for +ARGV.shift+:
-
-<ruby>
- case ARGV.shift
- ...
- when 's', 'server'
- require 'rails/commands/server'
- # Initialize the server first, so environment options are set
- server = Rails::Server.new
- require APP_PATH
- ...
- end
-</ruby>
-
-We're running +rails server+ and this means it will make a require out to _rails/commands/server_ (_railties/lib/rails/commands/server.rb_). Firstly, this file makes a couple of requires of its own:
-
-<ruby>
- require 'fileutils'
- require 'optparse'
- require 'action_dispatch'
-</ruby>
-
-The first two are Ruby core and this guide does not cover what they do, but _action_dispatch_ (_actionpack/lib/action_dispatch.rb_) is important. This file firstly make a require to _active_support_ (_activesupport/lib/active_support.rb_) which defines the +ActiveSupport+ module.
-
-h4. +require 'active_support'+
-
-_activesupport/lib/active_support.rb_ sets up +module ActiveSupport+:
-
-<ruby>
- module ActiveSupport
- class << self
- attr_accessor :load_all_hooks
- def on_load_all(&hook) load_all_hooks << hook end
- def load_all!; load_all_hooks.each { |hook| hook.call } end
- end
- self.load_all_hooks = []
-
- on_load_all do
- [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom]
- end
- end
-</ruby>
-
-This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this).
-
-The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later.
-
-This file goes on to define some classes that will be automatically loaded using Ruby's +autoload+ method, but not before including Rails's own variant of the +autoload+ method from _active_support/dependencies/autoload.rb_:
-
-
-<ruby>
- require "active_support/inflector/methods"
- require "active_support/lazy_load_hooks"
-
- module ActiveSupport
- module Autoload
- def self.extended(base)
- base.extend(LazyLoadHooks)
- end
-
- @@autoloads = {}
- @@under_path = nil
- @@at_path = nil
- @@eager_autoload = false
-
- def autoload(const_name, path = @@at_path)
- full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
- location = path || Inflector.underscore(full)
-
- if @@eager_autoload
- @@autoloads[const_name] = location
- end
- super const_name, location
- end
-
- ...
- end
- end
-</ruby>
-
-h4. Lazy Hooks
-
-+ActiveSupport::LazyLoadHooks+ is responsible for defining methods used for running hooks that are defined during the initialization process, such as the one defined inside the +active_record.initialize_timezone+ initializer:
-
-<ruby>
- initializer "active_record.initialize_timezone" do
- ActiveSupport.on_load(:active_record) do
- self.time_zone_aware_attributes = true
- self.default_timezone = :utc
- end
- end
-</ruby>
-
-When the initializer runs it invokes method +on_load+ for +ActiveRecord+ and the block passed to it would be called only when +run_load_hooks+ is called.
-When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked. The very last line of +activerecord/lib/active_record/base.rb+ is:
-
-<ruby>
-ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-</ruby>
-
-h4. +require 'active_support'+ cont'd.
-
-This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_:
-
-<ruby>
- def eager_autoload
- old_eager, @@eager_autoload = @@eager_autoload, true
- yield
- ensure
- @@eager_autoload = old_eager
- end
-</ruby>
-
-As you can see for the duration of the +eager_autoload+ block the class variable +@@eager_autoload+ is set to +true+, which has the consequence of when +autoload+ is called that the location of the file for that specific +autoload+'d constant is added to the +@@autoloads+ hash initialized at the beginning of this module declaration. So now that you have part of the context, here's the other, the code from _activesupport/lib/active_support.rb_:
-
-<ruby>
- require "active_support/dependencies/autoload"
-
- module ActiveSupport
- extend ActiveSupport::Autoload
-
- autoload :DescendantsTracker
- autoload :FileUpdateChecker
- autoload :LogSubscriber
- autoload :Notifications
-
- # TODO: Narrow this list down
- eager_autoload do
- autoload :BacktraceCleaner
- autoload :Base64
- autoload :BasicObject
- autoload :Benchmarkable
- autoload :BufferedLogger
- autoload :Cache
- autoload :Callbacks
- autoload :Concern
- autoload :Configurable
- autoload :Deprecation
- autoload :Gzip
- autoload :Inflector
- autoload :JSON
- autoload :Memoizable
- autoload :MessageEncryptor
- autoload :MessageVerifier
- autoload :Multibyte
- autoload :OptionMerger
- autoload :OrderedHash
- autoload :OrderedOptions
- autoload :Rescuable
- autoload :SecureRandom
- autoload :StringInquirer
- autoload :XmlMini
- end
-
- autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
- autoload :TestCase
- end
-
- autoload :I18n, "active_support/i18n"
-</ruby>
-
-So we know the ones in +eager_autoload+ are eagerly loaded and it does this by storing them in an +@@autoloads+ hash object and then loading them via +eager_autoload!+ which is called via the +preload_frameworks+ initializer defined in _railties/lib/rails/application/bootstrap.rb_.
-
-The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references
-
-Note: What does it means to be autoloaded? An example of this would be calling the +ActiveSupport::TestCase+ class which hasn't yet been initialized. Because it's been specified as an +autoload+ Ruby will require the file that it's told to. The file it requires is not defined in the +autoload+ call here but, as you may have seen, in the +ActiveSupport::Autoload.autoload+ definition. So once that file has been required Ruby will try again and then if it still can't find it it will throw the all-too-familiar +uninitialized constant+ error.
-
-h4. +require 'action_dispatch'+
-
-Back in _actionpack/lib/action_dispatch.rb_, the next require after _active_support_ is to _active_support/dependencies/autoload_ but this file has already been loaded by _activesupport/lib/active_support.rb_ and so will not be loaded again. The next require is to Rack itself:
-
-<ruby>
- require 'rack'
-</ruby>
-
-As mentioned previously, Bundler has added the gems' _lib_ directories to the load path so this _rack_ file that is referenced lives in the Rack gem: _lib/rack.rb_. This loads Rack so we can use it later on when we define +Rails::Server+ to descend from +Rack::Server+.
-
-This file then goes on to define the +ActionDispatch+ module and it's related autoloads:
-
-<ruby>
- module Rack
- autoload :Test, 'rack/test'
- end
-
- module ActionDispatch
- extend ActiveSupport::Autoload
-
- autoload_under 'http' do
- autoload :Request
- autoload :Response
- end
-
- autoload_under 'middleware' do
- autoload :Callbacks
- autoload :Cascade
- autoload :Cookies
- autoload :Flash
- autoload :Head
- autoload :ParamsParser
- autoload :RemoteIp
- autoload :Rescue
- autoload :ShowExceptions
- autoload :Static
- end
-
- autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
- autoload :Routing
-
- module Http
- extend ActiveSupport::Autoload
-
- autoload :Cache
- autoload :Headers
- autoload :MimeNegotiation
- autoload :Parameters
- autoload :FilterParameters
- autoload :Upload
- autoload :UploadedFile, 'action_dispatch/http/upload'
- autoload :URL
- end
-
- module Session
- autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
- autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
- autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
- end
-
- autoload_under 'testing' do
- autoload :Assertions
- autoload :Integration
- autoload :PerformanceTest
- autoload :TestProcess
- autoload :TestRequest
- autoload :TestResponse
- end
- end
-
- autoload :Mime, 'action_dispatch/http/mime_type'
-</ruby>
-
-h4. +require "rails/commands/server"+
-
-Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class:
-
-<ruby>
- module Rails
- class Server < ::Rack::Server
-
- ...
-
- def initialize(*)
- super
- set_environment
- end
-
- ...
-
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
- end
- ...
- end
- end
-</ruby>
-
-h4. +require "rails/commands"+
-
-Back in _rails/commands_ Rails calls +Rails::Server.new+ which calls the +initialize+ method on the +Rails::Server+ class, which calls +super+, meaning it's actually calling +Rack::Server#initialize+, with it being defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-The +options+ method like this:
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-The +parse_options+ method like this:
-
-<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+ like this:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Here it is important to note that the default environment is _development_. After +Rack::Server#initialize+ has done its thing it returns to +Rails::Server#initialize+ which calls +set_environment+:
-
-<ruby>
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
+ require "rails/cli"
+ rescue LoadError
+ railties_path = File.expand_path('../../railties/lib', __FILE__)
+ $:.unshift(railties_path)
+ require "rails/cli"
end
</ruby>
-From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified.
-
-Finally, after +Rails::Server.new+ has executed, there is one more require:
-
-<ruby>
- require APP_PATH
-</ruby>
-
-+APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next.
-
-h4. +require APP_PATH+
-
-This file is _config/application.rb_ in your application and makes two requires to begin with:
-
-<ruby>
- require File.expand_path('../boot', __FILE__)
- require 'rails/all'
-</ruby>
-
-The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again.
-
-If you generate the application with the +-O+ option this will put a couple of pick-and-choose requirements at the top of your _config/application.rb_ instead:
+This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again.
-<ruby>
- # Pick the frameworks you want:
- # require "active_record/railtie"
- require "action_controller/railtie"
- require "action_mailer/railtie"
- require "active_resource/railtie"
- require "rails/test_unit/railtie"
-</ruby>
+h4. +railites/lib/rails/cli.rb+
-For the purposes of this guide, will will assume only:
+This file looks like this:
<ruby>
- require 'rails/all'
-</ruby>
-
-h4. +require "rails/all"+
-
-Now we'll dive into the internals of the pre-initialization stage of Rails. The file that is being required is _railties/lib/rails/all.rb_. The first line in this file is:
-
-<ruby>
- require 'rails'
-</ruby>
-
-h4. +require 'rails'+
-
-This file (_railties/lib/rails.rb_) requires the very, very basics that Rails needs to get going. I'm not going to delve into these areas yet, just cover them briefly for now. Later on we will go through the ones that are important to the boot procedure.
-
-<ruby>
- require 'pathname'
+ require 'rbconfig'
+ require 'rails/script_rails_loader'
- require 'active_support'
- require 'active_support/core_ext/kernel/reporting'
- require 'active_support/core_ext/logger'
+ # If we are inside a Rails application this method performs an exec and thus
+ # the rest of this script is not run.
+ Rails::ScriptRailsLoader.exec_script_rails!
- require 'rails/application'
- require 'rails/version'
- require 'rails/deprecation'
- require 'rails/log_subscriber'
require 'rails/ruby_version_check'
+ Signal.trap("INT") { puts; exit }
- require 'active_support/railtie'
- require 'action_dispatch/railtie'
-</ruby>
-
-+require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+. Although is coming to use this path name to generate paths as below:
-
-<ruby>
- Rails.root.join("app/controllers")
-</ruby>
-
-Pathname can also be converted to string, so the following syntax is preferred:
-
-<ruby>
- "#{Rails.root}/app/controllers"
-</ruby>
-
-
-This works because Ruby automatically handles file path conversions. Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out.
-
-Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+.
-
-The first require:
-
-<ruby>
- require 'active_support'
-</ruby>
-
-Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_.
-
-
-h4. +require 'active_support/core_ext/kernel/reporting'+
-
-This file extends the +Kernel+ module, providing the methods +silence_warnings+, +enable_warnings+, +with_warnings+, +silence_stderr+, +silence_stream+ and +suppress+. The API documentation on these overridden methods is fairly good and if you wish to know more "have a read.":http://api.rubyonrails.org/classes/Kernel.html
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'active_support/core_ext/logger'+
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'rails/application'+
-
-Here's where +Rails::Application+ is defined. This is the superclass of +YourApp::Application+ from _config/application.rb_ and the subclass of +Rails::Engine+ This is the main entry-point into the Rails initialization process as when your application is initialized, your class is the basis of its configuration.
-
-This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_.
-
-
-h4. +require 'rails/railties_path'+
-
-This file serves one purpose:
-
-<ruby>
- RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
-</ruby>
-
-Helpful, hey? One must wonder why they just didn't define it outright.
-
-
-h4. +require 'rails/plugin'+
-
-Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section.
-
-This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+.
-
-This defines the first few initializers for the Rails stack:
-
-* load_init_rb
-* sanity_check_railties_collisons
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-TODO: Expand.
-
-h4. +require 'rails/engine'+
-
-This file requires _rails/railtie.rb_ which defines +Rails::Railtie+.
-
-+Rails::Engine+ defines a couple of further initializers for your application:
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-* add_routing_namespaces
-* add_locales
-* add_view_paths
-* add_generator_templates
-* load_application_initializers
-* load_application_classes
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-
-Also in here we see that a couple of methods are +delegate+'d:
-
-<ruby>
- delegate :middleware, :paths, :root, :to => :config
-</ruby>
-
-This means when you call either the +middleware+, +paths+ or +root+ methods you are in reality calling +config.middleware+, +config.paths+ and +config.root+ respectively.
-
-+Rails::Engine+ descends from +Rails::Railtie+.
-
-h4. +require 'rails/railtie'+
-
-+Rails::Railtie+ (_pronounced Rail-tie, as in a bowtie_), provides a method of classes to hook into Rails, providing them with methods to add generators, rake tasks and subscribers. All of the facets of Rails are their own Railtie. and as you've probably already figured out, the engines that you use are railties too. Plugins also can be railties, but they do not have to be.
-
-Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_.
-
-h4. +require 'rails/initializable'+
-
-The +Rails::Initializable+ module includes methods helpful for the initialization process in rails, such as the method to define initializers: +initializer+. This is included into +Rails::Railtie+ so it's available there as well as +Rails::Engine+, +Rails::Application+ and +YourApp::Application+. In here we also see the class definition for +Rails::Initializer+, the class for all initializer objects.
-
-h4. +require 'rails/configuration'+
-
-The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike.
-
-At the top of this file there are three +require+s:
-
-<ruby>
- require 'active_support/ordered_options'
- require 'rails/paths'
- require 'rails/rack'
-</ruby>
-
-h4. +require 'active_support/ordered_options'+
-
-+ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application.
-
-TODO: expand.
-
-h4. +require 'rails/paths'+
-
-This file is used to set up the +Rails::Paths+ module which is used to set up helpers for referencing paths to the folders of your Rails application, such as in _railties/lib/rails/engine/configuration.rb_ where it is used to firstly define them:
-
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.mailers "app/mailers", :eager_load => true
- paths.app.views "app/views", :eager_load => true
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths.public "public"
- paths.public.javascripts "public/javascripts"
- paths.public.stylesheets "public/stylesheets"
- paths
- end
- end
-</ruby>
-
-You can then get to these helper methods by calling +YourApp::Application.config.paths+.
-
-h4. +require 'rails/rack'+
-
-This file sets up some +autoload+'d constants for +Rails::Rack+:
-
-<ruby>
- module Rails
- module Rack
- autoload :Debugger, "rails/rack/debugger"
- autoload :Logger, "rails/rack/logger"
- autoload :LogTailer, "rails/rack/log_tailer"
- autoload :Static, "rails/rack/static"
- end
- end
-</ruby>
-
-h4. +require 'rails/version'+
-
-Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is:
-
-<ruby>
- require 'rails/version'
-</ruby>
-
-The code in this file declares +Rails::VERSION+ so that the version number can easily be accessed. It stores it in constants, with the final version number being attainable by calling +Rails::VERSION::STRING+.
-
-h4. +require 'rails/deprecation'+
-
-This sets up a couple of familiar constants: +RAILS_ENV+, +RAILS_ROOT+ and +RAILS_DEFAULT_LOGGER+ to still be usable, but raise a deprecation warning when they are. Their alternatives are now +Rails.env+, +Rails.root+ and +Rails.logger+ respectively.
-
-If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section.
-
-h4. +require 'rails/log_subscriber'+
-
-The +Rails::LogSubscriber+ provides a central location for logging in Rails 3 so as to not slow down the main thread. When you call one of the logging methods (+info+, +debug+, +warn+, +error+, +fatal+ or +unknown+) from the +Rails::LogSubscriber+ class or one of its subclasses this will notify the Rails logger to log this call in the fashion you specify, but will not write it to the file. The file writing is done at the end of the request, courtesy of the +Rails::Rack::Logger+ middleware.
-
-Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks.
-
-h4. +require 'rails/ruby_version_check'+
-
-This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you:
-
-<pre>
- Rails requires Ruby version 1.8.7 or later.
- You're running [your Ruby version here]; please upgrade to continue.
-</pre>
-
-h4. +require 'activesupport/railtie'+
-
-This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined:
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-* i18n.initialize
-
-This Railtie also defines an an +after_initialize+ block, which will (as the name implies) be ran after the initialization process. More on this later. TODO: When you write the section you can link to it.
-
-h4. +require 'action_dispatch/railtie'+
-
-This file is explained in the ActionDispatch Railtie Section. TODO: link
-
-h4. Return to _rails/all.rb_
-
-Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder:
-
-<ruby>
- %w(
- active_record
- action_controller
- action_mailer
- active_resource
- rails/test_unit
- ).each do |framework|
- begin
- require "#{framework}/railtie"
- rescue LoadError
- end
+ if ARGV.first == 'plugin'
+ ARGV.shift
+ require 'rails/commands/plugin_new'
+ else
+ require 'rails/commands/application'
end
</ruby>
-As you may be able to tell from the code, this is going through and loading all the Railties for Active Record, Action Controller, Action Mailer, Active Resource. Two other Railties, one for Active Support and one for Action Dispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link.
-
-h4. ActiveSupport Railtie
-
-From Active Support's README:
-
-Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails.
-
-TODO: Quotify.
-
-h5. +require 'active_support/railtie'+
-
-
-h4. Active Record Railtie
-
-The Active Record Railtie takes care of hooking Active Record into Rails. This depends on Active Support, Active Model and Arel. From Active Record's readme:
-
-TODO: Quotify.
-
-<plain>
- Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler:
-
- "An object that wraps a row in a database table or view, encapsulates
- the database access, and adds domain logic on that data."
-
- Active Record's main contribution to the pattern is to relieve the original of two stunting problems:
- lack of associations and inheritance. By adding a simple domain language-like set of macros to describe
- the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the
- gap of functionality between the data mapper and active record approach.
-</plain>
-
-h5. +require "active_record/railtie"+
-
-The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for Active Record.
-
-This file first requires Active Record, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the Active Model Railtie:
-
-<ruby>
- require "active_record"
- require "rails"
- require "active_model/railtie"
-</ruby>
-
-Active Model's Railtie is covered in the next section. TODO: Section.
-
-h5. +require "active_record"+
-
-TODO: Why are +activesupport_path+ and +activemodel_path+ defined here?
-
-The first three requires require ActiveSupport, Active Model and Arel in that order:
+The +rbconfig+ file here is out of Ruby's standard library and provides us with the +RbConfig+ class which contains useful information dependent on how Ruby was compiled. We'll see this in use in +railties/lib/rails/script_rails_loader+.
<ruby>
- require 'active_support'
- require 'active_model'
- require 'arel'
-</ruby>
-
-
-h5. +require "active_support"+
-
-This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when Active Record is loaded outside the scope of Rails.
-
-h5. +require "active_model"+
-
-TODO: Again with the +activesupport_path+!
-
-Here we see another +require "active_support"+ this is again, a safeguard for when Active Model is loaded outside the scope of Rails.
-
-This file defines a few +autoload+'d modules for Active Model, requires +active_support/i18n+ and adds the default translation file for Active Model to +I18n.load_path+.
-
-The +require 'active_support/i18n'+ just loads I18n and adds Active Support's default translations file to +I18n.load_path+ too:
-
-<ruby>
- require 'i18n'
- I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml
-</ruby>
-
-
-h5. +require "arel"+
-
-This file in _arel/lib/arel.rb_ loads a couple of Active Support things first:
-
-<ruby>
- require 'active_support/inflector'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-These files are explained in the "Common Includes" section.
-
-h5. +require 'arel'+
-
-Back in _arel/lib/arel.rb_, the next two lines require Active Record parts:
-
-<ruby>
- require 'active_record'
- require 'active_record/connection_adapters/abstract/quoting'
-</ruby>
-
-Because we're currently loading _active_record.rb_, it skips right over it.
-
-h5. +require 'active_record/connection_adapters/abstract/quoting'+
-
-_activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in Active Record.
-
-TODO: Explain why this is loaded especially.
-
-h5. +require 'active_record'+
-
-Back the initial require from the _railtie.rb_.
-
-The _active_support_ and _active_model_ requires are again just an insurance for if we're loading Active Record outside of the scope of Rails. In _active_record.rb_ the ActiveRecord +Module+ is initialized and in it there is defined a couple of +autoloads+ and +eager_autoloads+.
-
-There's a new method here called +autoload_under+ which is defined in +ActiveSupport::Autoload+. This sets the autoload path to temporarily be the specified path, in this case +relation+ for the +autoload+'d classes inside the block.
-
-Inside this file the +AttributeMethods+, +Locking+ and +ConnectionAdapter+ modules are defined inside the +ActiveRecord+ module. The second to last line tells Arel what SQL engine we want to use. In this case it's +ActiveRecord::Base+. The final line adds in the translations for Active Record which are only for if a record is invalid or non-unique.
-
-h5. +require 'rails'+
-
-As mentioned previously this is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-h5. +require 'active_model/railtie'+
-
-This is covered in the Active Model Railtie section. TODO: link there.
-
-h5. +require 'action_controller/railtie'+
-
-This is covered in the Action Controller Railtie section. TODO: link there.
-
-h5. The Active Record Railtie
-
-Inside the Active Record Railtie the +ActiveRecord::Railtie+ class is defined:
-
-<ruby>
- module ActiveRecord
- class Railtie < Rails::Railtie
+require 'pathname'
+module Rails
+ module ScriptRailsLoader
+ RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
+ SCRIPT_RAILS = File.join('script', 'rails')
...
- end
- end
-</ruby>
-
-TODO: Explain the logger.
-
-By doing this the +ActiveRecord::Railtie+ class gains access to the methods contained within +Rails::Railtie+ such as +rake_tasks+, +log_subscriber+ and +initiailizer+, all of which the Railtie is using in this case. The initializers defined here are:
-
-* active_record.initialize_timezone
-* active_record.logger
-* active_record.set_configs
-* active_record.initialize_database
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-As with the engine initializers, these are explained later.
-
-
-h4. Active Model Railtie
-
-This Railtie is +require+'d by Active Record's Railtie.
-
-From the Active Model readme:
-
-<plain>
- Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have an object interact with Action Pack helpers, it was required to either copy chunks of code from Rails, or monkey patch entire helpers to make them handle objects that did not look like Active Record. This generated code duplication and fragile applications that broke on upgrades.
-
- Active Model is a solution for this problem.
-
- Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers.
-</plain>
-
-
-h5. +require "active_model/railtie"+
-
-This Railtie file, _activemodel/lib/active_model/railtie.rb_ is quite small and only requires in +active_model+. As mentioned previously, the require to _rails_ is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-<ruby>
- require "active_model"
- require "rails"
-</ruby>
-
-h5. +require "active_model"+
-
-Active Model depends on Active Support and ensures it is required by making a +require 'active_support'+ call. It has already been loaded from _railties/lib/rails.rb_ so will not be reloaded for us here. The file goes on to define the +ActiveModel+ module and all of its autoloaded classes. This file also defines the english translations for some of the validation messages provided by Active Model, such as "is not included in the list" and "is reserved".
-
-h4. Action Controller Railtie
-
-The Action Controller Railtie takes care of all the behind-the-scenes code for your controllers; it puts the C into MVC; and does so by implementing the +ActionController::Base+ class which you may recall is where your +ApplicationController+ class descends from.
-
-h5. +require 'action_controller/railtie'+
-
-This first makes a couple of requires:
-
-<ruby>
- require "action_controller"
- require "rails"
- require "action_view/railtie"
-</ruby>
-
-The _action_controller_ file is explained in the very next section. The require to _rails_ is requiring the already-required _railties/lib/rails.rb_. If you wish to know about the require to _action_view/railtie_ this is explained in the Action View Railtie section.
-
-h5. +require 'action_controller+
-
-This file, _actionpack/lib/action_controller.rb_, defines the Action Controller module and its relative autoloads. Before it does any of that it makes two requires: one to _abstract_controller_, explored next, and the other to _action_dispatch_, explored directly after that.
-
-h5. +require 'abstract_controller'+
-
-+AbstractController+ provides the functionality of TODO.
-
-This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to Active Support to the load path, which it would succeed in if it wasn't already set by anything loaded before it. In this case, it's not going to be set due to Arel already loading it in (TODO: right?).
-
-The next thing in this file four +require+ calls:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/dependencies/autoload'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
-</ruby>
-
-After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes.
-
-
-h5. +require 'active_support/ruby/shim'+
-
-This file is explained in the "Common Includes" section beneath.
-
-h5. +require 'active_support/dependencies/autoload+
-
-This file was loaded upon the first require of +active_support+ and is not included. If you wish to be refreshed on what this file performs visit TODO: link to section.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Common Includes" section as it is required again later on. See the TODO: section. I also think this may be explained in the Active Support Core Extensions guide.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section as it has already been required by Arel at this point in the initialization process (see: section TODO: LINK!).
-
-h5. +require 'action_controller'+
-
-Back to _actionpack/lib/action_controller.rb_.
-
-After the initial call to +require 'abstract_controller'+, this calls +require 'action_dispatch'+ which was required earlier by _railties/lib/rails.rb_. The purpose of this file is explained in the ActionDispatch Railtie section.
-
-This file defines the +ActionController+ module and its autoloaded classes.
-
-Here we have a new method called +autoload_under+. This was covered in the Active Record Railtie but it is covered here also just in case you missed or skimmed over it. The +autoload_under+ method is defined in +ActiveSupport::Autoload+ and it sets the autoload path to temporarily be the specified path, in this case by specifying _metal_ it will load the specified +autoload+'d classes from _lib/action_controller/metal_ inside the block.
-
-Another new method we have here is called +autoload_at+:
-
-<ruby>
- autoload_at "action_controller/metal/exceptions" do
- autoload :ActionControllerError
- autoload :RenderError
- autoload :RoutingError
- autoload :MethodNotAllowed
- autoload :NotImplemented
- autoload :UnknownController
- autoload :MissingFile
- autoload :RenderError
- autoload :SessionOverflowError
- autoload :UnknownHttpMethod
- end
-</ruby>
-
-This defines the path of which to find these classes defined at and is most useful for if you have multiple classes defined in a single file, as is the case for this block; all of those classes are defined inside _action_controller/metal/exceptions.rb_ and when Active Support goes looking for them it will look in that file.
-
-At the end of this file there are a couple more requires:
-
-<ruby>
- # All of these simply register additional autoloads
- require 'action_view'
- require 'action_controller/vendor/html-scanner'
-
- # Common Active Support usage in ActionController
- 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/inflector'
-</ruby>
-
-h5. +require 'action_view'+
-
-This is best covered in the Action View Railtie section, so skip there by TODO: Link / page?
-
-h5. +require 'action_controller/vendor/html-scanner'+
-
-TODO: What is the purpose of this? Find out.
-
-h5. +require 'active_support/concern'+
-
-TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however.
-
-h5. +require 'active_support/core_ext/class/attribute_accessors'+
-
-This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+.
-
-h5. +require 'active_support/core_ext/load_error'+
-
-The Active Support Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Core Extension" guide.
-
-This file was required through the earlier _abstract_controller.rb_ require.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section.
-
-This file was required earlier by Arel and so is not required again.
-
-h5. +require 'active_support/core_ext/name_error'+
-
-This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the Active Support Core Extensions guide.
-
-h5. +require 'active_support/inflector'+
-
-This file is explained in the "Common Includes" section.
-
-This file was earlier required by Arel and so is not required again.
-
-h5. Action Controller Railtie
-
-So now we come back to the Action Controller Railtie with a couple more requires to go before +ActionController::Railtie+ is defined:
-
-<ruby>
- require "action_view/railtie"
- require "active_support/core_ext/class/subclasses"
- require "active_support/deprecation/proxy_wrappers"
- require "active_support/deprecation"
-</ruby>
-
-As explained previously the +action_view/railtie+ file will be explained in the Action View Railtie section. TODO: link to it.
-
-h5. +require 'active_support/core_ext/class/subclasses'+
-
-For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the Active Support Core Extension guide.
-
-h5. +require 'active_support/deprecation/proxy_wrappers'+
-
-This file, _activesupport/lib/active_support/deprecation/proxy_wrappers.rb_, defines a couple of deprecation classes, which are +DeprecationProxy+, +DeprecationObjectProxy+, +DeprecationInstanceVariableProxy+, +DeprecationConstantProxy+ which are all namespaced into +ActiveSupport::Deprecation+. These last three are all subclasses of +DeprecationProxy+.
-
-Why do we mention them here? Beside the obvious-by-now fact that we're covering just about everything about the initialization process in this guide, if you're deprecating something in your library and you use Active Support, you too can use the +DeprecationProxy+ class (and it's subclasses) too.
-
-
-h6. +DeprecationProxy+
-
-This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way:
-
-<ruby>
- RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.root
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack)
- self.warned = true
- end
- end
- end).new
-</ruby>
-
-There is similar definitions for the other constants of +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+. All three of these constants are in the midst of being deprecated (most likely in Rails 3.1) so Rails will tell you if you reference them that they're deprecated using the +DeprecationProxy+ class. Whenever you call +RAILS_ROOT+ this will raise a warning, telling you: "RAILS_ROOT is deprecated! Use Rails.root instead".... TODO: investigate if simply calling it does raise this warning. This same rule applies to +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+, their new alternatives are +Rails.env+ and +Rails.logger+ respectively.
-
-h6. +DeprecatedObjectProxy+
-
-This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section:
-
-<ruby>
- ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
-</ruby>
-
-This makes more sense in the wider scope of the initializer:
-
-<ruby>
- initializer "action_controller.url_helpers" do |app|
- ActionController.base_hook do
- extend ::ActionController::Railtie::UrlHelpers.with(app.routes)
- end
-
- message = "ActionController::Routing::Routes is deprecated. " \
- "Instead, use Rails.application.routes"
- proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
- ActionController::Routing::Routes = proxy
end
+end
</ruby>
-+ActionController::Routing::Routes+ was the previous constant used in defining routes in Rails 2 applications, now it's simply a method on +Rails.application+ rather than it's own individual class: +Rails.application.routes+. Both of these still call the +draw+ method on the returned object to end up defining the routes.
-
-
-h6. +DeprecatedInstanceVariableProxy+
-
-This isn't actually used anywhere in Rails anymore. It was used previously for when +@request+ and +@params+ were deprecated in Rails 2. It has been kept around as it could be useful for the same purposes in libraries that use Active Support.
-
-h6. +DeprecatedConstantProxy+
+The +rails/script_rails_loader+ file uses +RbConfig::Config+ to gather up the +bin_dir+ and +ruby_install_name+ values for the configuration which will result in a path such as +/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby+, which is the default path on Mac OS X. If you're running Windows the path may be something such as +C:/Ruby192/bin/ruby+. Anyway, the path on your system may be different, but the point of this is that it will point at the known ruby executable location for your install. The +RbConfig::CONFIG["EXEEXT"]+ will suffix this path with ".exe" if the script is running on Windows. This constant is used later on in +exec_script_rails!+. As for the +SCRIPT_RAILS+ console, we'll see that when we get to the +in_rails_application?+ method.
-This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_.
-
-In _encoding.rb_ it's used to define a constant that's now been deprecated:
+Back in +rails/cli+, the next line is this:
<ruby>
- CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError)
-</ruby>
-
-
-Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning:
-
-<plain>
- ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead.
-</plain>
-
-h5. +require "active_support/deprecation"+
-
-This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires:
-
-<ruby>
- require 'active_support/deprecation/behaviors'
- require 'active_support/deprecation/reporting'
- require 'active_support/deprecation/method_wrappers'
- require 'active_support/deprecation/proxy_wrappers'
+ Rails::ScriptRailsLoader.exec_script_rails!
</ruby>
-The remainder of this file goes about setting up the +silenced+ and +debug+ accessors:
+This method is defined in +rails/script_rails_loader+ like this:
<ruby>
- module ActiveSupport
- module Deprecation #:nodoc:
- class << self
- # The version the deprecated behavior will be removed, by default.
- attr_accessor :deprecation_horizon
- end
- self.deprecation_horizon = '3.0'
-
- # By default, warnings are not silenced and debugging is off.
- self.silenced = false
- self.debug = false
+ def self.exec_script_rails!
+ cwd = Dir.pwd
+ return unless in_rails_application? || in_rails_application_subdirectory?
+ exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application?
+ Dir.chdir("..") do
+ # Recurse in a chdir block: if the search fails we want to be sure
+ # the application is generated in the original working directory.
+ exec_script_rails! unless cwd == Dir.pwd
end
+ rescue SystemCallError
+ # could not chdir, no problem just return
end
</ruby>
-h5. +require "active_support/deprecation/behaviors"+
-
-This sets up some default behavior for the warnings raised by +ActiveSupport::Deprecation+, defining different ones for _development_ and _test_ and nothing for production, as we never want deprecation warnings in production:
+This method will first check if the current working directory (+cwd+) is a Rails application or is a subdirectory of one. The way to determine this is defined in the +in_rails_application?+ method like this:
<ruby>
- # Default warning behaviors per Rails.env. Ignored in production.
- DEFAULT_BEHAVIORS = {
- 'test' => Proc.new { |message, callstack|
- $stderr.puts(message)
- $stderr.puts callstack.join("\n ") if debug
- },
- 'development' => Proc.new { |message, callstack|
- logger =
- if defined?(Rails) && Rails.logger
- Rails.logger
- else
- require 'logger'
- Logger.new($stderr)
- end
- logger.warn message
- logger.debug callstack.join("\n ") if debug
- }
- }
-</ruby>
-
-In the _test_ environment, we will see the deprecation errors displayed in +$stderr+ and in _development_ mode, these are sent to +Rails.logger+ if it exists, otherwise it is output to +$stderr+ in a very similar fashion to the _test_ environment. These are both defined as procs, so Active Support can pass arguments to the +call+ method we call on it when Active Support +warn+.
-
-h5. +require 'active_support/deprecation/reporting'+
-
-This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from Active Support's +DeprecationProxy+ class and an +attr_accessor+ on the class called +silenced+. This checks that we have a behavior defined, which we do in the _test_ and _development_ environments, and that we're not +silenced+ before warning about deprecations by +call+'ing the +Proc+ time.
-
-This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors:
-
-<ruby>
- ActiveSupport::Deprecation.silence do
- puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}"
+ def self.in_rails_application?
+ File.exists?(SCRIPT_RAILS)
end
</ruby>
-TODO: may have to correct this example.
-
-h5. +require 'active_support/deprecation/method_wrappers'+
-
-This file defines a class method on +ActiveSupport::Deprecation+ called +deprecate_methods+. This method is used in _activesupport/lib/active_support/core_ext/module/deprecation.rb_ to allow you to declare deprecated methods on modules:
+The +SCRIPT_RAILS+ constant defined earlier is used here, with +File.exists?+ checking for its presence in the current directory. If this method returns +false+, then +in_rails_application_subdirectory?+ will be used:
<ruby>
- class Module
- # Declare that a method has been deprecated.
- # deprecate :foo
- # deprecate :bar => 'message'
- # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!'
- def deprecate(*method_names)
- ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
- end
+ def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
+ File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent)
end
</ruby>
-h5. +require 'action_controller/railtie'+
-
-Inside +ActionController::Railtie+ there are another two requires:
+This climbs the directory tree until it reaches a path which contains a +script/rails+ file. If a directory is reached which contains this file then this line will run:
<ruby>
- require "action_controller/railties/log_subscriber"
- require "action_controller/railties/url_helpers"
+ exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application?
</ruby>
+This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server".
-h5. +require 'action_controller/railties/log_subscriber'+
-
-+ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending.
-
-h5. +require 'action_controller/railties/url_helpers'+
-
-This file defines a +with+ method on +ActionController::Railtie::UrlHelpers+ which is later used in the +action_controller.url_helpers+ initializer. For more information see the +action_controller.url_helpers+ initializer section.
+h4. +script/rails+
-h5. Action Controller Railtie
-
-After these requires it deprecates a couple of ex-Action Controller methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+.
-
-After the deprecations, Rails defines the +log_subscriber+ to be a new instance of +ActionController::Railties::LogSubscriber+ and then go about defining the following initializers, keeping in mind that these are added to the list of initializers defined before hand:
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-* action_controller.url_helpers
-
-h4. Action View Railtie
-
-The Action View Railtie provides the backend code for your views and it puts the C into MVC. This implements the +ActionView::Base+ of which all views and partials are objects of.
-
-h5. +require 'action_view/railtie'+
-
-The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+.
-
-h5. +require 'action_view'+
-
-Here again we have the addition of the path to Active Support to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires:
+This file looks like this:
<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-And these have already been required. If you wish to know what these files do go to the explanation of each in the "Common Includes" section. TODO: link to them!
-
-This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped):
-
-<ruby>
- require 'action_pack/version'
-</ruby>
-
-the _version_ file contains this code (comments stripped):
-
-<ruby>
- module ActionPack #:nodoc:
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 1
- TINY = 0
- BUILD = "beta"
-
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
- end
- end
-</ruby>
-
-TODO: Why?!
-
-This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires:
-
-<ruby>
- require 'active_support/core_ext/string/output_safety'
- require 'action_view/base'
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
+ require File.expand_path('../../config/boot', __FILE__)
+ require 'rails/commands'
</ruby>
-h5. +require 'active_support/core_ext/string/output_safety'+
+The +APP_PATH+ constant here will be used later in +rails/commands+. The +config/boot+ file that +script/rails+ references is the +config/boot.rb+ file in our application which is responsible for loading Bundler and setting it up.
-The _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ file is responsible for the code used in escaping HTML and JSON, namely the +html_escape+ and +json_escape+ methods. It does this by overriding these methods in +Erb::Util+ which is later included into +ActionView::Base+. This also defines +ActiveSupport::SafeBuffer+ which descends from +String+ and is used for concatenating safe output from your views to ERB templates.
+h4. +config/boot.rb+
-h5. +require 'action_view/base'+
-
-This file initially makes requires to the following files:
++config/boot.rb+ contains this:
<ruby>
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute'
-</ruby>
-
-These are explained in their relevant areas inside the "Common Includes" section.
-
-The remainder of this file sets up the +ActionView+ module and the +ActionView::Base+ class which is the class of all view templates. Inside of +ActionView::Base+ it makes an include to several helper modules:
+ require 'rubygems'
-<ruby>
- include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
+ # Set up gems listed in the Gemfile.
+ gemfile = File.expand_path('../../Gemfile', __FILE__)
+ begin
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+ rescue Bundler::GemNotFound => e
+ STDERR.puts e.message
+ STDERR.puts "Try running `bundle install`."
+ exit!
+ end if File.exist?(gemfile)
</ruby>
-h5. +ActionView::Helpers+
-
-This module, from _actionpack/lib/action_view/helpers.rb_, initially sets up the +autoload+'s for the various +ActionView::Helpers+ modules (TODO: mysteriously not using +autoload_under+). This also sets up a +ClassMethods+ module which is included automatically into wherever +ActionView::Helpers+ is included by defining a +self.included+ method:
-
-<ruby>
- def self.included(base)
- base.extend(ClassMethods)
- end
+In a standard Rails application, there's a +Gemfile+ which declares all dependencies of the application. +config/boot.rb+ sets +ENV["BUNDLE_GEMFILE"]+ to the location of this file, then requires Bundler and calls +Bundler.setup+ which adds the dependencies of the application (including all the Rails parts) to the load path, making them available for the application to load. The gems that a Rails 3.1 application depends on are as follows:
+
+* abstract (1.0.0)
+* actionmailer (3.1.0.beta)
+* actionpack (3.1.0.beta)
+* activemodel (3.1.0.beta)
+* activerecord (3.1.0.beta)
+* activeresource (3.1.0.beta)
+* activesupport (3.1.0.beta)
+* arel (2.0.7)
+* builder (3.0.0)
+* bundler (1.0.6)
+* erubis (2.6.6)
+* i18n (0.5.0)
+* mail (2.2.12)
+* mime-types (1.16)
+* polyglot (0.3.1)
+* rack (1.2.1)
+* rack-cache (0.5.3)
+* rack-mount (0.6.13)
+* rack-test (0.5.6)
+* rails (3.1.0.beta)
+* railties (3.1.0.beta)
+* rake (0.8.7)
+* sqlite3-ruby (1.3.2)
+* thor (0.14.6)
+* treetop (1.4.9)
+* tzinfo (0.3.23)
+
+h4. +rails/commands.rb+
+
+Once +config/boot.rb+ has finished, the next file that is required is +rails/commands+ which will execute a command based on the arguments passed in. In this case, the +ARGV+ array simply contains +server+ which is extracted into the +command+ variable using these lines:
+
+<ruby>
+ aliases = {
+ "g" => "generate",
+ "c" => "console",
+ "s" => "server",
+ "db" => "dbconsole"
+ }
- module ClassMethods
- include SanitizeHelper::ClassMethods
- end
+ command = ARGV.shift
+ command = aliases[command] || command
</ruby>
-Inside of +SanitizeHelper::ClassMethods+ it defines, of course, methods for assisting with sanitizing in Rails such as +link_sanitizer+ which is used by the +strip_links+ method.
-
-Afterwards this includes the +ActiveSupport::Benchmarkable+ which is used for benchmarking how long a specific thing takes in a view. The method is simply +benchmark+ and can be used like this:
+If we used <tt>s</tt> rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code:
<ruby>
- benchmark("potentially long running thing") do
- Post.count
- end
-</ruby>
-
-The "documentation":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html is great about explaining what precisely this does.
+ when 'server'
+ # Change to the application's path if there is no config.ru file in current dir.
+ # This allows us to run script/rails server from other directories, but still get
+ # the main config.ru and properly set the tmp directory.
+ Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
-This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods.
-
-After including +ActiveSupport::Benchmarkable+, the helpers which we have declared to be +autoload+'d are included. I will not go through and cover what each of these helpers do, as their names should be fairly explicit about it, and it's not really within the scope of this guide.
-
-h5. +ActionView::Rendering+
-
-This module, from _actionpack/lib/action_view/render/rendering.rb_ defines a method you may be a little too familiar with: +render+. This is the +render+ use for rendering all kinds of things, such as partials, templates and text.
-
-h5. +ActionView::Partials+
-
-This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials.
-
-h5. +ActionView::Layouts+
-
-This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts.
-
-h5. +ERB::Util+
-
-The +ERB::Util+ module from Ruby core, as the document describes it: "A utility module for conversion routines, often handy in HTML generation". It offers two methods +html_escape+ and +url_encode+, with a third called +json_escape+ being added in by the requirement of _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ earlier. As explained earlier, +html_escape+ is overridden to return a string marked as safe.
-
-h5. +ActionView::Context+
-
-TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out.
-
-h5. Action View Railtie
-
-Now that _actionpack/lib/action_view.rb_ has been required, the next step is to +require 'rails'+, but this will be skipped as the file was required by _railties/lib/rails/all.rb_ way back in the beginnings of the initialization process.
-
-Next, the Railtie itself is defined:
-
-
-<ruby>
- module ActionView
- class Railtie < Rails::Railtie
- railtie_name :action_view
-
- require "action_view/railties/log_subscriber"
- log_subscriber ActionView::Railties::LogSubscriber.new
-
- initializer "action_view.cache_asset_id" do |app|
- unless app.config.cache_classes
- ActiveSupport.on_load(:action_view) do
- ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
- end
- end
- end
- end
- end
+ require 'rails/commands/server'
+ Rails::Server.new.tap { |server|
+ # We need to require application after the server sets environment,
+ # otherwise the --environment option given to the server won't propagate.
+ require APP_PATH
+ Dir.chdir(Rails.application.root)
+ server.start
+ }
</ruby>
-The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct.
-
-The sole initializer defined here, _action_view.cache_asset_ids_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate.
-
-h4. Action Mailer Railtie
+This file will change into the root of the directory (a path two directories back from +APP_PATH+ which points at +config/application.rb+), but only if the +config.ru+ file isn't found. This then requires +rails/commands/server+ which requires +action_dispatch+ and sets up the +Rails::Server+ class.
-The Action Mailer Railtie is responsible for including all the emailing functionality into Rails by way of the Action Mailer gem itself. Action Mailer is:
+h4. +actionpack/lib/action_dispatch.rb+
-Action Mailer is a framework for designing email-service layers. These layers
-are used to consolidate code for sending out forgotten passwords, welcome
-wishes on signup, invoices for billing, and any other use case that requires
-a written notification to either a person or another system.
+Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+.
-Action Mailer is in essence a wrapper around Action Controller and the
-Mail gem. It provides a way to make emails using templates in the same
-way that Action Controller renders views using templates.
+h4. +activesupport/lib/active_support.rb+
-TODO: Quotify.
+This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+
-h5. +require 'action_mailer/railtie'+
+h4. +activesupport/lib/active_support/lazy_load_hooks.rb+
-This file first makes two requires:
+This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on.
-<ruby>
- require "action_mailer"
- require "rails"
-</ruby>
-
-The requires in +action_mailer+ are already loaded or are core extensions:
-
-<ruby>
- require 'abstract_controller'
- require 'action_view'
-
- # Common Active Support usage in Action Mailer
- require 'active_support/core_ext/class'
- require 'active_support/core_ext/object/blank'
- require 'active_support/core_ext/array/uniq_by'
- 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'
-</ruby>
-
-_abstract_controller_ is covered in the "Action Controller Railtie" section. TODO: Cover AbstractController there and link to it.
-_action_view_ was required by the Action View Railtie and will not be required again.
-
-For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide.
-
-_active_support/lazy_load_hooks_ was covered earlier in the guide and since it has already been required at this point in the initialization process, it will not be required again.
-
-The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section.
+This file begins with requiring +active_support/inflector/methods+.
-_actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module:
+h4. +activesupport/lib/active_support/inflector/methods.rb+
-<ruby>
- module ActionMailer
- extend ::ActiveSupport::Autoload
-
- autoload :AdvAttrAccessor
- autoload :Collector
- autoload :Base
- autoload :DeliveryMethods
- autoload :DeprecatedApi
- autoload :MailHelper
- autoload :OldApi
- autoload :Quoting
- autoload :TestCase
- autoload :TestHelper
- end
-</ruby>
+The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently.
-And a +Text+ module too:
+In this file there are a lot of lines such as this inside the +ActiveSupport+ module:
<ruby>
- module Text
- extend ActiveSupport::Autoload
-
- autoload :Format, 'text/format'
- end
+ autoload :Inflector
</ruby>
-which is used by the +ActionMailer::MailerHelper+ method +block_format+:
-
-<ruby>
- def block_format(text)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
- }.join("\n")
-
- # Make list points stand on their own line
- formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
- formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
- formatted
- end
-</ruby>
+Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced.
-h5. Action Mailer Railtie
+The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport.
-The Railtie defines the +log_subscriber+ as +ActionMailer::Railties::LogSubscriber.new+, with this class having two logging methods: one for delivery called +deliver+ and one for receipt called +receive+.
+The +active_support/lib/active_support.rb+ file simply defines the +ActiveSupport+ module and some autoloads (eager and of the normal variety) for it.
-The initializers defined in this Railtie are:
+h4. +actionpack/lib/action_dispatch.rb+ cont'd.
-* action_mailer.url_for
-* action_mailer.logger
-* action_mailer.set_configs
+Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this file is one for +action_pack+, which simply calls +action_pack/version.rb+ which defines +ActionPack::VERSION+ and the constants, much like +ActiveSpport+ does.
-These are covered later on the Initialization section. TODO: first write then link to Initialization section.
+After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on.
-h4. Active Resource Railtie
+The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it.
-The Active Resource Railtie is responsible for creating an interface into remote sites that offer a REST API. The Active Resource Railtie depends on Active Support and Active Model.
+Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared.
-h5. +require 'active_resource/railtie'+
+h4. +rails/commands/server.rb+
-This file defines the Active Resource Railtie:
+The +Rails::Server+ class is defined in this file as inheriting from +Rack::Server+. When +Rails::Server.new+ is called, this calls the +initialize+ method in +rails/commands/server.rb+:
<ruby>
- require "active_resource"
- require "rails"
-
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
+ def initialize(*)
+ super
+ set_environment
end
</ruby>
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-h5. +require 'active_resource'+
-
-This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to Active Support and Active Model to the load path if it's not already there, then require both +active_support+ (_activesupport/lib/active_support.rb_) and +active_model+ (_activemodel/lib/active_model.rb_)
-
-<ruby>
- activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
- $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
- activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
- $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
-
- require 'active_support'
- require 'active_model'
+Firstly, +super+ is called which calls the +initialize+ method on +Rack::Server+.
- module ActiveResource
- extend ActiveSupport::Autoload
-
- autoload :Base
- autoload :Connection
- autoload :CustomMethods
- autoload :Formats
- autoload :HttpMock
- autoload :Observing
- autoload :Schema
- autoload :Validations
- end
-</ruby>
+h4. Rack: +lib/rack/server.rb+
-h5. Active Resource Railtie
++Rack::Server+ is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of.
-The Railtie itself is fairly short as Active Resource is the smallest component of Rails.
+The +initialize+ method in +Rack::Server+ simply sets a couple of variables:
<ruby>
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
+ def initialize(options = nil)
+ @options = options
+ @app = options[:app] if options && options[:app]
end
</ruby>
-The Railtie defines the +log_subscriber+ as +ActiveResource::Railties::LogSubscriber.new+ which has one method defined: +request+. +request+ is used whenever a request is made to an external service.
-
-There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section.
-
-
-h4. ActionDispatch Railtie
-
-ActionDispatch handles all dispatch work for Rails. It interfaces with Action Controller to determine what action to undertake when a request comes in. TODO: I would quote the README but it is strangely absent. Flyin' blind here!
-
-The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too.
+In this case, +options+ will be +nil+ so nothing happens in this method.
-ActionDispatch depends on Active Support.
-
-h5. +require 'action_dispatch/railtie'+
-
-This file defines the ActionDispatch Railtie:
+After +super+ has finished in +Rack::Server+, we jump back to +rails/commands/server.rb+. At this point, +set_environment+ is called within the context of the +Rails::Server+ object and this method doesn't appear to do much at first glance:
<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
- end
-</ruby>
-
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-
-
-
-h5. +require 'action_dispatch'+
-
-This file was already loaded earlier in the initialization process. TODO: link to it.
-
-h5. ActionDispatch Railtie
-
-The ActionDispatch Railtie is almost as short as the Active Resource Railtie:
-
-<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
+ def set_environment
+ ENV["RAILS_ENV"] ||= options[:environment]
end
</ruby>
-The +config+ method here is from +Rails::Railtie+ and pertains to your application's configuration. In this case, it is setting up some defaults which you can later override in _config/application.rb_.
-
-This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+.
-
-h3. Return to _config/application.rb_
-
-Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line:
+In fact, the +options+ method here does quite a lot. This method is defined in +Rack::Server+ like this:
<ruby>
- Bundler.require :default, Rails.env
-</ruby>
-
-NOTE: It is worth mentioning here that you are not tied to using Bundler with Rails 3, but it is (of course) advised that you do. To "turn off" Bundler, comment out or remove the corresponding lines in _config/application.rb_ and _config/boot.rb_.
-
-Bundler was +require+'d back in _config/boot.rb_, and so that is what makes it available here. This guide does not dive into the internals of Bundler; it's really it's own separate guide.
-
-The +Bundler.require+ method adds all the gems not specified inside a +group+ in the +Gemfile+ and the ones specified in groups for the +Rails.env+ (in this case, _development_), to the load path. This is how an application is able to find them.
-
-The rest of this file is spent defining your application's main class. This is it without the comments:
-
-<ruby>
- module YourApp
- class Application < Rails::Application
- config.encoding = "utf-8"
- config.filter_parameters += [:password]
- end
+ def options
+ @options ||= parse_options(ARGV)
end
</ruby>
-h3. Return to Rails
-
-On the surface, this looks like a simple class inheritance. There's more underneath though. back in +Rails::Application+, the +inherited+ method is defined:
+Then +parse_options+ is defined like this:
<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-We do not already have a +Rails.application+, so instead this resorts to calling +super+. +Rails::Application+ descends from +Rails::Engine+ and so will call the +inherited+ method in +Rails::Engine+ (in _railties/lib/rails/engine.rb_), but before that it's important to note that +called_from+ is defined an +attr_accessor+ on +Rails::Engine+ and that +YourApp::Application+ is not an +abstract_railtie+:
+ def parse_options(args)
+ options = default_options
-<ruby>
- def inherited(base)
- unless base.abstract_railtie?
- base.called_from = begin
- # Remove the line number from backtraces making sure we don't leave anything behind
- call_stack = caller.map { |p| p.split(':')[0..-2].join(':') }
- File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] })
- end
- end
+ # Don't evaluate CGI ISINDEX parameters.
+ # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
+ args.clear if ENV.include?("REQUEST_METHOD")
- super
+ options.merge! opt_parser.parse! args
+ options[:config] = ::File.expand_path(options[:config])
+ ENV["RACK_ENV"] = options[:environment]
+ options
end
</ruby>
-This +called_from+ setting looks a little overwhelming to begin with, but the short end of it is that it returns your application's root, something like: _/home/you/yourapp_. After +called_from+ has been set, +super+ is again called and this means the +Rails::Railtie#inherited+ method (in _railties/lib/rails/railtie.rb_):
+With the +default_options+ set to this:
<ruby>
- def inherited(base)
- unless base.abstract_railtie?
- base.send(:include, self::Configurable)
- subclasses << base
- end
+ def default_options
+ {
+ :environment => ENV['RACK_ENV'] || "development",
+ :pid => nil,
+ :Port => 9292,
+ :Host => "0.0.0.0",
+ :AccessLog => [],
+ :config => "config.ru"
+ }
end
</ruby>
-Again, +YourApp::Application+ will return false for +abstract_railtie+ and so the code inside the +unless+ will be ran. The first line:
-
-<ruby>
- base.send(:include, self::Configurable)
-</ruby>
-
-includes the +self::Configurable+ module, with self being +Rails::Application+ in this context:
+There is no +REQUEST_METHOD+ key in +ENV+ so we can skip over that line. The next line merges in the options from +opt_parser+ which is defined plainly in +Rack::Server+
<ruby>
- module Rails
- class Application
- module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- def inherited(base)
- raise "You cannot inherit from a Rails::Application child"
- end
- end
-
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
- end
- end
+ def opt_parser
+ Options.new
end
</ruby>
-The inclusion of the +Rails::Application::Configurable+ module triggers the +included+ method in here which extends +YourApp::Application+ with the +Rails::Application::Configurable::ClassMethods+.
-
-Now that the chain of +super+ calls is done, we'll go back to the original +inherited+ method in +Rails::Application+ and the final line in this method:
+The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ to take different arguments. Its +parse!+ method begins like this:
<ruby>
- Rails.application = base.instance
-</ruby>
-
-+base+ in this case is +YourApp::Application+ and calling +instance+ on this will return an instance of +YourApp::Application+ through the +instance+ method defined here:
+ def parse!(args)
+ args, options = args.dup, {}
-<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
+ opt_parser = OptionParser.new do |opts|
+ opts.banner = "Usage: rails server [mongrel, thin, etc] [options]"
+ opts.on("-p", "--port=port", Integer,
+ "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
+ ...
</ruby>
-+self+ in this case is +YourApp::Application+, so it won't match to +Rails::Application+ so instead the +new+ method is called which calls the +initialize+ method.
-
-
-
-
-h3. Firing it up!
+This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server.
-Now that we've covered the boot process of Rails the next line best to cover would be what happens after _script/rails_ has loaded _config/boot.rb_. That's quite simply that it then +require 'rails/commands'+ which is located at _railties/lib/rails/commands.rb_. Remember how +exec+ passed the arguments to +script/rails+? This is where they're used. _rails/commands.rb_ is quite a large file in Rails 3, as it contains all the Rails commands like console, about, generate and, of course, server. Because we've called +rails server+ the first argument in +ARGV+ is of course +"server"+. So assuming this we can determine that the +ARGV.shift+ in _commands.rb_ is going to return +"server"+, therefore it'll match this +when+:
+h4. +Rails::Server#start+
-<ruby>
- when 's', 'server'
- require 'rails/commands/server'
- Dir.chdir(ROOT_PATH)
- Rails::Server.start
-</ruby>
-
-The keen-eyed observer will note that this +when+ also specifies the argument could also be simply +'s'+ thereby making the full command +rails s+. This is the same with the other commands with +generate+ becoming +g+, +console+ becoming +c+ and +dbconsole+ becoming +db+.
-
-This code here ensures we are at the +ROOT_PATH+ of our application (this constant was defined in _script/rails_) and then calls +Rails::Server.start+. +Rails::Server+ descends from +Rack::Server+ which is defined in the rack gem. The +Rails::Server.start+ method is defined like this:
+This method is defined like this:
<ruby>
def start
- ENV["RAILS_ENV"] = options[:environment]
-
puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}"
puts "=> Call with -d to detach" unless options[:daemonize]
trap(:INT) { exit }
puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
+ #Create required tmp directories if not found
+ %w(cache pids sessions sockets).each do |dir_to_make|
+ FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make))
+ end
+
super
ensure
- puts 'Exiting' unless options[:daemonize]
- end
-</ruby>
-
-We can see here that there is usual output indicating that the server is booting up.
-
-How the +options+ variable gets set and how Rack starts the server up is covered in the next section.
-
-h3. Racking it up!
-
-
-This +Rack::Server.start+ method is defined like this:
-
-<ruby>
- def self.start
- new.start
- end
-</ruby>
-
-+new+ as you know calls +initialize+ in a class, and that is defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
+ # The '-h' option calls exit before @options is set.
+ # If we call 'options' with it unset, we get double help banners.
+ puts 'Exiting' unless @options && options[:daemonize]
end
</ruby>
-And then +options+, which are the options referenced by the +start+ method in +Rails::Server+.
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-And +parse_options+:
-
-<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Finally! We've arrived at +default_options+ which leads into our next point quite nicely. After the object has been +initialize+'d, +start+ is called:
+This is where the first output of the Rails initialization happens. This method creates a trap for +INT+ signals, so if you +CTRL+C+ the server, it will exit the process. As we can see from the code here, it will create the +tmp/cache+, +tmp/pids+, +tmp/sessions+ and +tmp/sockets+ directories if they don't already exist prior to calling +super+. The +super+ method will call +Rack::Server.start+ which begins its definition like this:
<ruby>
def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-
if options[:warn]
$-w = true
end
if includes = options[:include]
- $LOAD_PATH.unshift *includes
+ $LOAD_PATH.unshift(*includes)
end
if library = options[:require]
require library
end
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
+ if options[:debug]
+ $DEBUG = true
+ require 'pp'
+ p options[:server]
+ pp wrapped_app
+ pp app
+ end
</ruby>
-We're not debugging anything, so there goes the first 7 lines, we're not warning, nor are we including, requiring, daemonising or writing out a pid file. That's everything except the final line, which calls +run+ with the +wrapped_app+ which is then defined like this:
+In a Rails application, these options are not set at all and therefore aren't used at all. The first line of code that's executed in this method is a call to this method:
<ruby>
- def wrapped_app
- @wrapped_app ||= build_app app
- end
+ wrapped_app
</ruby>
-and +build_app+'s first and only argument is +app+ which is defined like this:
+This method calls another method:
+
+<ruby>
+ @wrapped_app ||= build_app app
+</ruby>
+Then the +app+ method here is defined like so:
<ruby>
def app
@@ -2023,1744 +435,678 @@ and +build_app+'s first and only argument is +app+ which is defined like this:
end
</ruby>
-+options+ is a method we talked about a short while ago, which is just the set of default options. +options[:config]+ in this context is therefore _config.ru_ which coincidentally we have in our application! To get an application instance from this method +Rack::Builder+ joins the fray with a call to +parse_file+ on our _config.ru_:
-
-<ruby>
- def self.parse_file(config, opts = Server::Options.new)
- options = {}
- if config =~ /\.ru$/
- cfgfile = ::File.read(config)
- if cfgfile[/^#\\(.*)/] && opts
- options = opts.parse! $1.split(/\s+/)
- end
- cfgfile.sub!(/^__END__\n.*/, '')
- app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
- TOPLEVEL_BINDING, config
- else
- require config
- app = Object.const_get(::File.basename(config, '.rb').capitalize)
- end
- return app, options
- end
-</ruby>
-
-First this reads your config file and checks it for +#\+ at the beginning. This is supported if you want to pass options into the +Rack::Server+ instance that you have and can be used like this:
+The +options[:config]+ value defaults to +config.ru+ which contains this:
<ruby>
- #\\ -E production
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
- run YourApp::Application.instance
-
-</ruby>
-
-TODO: Is the above correct? I am simply guessing!
-
-After that it removes all the content after any +__END__+ in your _config.ru_ (TODO: because? Is this so it doesn't get eval'd?) and then evals the content of this file which, as you've seen is quite simple. The code that's first evaluated would be the require to the _config/environment.rb_ file, which leads into the next section.
-
-h3. _config/environment.rb_
-
-Now that we've seen that _rails/server_ gets to _config/environment.rb_ via Rack's requiring of it and Passenger requires it straight off the line. We've covered the boot process of Rails and covered the beginnings of a Rack server starting up. We have reached a common path for both _rails/server_ and Passenger now, so let's investigate what _config/environment.rb_ does.
-
-<ruby>
- # Load the rails application
- require File.expand_path('../application', __FILE__)
-
- # Initialize the rails application
- YourApp::Application.initialize!
-
+ run YourApp::Application
</ruby>
-As you can see, there's a require in here for _config/application.rb_, and this file looks like this:
+The +Rack::Builder.parse_file+ method here takes the content from this +config.ru+ file and parses it using this code:
<ruby>
- module YourApp
- class Application < Rails::Application
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
-
- # Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{config.root}/extras )
-
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
- # 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)'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
- # config.i18n.default_locale = :de
-
- # Configure generators values. Many other options are available, be sure to check the documentation.
- # config.generators do |g|
- # g.orm :active_record
- # g.template_engine :erb
- # g.test_framework :test_unit, :fixture => true
- # end
- end
- end
-</ruby>
-
-These options (and their siblings) are explained in a later section. What's important to note for this file currently is that this is where the +YourApp::Application+ class is initialized and that it's a subclass of +Rails::Application+. This is the first point where your application begins to initialize Rails and as you can see all of this is configuration stuff which your initializers and really, the rest of your application will depend on. These options and what they do will be covered later.
-
-
-h3. Rails Initialization Process
-
-Now begins the actual initialization of Rails. Previously we have covered how _rails server_ and Passenger get to this stage and the parts of Rails that they have both loaded.
-
-h3. +Rails::Application+
-
-The first steps for the initialization process of Rails begins when +YourApp::Application+ descends from +Rails::Application+. The +Rails::Application+ class descends from +Rails::Engine+ class which itself descends from +Rails::Railtie+ defined in _railties/lib/rails/railtie.rb_. Along this fantastical chain of superclasses, there's defined a couple of inherited class methods. These methods just so happen to be called when a class inherits from (aka: is made a subclass of) this class. This first one is for +Rails::Application+:
-
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-This goes up the chain by using +super+ to calling +Rails::Engine.inherited+:
-
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
- end
- end
-
- super
- end
+ app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
+ TOPLEVEL_BINDING, config
</ruby>
-+called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section.
-
-Which then calls +Rails::Railtie.inherited+:
+The <ruby>initialize</ruby> method will take the block here and execute it within an instance of +Rack::Builder+. This is where the majority of the initialization process of Rails happens. The chain of events that this simple line sets off will be the focus of a large majority of this guide. The +require+ line for +config/environment.rb+ in +config.ru+ is the first to run:
<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.send(:include, self::Configurable)
- subclasses << base
- end
- end
+ require ::File.expand_path('../config/environment', __FILE__)
</ruby>
-This +inherited+ first includes the +Rails::Configurable+ module on +base+, which is +YourApp::Application+. This module defines the +config+ method on +YourApp::Application+, and now it's starting to come together. You may notice that in your +config/application.rb+ file there's a +config+ method called there. This is the method from +Rails::Configurable+.
+h4. +config/environment.rb+
-Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain.
+This file is the common file required by +config.ru+ (+rails server+) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup.
-With +Rails::Railtie.inherited+ out of the way, and that being the last thing to do in +Rails::Engine.inherited+ we return to +Rails::Application.inherited+ which calls the following:
+This file begins with requiring +config/application.rb+.
-<ruby>
- Rails.application = base.instance
-</ruby>
+h4. +config/application.rb+
-As you already know, +base+ is +YourApp::Application+ and now it's calling the +instance+ method on it. This method is defined in +Rails::Application+ like this:
+This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger.
-<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
-</ruby>
+Then the fun begins!
-The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic.
+h3. Loading Rails
-h3. Your Application's Configuration
-
-Now that +inherited+ has finished doing its job, next up in _config/application.rb_ is the call to the +config+ object's methods. As explained before, this +config+ object is an instance of +Rails::Railtie::Configuration+, put into place by the call of +include Rails::Configurable+ back in +Rails::Railtie.inherited+. This defined it as such:
-
-<ruby>
- def config
- @config ||= Railtie::Configuration.new
- end
-</ruby>
-
-All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_:
+The next line in +config/application.rb+ is:
<ruby>
- require 'rails/configuration'
-
- module Rails
- class Railtie
- class Configuration
- include Rails::Configuration::Shared
- end
- end
- end
+ require 'rails/all'
</ruby>
-As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_).
+h4 +railties/lib/rails/all.rb+
-h3. +Rails::Configuration::Shared+
-In a standard application, the +application.rb+ looks like this with all the comments stripped out:
+This file is responsible for requiring all the individual parts of Rails like so:
<ruby>
- require File.expand_path('../boot', __FILE__)
+ require "rails"
- module YourApp
- class Application < Rails::Application
- config.filter_parameters << :password
+ %w(
+ active_record
+ action_controller
+ action_mailer
+ active_resource
+ rails/test_unit
+ ).each do |framework|
+ begin
+ require "#{framework}/railtie"
+ rescue LoadError
end
end
</ruby>
-The +config+ method being the one defined on +Rails::Application::Configurable+:
-
-<ruby>
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
-</ruby>
+First off the line is the +rails+ require itself.
-The method +find_with_root_flag+ is defined on +Rails::Engine+ (the superclass of +Rails::Application+) and it will find the directory containing a certain flag. In this case it's the +config.ru+ file:
+h4. +railties/lib/rails.rb+
-<ruby>
- def find_root_with_flag(flag, default=nil)
- root_path = self.called_from
+This file is responsible for the initial definition of the +Rails+ module and, rather than defining the autoloads like +ActiveSupport+, +ActionDispatch+ and so on, it actually defines other functionality. Such as the +root+, +env+ and +application+ methods which are extremely useful in Rails 3 applications.
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
+However, before all that takes place the +rails/ruby_version_check+ file is required first.
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
+h4. +railties/lib/rails/ruby_version_check.rb+
- RUBY_PLATFORM =~ /(:?mswin|mingw)/ ?
- Pathname.new(root).expand_path : Pathname.new(root).realpath
- end
-</ruby>
+This file simply checks if the Ruby version is less than 1.8.7 or is 1.9.1 and raises an error if that is the case. Rails 3 simply will not run on earlier versions of Ruby than 1.8.7 or 1.9.1.
-+called_from+ goes through the +caller+ which is the stacktrace of the current thread, in the case of your application it would go a little like this:
+NOTE: You should always endeavour to run the latest version of Ruby with your Rails applications. The benefits are many, including security fixes and the like, and very often there is a speed increase associated with it. The caveat is that you could have code that potentially breaks on the latest version, which should be fixed to work on the latest version rather than kept around as an excuse not to upgrade.
-<pre>
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/application.rb:30:in `inherited'
- /home/you/yourapp/config/application.rb:4:in `<module:TestApp>'
- /home/you/yourapp/config/application.rb:3:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:33:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /var/www/rboard/script/rails:10:in `<main>'
-</pre>
+h4. +active_support/core_ext/kernel/reporting.rb+
-+called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this:
+This is the first of the many Active Support core extensions that come with Rails. This one in particular defines methods in the +Kernel+ module which is mixed in to the +Object+ class so the methods are available on +main+ and can therefore be called like this:
<ruby>
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
+ silence_warnings do
+ # some code
end
</ruby>
-The +call_stack+ here is the +caller+ output shown previously, minus everything after the first +:+ on all the lines. The first path that matches this is _/usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_.
+These methods can be used to silence STDERR responses and the +silence_stream+ allows you to also silence other streams. Additionally, this mixin allows you to suppress exceptions and capture streams. For more information see the "Silencing Warnings, Streams, and Exceptions":http://guides.rubyonrails.org/active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide.
-The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+.
+h4. +active_support/core_ext/logger.rb+
-<ruby>
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
+The next file that is required is another Active Support core extension, this time to the +Logger+ class. This begins by defining the +around_[level]+ helpers for the +Logger+ class as well as other methods such as a +datetime_format+ getter and setter for the +formatter+ object tied to a +Logger+ object.
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
-</ruby>
-
-TODO: What is all this for?
-
-At the root of the system it looks for +config.ru+. TODO: Why? Obviously it's not going to find it, so it uses the +default+ option we've specified which is +Dir.pwd+ which will default to the root folder of your Rails application. This path is then passed to +Rails::Application::Configuration.new+. +Rails::Application::Configuration+ descends from +Rails::Engine::Configuration+ and the +initialize+ method goes like this:
+For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide.
-<ruby>
- def initialize(*)
- super
- @allow_concurrency = false
- @colorize_logging = true
- @filter_parameters = []
- @dependency_loading = true
- @serve_static_assets = true
- @time_zone = "UTC"
- @consider_all_requests_local = true
- end
-</ruby>
+h4. +railties/lib/rails/application.rb+
-The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+:
+The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first.
-<ruby>
- def initialize(root=nil)
- @root = root
- end
-</ruby>
+The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section.
-Here, the +@root+ variable is assigned the path of your application and then the remainder of +Rails::Application::Configuration.initialize+ is ran, setting up a few instance variables for basic configuration, including one for +@filter_parameters+.
+h4. +active_support/file_update_checker.rb+
-Now with the +config+ option set up, we can go onwards and call +filter_parameters+ on it. This +filter_parameters+ method is not defined on +Rails::Configuration::Shared+ and actually falls to the +method_missing+ defined there instead:
+The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs.
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
- end
- super
- end
-</ruby>
+h4. +railties/lib/rails/plugin.rb+
-We're not calling +filter_parameters=+, we're calling +filter_parameters+, therefore it'll be the second part of this ternary argument: +options[$1]+. The options method is defined like this:
+This file defines +Rails::Plugin+ which inherits from +Rails::Engine+. Unlike +Rails::Engine+ and +Rails::Railtie+ however, this class is not designed to be inherited from. Instead, this is used simply for loading plugins from within an application and an engine.
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
+This file begins by requiring +rails/engine.rb+
-OrderedOptions exists... TODO: explain.
+h4. +railties/lib/rails/engine.rb+
+The +rails/engine.rb+ file defines the +Rails::Engine+ class which inherits from +Rails::Railtie+. The +Rails::Engine+ class defines much of the functionality found within a standard application class such as the +routes+ and +config+ methods.
-So from this we can determine that our +options+ hash now has a key for +filter_parameters+ which's value is an array consisting of a single symbol: +:password+. How this option manages to get into the +@filter_parameters+ variable defined on the +Rails::Application::Configuration.initialize+ method is explained later.
+The "API documentation":http://api.rubyonrails.org/classes/Rails/Engine.html for +Rails::Engine+ explains the function of this class pretty well.
-h3. Application Configured!
+This file's first line requires +rails/railtie.rb+.
-Now your application has finished being configured (at least in the sense of _config/application.rb_, there's more to come!) in _config/environment.rb_ the final line calls +YourApp::Application.initalize!+.
+h4. +railties/lib/rails/railtie.rb+
-h3. Initialization begins
+The +rails/railtie.rb+ file is responsible for defining +Rails::Railtie+, the underlying class for all ties to Rails now. Gems that want to have their own initializers or rake tasks and hook into Rails should have a +GemName::Railtie+ class that inherits from +Rails::Railtie+.
-This is one of those magical uses of +method_missing+ which, for the purposes of debugging, is something that you don't expect to come across as often as you do and as a consequence you'll spend a good portion of an hour looking for method definitions that don't exist because +method_missing+ is taking care of it. There's some pretty crafty use of +method_missing+ all over Rails and it's encouraged to take note of its power.
+The "API documentation":http://api.rubyonrails.org/classes/Rails/Railtie.html for +Rails::Railtie+, much like +Rails::Engine+, explains this class exceptionally well.
-+Rails::Application+ has a +method_missing+ definition which does this:
+The first require in this file is +rails/initializable.rb+.
-<ruby>
- def method_missing(*args, &block)
- instance.send(*args, &block)
- end
-</ruby>
+h4. +railties/lib/rails/initializable.rb+
-With our +instance+ being our already initialized by the +inherited+ method, this will just return the value of the +@@instance+ variable, a +Rails::Application+ object. Calling +initialize!+ on this method does this:
+Now we reach the end of this particular rabbit hole as +rails/initializable.rb+ doesn't require any more Rails files, only +tsort+ from the Ruby standard library.
-<ruby>
- def initialize!
- run_initializers(self)
- self
- end
-</ruby>
+This file defines the +Rails::Initializable+ module which contains the +Initializer+ class, the basis for all initializers in Rails. This module also contains a +ClassMethods+ class which will be included into the +Rails::Railtie+ class when these requires have finished.
-The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+.
+Now that +rails/initializable.rb+ has finished being required from +rails/railtie.rb+, the next require is for +rails/configuration+.
+h4. +railties/lib/rails/configuration.rb+
-h3. +run_initializers+
+This file defines the +Rails::Configuration+ module, containing the +MiddlewareStackProxy+ class as well as the +Generators+ class. The +MiddlewareStackProxy+ class is used for managing the middleware stack for an application, which we'll see later on. The +Generators+ class provides the functionality used for configuring what generators an application uses through the "+config.generators+ option":http://guides.rubyonrails.org/configuring.html#configuring-generators.
-This method begins the running of all the defined initializers. In the section "The Boot Process" we covered the loading sequence of Rails before any initialization happens and during this time we saw that the +Rails::Railtie+ class includes the +Initializable+ module. As we've also seen +YourApp::Application+ is a descendant of this class, so it too has these methods.
+The first file required in this file is +activesupport/deprecation+.
-+run_initializers+ looks like this:
+h4. +activesupport/lib/active_support/deprecation.rb+
-<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
- end
- @ran = true
- end
-</ruby>
+This file, and the files it requires, define the basic deprecation warning features found in Rails. This file is responsible for setting defaults in the +ActiveSupport::Deprecation+ module for the +deprecation_horizon+, +silenced+ and +debug+ values. The files that are required before this happens are:
-Here the +initializers+ method is defined in _railties/lib/rails/application.rb_:
+* +active_support/deprecation/behaviors+
+* +active_support/deprecation/reporting+
+* +active_support/deprecation/method_wrappers+
+* +active_support/deprecation/proxy_wrappers+
-<ruby>
- def initializers
- initializers = Bootstrap.initializers_for(self)
- railties.all { |r| initializers += r.initializers }
- initializers += super
- initializers += Finisher.initializers_for(self)
- initializers
- end
-</ruby>
+h4. +activesupport/lib/active_support/deprecation/behaviors.rb+
-h3. +Bootstrap+ initializers
+This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+.
-The first line here references a +Bootstrap+ class we haven't seen before. Or have we? The keen-eyed observer would have spotted an +autoload+ for it at the top of +Rails::Application+:
+h4 +activesupport/lib/active_support/notifications.rb+
-<ruby>
- autoload :Bootstrap, 'rails/application/bootstrap'
-</ruby>
+TODO: document +ActiveSupport::Notifications+.
-Now that we've referenced that class, it will be required for us. You'll notice inside this class that there's an +include Initializable+, providing the afore-mentioned methods from this module. Inside this class a number of initializers are defined.
+h4. +activesupport/core_ext/array/wrap+
-* load_environment_config
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
+As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#wrapping
-These are all defined using the +initializer+ method:
+h4. +activesupport/lib/active_support/deprecation/reporting.rb+
-<ruby>
- def initializer(name, opts = {}, &blk)
- raise ArgumentError, "A block must be passed when defining an initializer" unless blk
- opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
- initializers << Initializer.new(name, nil, opts, &blk)
- end
-</ruby>
+This file is responsible for defining the +warn+ and +silence+ methods for +ActiveSupport::Deprecation+ as well as additional private methods for this module.
-The +initializers+ method defined here just references an +@initializers+ variable:
+h4. +activesupport/lib/active_support/deprecation/method_wrappers.rb+
-<ruby>
- def initializers
- @initializers ||= []
- end
-</ruby>
+This file defines a +deprecate_methods+ which is primarily used by the +module/deprecation+ core extension required by the first line of this file. Other core extensions required by this file are the +module/aliasing+ and +array/extract_options+ files.
-As you can see from this method it will set +opts[:after]+ if there are previously defined initializers. So we can determine from this that the order our initializers are defined in is the same order that they run in, but only by default. It is possible to change this by specifying an +:after+ or +:before+ option as we will see later on. Each initializer is its own instance of the +Initializer+ class:
+h4. +activesupport/lib/active_support/deprecation/proxy_wrappers.rb+
-<ruby>
- class Initializer
- attr_reader :name, :block
++proxy_wrappers.rb+ defines deprecation wrappers for methods, instance variables and constants. Previously, this was used for the +RAILS_ENV+ and +RAILS_ROOT+ constants for 3.0 but since then these constants have been removed. The deprecation message that would be raised from these would be something like:
- def initialize(name, context, options, &block)
- @name, @context, @options, @block = name, context, options, block
- end
-
- def before
- @options[:before]
- end
+<plain>
+ BadConstant is deprecated! Use GoodConstant instead.
+</plain>
- def after
- @options[:after]
- end
+h4. +active_support/ordered_options+
- def run(*args)
- @context.instance_exec(*args, &block)
- end
+This file is the next file required from +rails/configuration.rb+ is the file that defines +ActiveSupport::OrderedOptions+ which is used for configuration options such as +config.active_support+ and the like.
- def bind(context)
- return self if @context
- Initializer.new(@name, context, @options, &block)
- end
- end
-</ruby>
+The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup
-Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this:
+The file that is required next from is +rails/paths+
-<ruby>
- initializers = Bootstrap.initializers_for(self)
-</ruby>
+h4. +railties/lib/rails/paths.rb+
-Calling +initializers_for+, defined like this:
+This file defines the +Rails::Paths+ module which allows paths to be configured for a Rails application or engine. Later on in this guide when we cover Rails configuration during the initialization process we'll see this used to set up some default paths for Rails and some of them will be configured to be eager loaded.
-<ruby>
- def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
- end
-</ruby>
+h4. +railties/lib/rails/rack.rb+
-The +binding+ argument here is +YourApp::Application+ and this will return a new +Initializer+ object for all the initializers in +initializers_chain+ for this particular context. +initializers_chain+ goes like this:
+The final file to be loaded by +railties/lib/rails/configuration.rb+ is +rails/rack+ which defines some simple autoloads:
<ruby>
- def initializers_chain
- initializers = Collection.new
- ancestors.reverse_each do |klass|
- next unless klass.respond_to?(:initializers)
- initializers = initializers + klass.initializers
+ module Rails
+ module Rack
+ autoload :Debugger, "rails/rack/debugger"
+ autoload :Logger, "rails/rack/logger"
+ autoload :LogTailer, "rails/rack/log_tailer"
+ autoload :Static, "rails/rack/static"
end
- initializers
- end
-</ruby>
-
-The ancestors list is relatively short for +Rails::Application::Bootstrap+, consisting of itself and +Rails::Initializable+. Rails will go through these ancestors in reverse and check them all if they +respond_to?(:initializers)+. +Rails::Initializable+ does not and so it's skipped. +Rails::Application::Bootstrap+ of course does, and this is the list of initializers we covered earlier.
-
-After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously.
-
-<ruby>
- def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
- end
-</ruby>
-
-Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+.
-
-h3. Railties Initializers
-
-This section covers the loading of the initializers and we will go into depth for each initializer in the next section, as they make more sense explained in their chain.
-
-The second line in +Rails::Application#initializers+:
-
-<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
end
</ruby>
-calls +railties+, which is defined like this:
+Once this file is finished loading, then the +Rails::Configuration+ class is initialized. This completes the loading of +railties/lib/rails/configuration.rb+ and now we jump back to the loading of +railties/lib/rails/railtie.rb+, where the next file loaded is +active_support/inflector+.
-<ruby>
- def railties
- @railties ||= Railties.new(config)
- end
-</ruby>
+h4. +activesupport/lib/active_support/inflector.rb+
-This sets up a new +Rails::Application::Railties+ object like this:
++active_support/inflector.rb+ requires a series of file which are responsible for setting up the basics for knowing how to pluralize and singularize words. These files are:
<ruby>
- def initialize(config)
- @config = config
- end
-</ruby>
-
-And calls +all+ on it:
+ require 'active_support/inflector/inflections'
+ require 'active_support/inflector/transliterate'
+ require 'active_support/inflector/methods'
-<ruby>
- def all(&block)
- @all ||= railties + engines + plugins
- @all.each(&block) if block
- @all
- end
+ require 'active_support/inflections'
+ require 'active_support/core_ext/string/inflections'
</ruby>
-This +all+ method executes code on all the +Rails::Railtie+ and +Rails::Engine+ subclasses, retreived by the +railties+ and +engines+ methods defined right after +all+:
-
-<ruby>
- def railties
- @railties ||= ::Rails::Railtie.subclasses.map(&:new)
- end
+The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here.
- def engines
- @engines ||= ::Rails::Engine.subclasses.map(&:new)
- end
-</ruby>
+h4. +activesupport/lib/active_support/inflector/inflections.rb+
-By default, the railties are:
+This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes".
-* +ActiveSupport::Railtie+
-* +I18n::Railtie+
-* +ActionDispatch::Railtie+
-* +ActionController::Railtie+
-* +ActiveRecord::Railtie+
-* +ActionView::Railtie+
-* +ActionMailer::Railtie+
-* +ActiveResource::Railtie+
-* +Rails::TestUnitRailtie+
+h4. +activesupport/lib/active_support/inflector/transliterate.rb+
-And these all descend from +Rails::Railtie+.
+In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading.
-The default +engines+ are +[]+.
+h4. Back to +railties/lib/rails/railtie.rb+
-The +plugins+ method it calls is a little more complex:
+Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods.
-<ruby>
- def plugins
- @plugins ||= begin
- plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths.vendor.plugins)
- end
- end
-</ruby>
+h4. +railties/lib/rails/initializable.rb+
-+@config.paths+ is defined in the +Rails::Application::Configuration+ like this:
+When the module from this file (+Rails::Initializable+) is included, it extends the class it's included into with the +ClassMethods+ module inside of it. This module defines the +initializer+ method which is used to define initializers throughout all of the railties. This file completes the loading of +railties/lib/rails/railtie.rb+. Now we go back to +rails/engine.rb+.
-<ruby>
- def paths
- @paths ||= begin
- paths = super
- paths.app.controllers << builtin_controller if builtin_controller
- paths.config.database "config/database.yml"
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
- paths.log "log/#{Rails.env}.log"
- paths.tmp "tmp"
- paths.tmp.cache "tmp/cache"
- paths.vendor "vendor", :load_path => true
- paths.vendor.plugins "vendor/plugins"
-
- if File.exists?("#{root}/test/mocks/#{Rails.env}")
- ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " <<
- "automatically to load paths anymore in future releases"
- paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env
- end
+h4. +railties/lib/rails/engine.rb+
- paths
- end
- end
-</ruby>
+The next file required in +rails/engine.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation.
-When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+.
+The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+.
+h4. +railties/lib/rails/engine/railties.rb+
-If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code:
+This file defines the +Rails::Engine::Railties+ class which provides the +engines+ and +railties+ methods which are used later on for defining rake tasks and other functionality for engines and railties.
-<ruby>
- config.plugins = [:will_paginate, :by_star]
-</ruby>
+h4. Back to +railties/lib/rails/engine.rb+
-or specific plugin loading using a similar statement such as this next one:
+Once +rails/engine/railties.rb+ has finished loading the +Rails::Engine+ class gets its basic functionality defined, such as the +inherited+ method which will be called when this class is inherited from.
-<ruby>
- config.plugins = [:will_paginate, :by_star, :all]
-</ruby>
+Once this file has finished loading we jump back to +railties/lib/rails/plugin.rb+
+h4. Back to +railties/lib/rails/plugin.rb+
-Then this is where the +@config.plugins+ comes from. If you wish to load only certain plugins for your application, use the first example. If you wish to load certain plugins before the rest then the second example is what you would use.
+The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":http://guides.rubyonrails.org/active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide.
-If +config.plugins+ is not defined then +:all+ is specified in its place. Whatever the +plugin_names+ is specified as, is passed to +Plugin.all+ along with the path to the plugins, +@config.path.vendor.plugins+ (which defaults to _vendor/plugins_):
+Once that file has finished loading, the +Rails::Plugin+ class is defined.
-<ruby>
- def self.all(list, paths)
- plugins = []
- paths.each do |path|
- Dir["#{path}/*"].each do |plugin_path|
- plugin = new(plugin_path)
- next unless list.include?(plugin.name) || list.include?(:all)
- plugins << plugin
- end
- end
+h4. Back to +railties/lib/rails/application.rb+
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
- end
-</ruby>
+Jumping back to +rails/application.rb+ now. This file defines the +Rails::Application+ class where the application's class inherits from. This class (and its superclasses) define the basic behaviour on the application's constant such as the +config+ method used for configuring the application.
-As we can see here it will go through the paths and for every folder in _vendor/plugins_ and +initialize+ a new +Rails::Plugin+ object for each:
+Once this file's done then we go back to the +railties/lib/rails.rb+ file, which next requires +rails/version+.
-<ruby>
- def initialize(root)
- @name = File.basename(root).to_sym
- config.root = root
- end
-</ruby>
+h4. +railties/lib/rails/version.rb+
-This sets the plugin name to be the same name as the folder so the plugin located at _vendor/plugins/by\_star_'s name is +by_star+. After that, the +config+ object is initialized:
+Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails.
-<ruby>
- def config
- @config ||= Engine::Configuration.new
- end
-</ruby>
+Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+.
-and the root of the plugin defined as that folder. The reasoning for defining a +root+ is so that the initializer called +load_init_rb+ has some place to look for this file:
+h4. +activesupport/lib/active_support/railtie.rb+
-<ruby>
- initializer :load_init_rb, :before => :load_application_initializers do |app|
- file = Dir["#{root}/{rails/init,init}.rb"].first
- config = app.config
- eval(File.read(file), binding, file) if file && File.file?(file)
- end
-</ruby>
+This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+.
-A little more on that later, however.
+h4. +activesupport/lib/active_support/i18n_railtie.rb+
-If the plugin is not included in the list then it moves on to the next one. For all plugins included in the list (or if +:all+ is specified in the list) they are put into a +plugins+ local variable which is then sorted:
+This file is the first file that sets up configuration with these lines inside the class:
<ruby>
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
+ class Railtie < Rails::Railtie
+ config.i18n = ActiveSupport::OrderedOptions.new
+ config.i18n.railties_load_path = []
+ config.i18n.load_path = []
+ config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
</ruby>
-The sort order is the same order as which they appear in the +config.plugins+ setting, or in alphabetical order if there is no setting specified.
-
-Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code:
+By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called:
<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
- end
-</ruby>
-
-This block will gather add the railties' initializers to it.
-
-h3. Engine Initializers
-
-The third line in this +initializers+ method:
-
-<ruby>
- initializers += super
-</ruby>
-
-The +super+ method it's referring to is of course +Rails::Engine.initializers+, which isn't defined on the class but, as we have seen before, is defined on the +Rails::Railtie+ class it inherits from through the +Rails::Initializable+ module. Therefore we can determine the initializers to be added are now the ones defined in +Rails::Engine+.
-
-h3. Finisher Initializers
-
-The final set of initializers in this chain are those in +Rails::Finisher+. This involves running any after initialize code, building the middleware stack and adding the route for _rails/info/properties_.
-
-h3. Running the Initializers
-
-Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+:
-
-<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
+ def inherited(base)
+ unless base.abstract_railtie?
+ base.send(:include, Railtie::Configurable)
+ subclasses << base
end
- @ran = true
end
</ruby>
-Now we finally have all the +initializers+ we can go through them and call +run+:
+This first checks if the Railtie that's inheriting it is a component of Rails itself:
<ruby>
- def run(*args)
- @context.instance_exec(*args, &block)
- end
-</ruby>
-
-You may remember that the +@context+ in this code is +YourApp::Application+ and calling +instance_exec+ on this class will make a new instance of it and execute the code within the +&block+ passed to it. This code within the block is the code from all the initializers.
+ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
-h3. Bootstrap Initializers
-
-These initializers are the very first initializers that will be used to get your application going.
-
-h4. +load_environment_config+
-
-<ruby>
- initializer :load_environment_config do
- require_environment!
- end
-</ruby>
+...
-This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+:
-
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
-</ruby>
-
-We've seen +config.paths+ before when loading the plugins and they're explained in more detail in the Bonus section at the end of this guide. +config.enviroment+ for +paths+ is defined like this:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
-</ruby>
-
-+Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required:
-
-<ruby>
-module Rails
- class << self
-
- ...
-
- def env
- @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
- end
-
- ...
-
- end
+def abstract_railtie?
+ ABSTRACT_RAILTIES.include?(name)
end
</ruby>
-With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+.
-
-Therefore the path to this config file line would look like this with a substitution made:
+Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array.
<ruby>
- paths.config.environment "config/environments", :glob => "development.rb"
-</ruby>
-
-This method returns a +Path+ object (which acts as an +Enumerable+).
-
-Back to +require_environment+ now:
-
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
+def subclasses
+ @subclasses ||= []
+end
</ruby>
-And we've determined that +config.paths.config.environment+ is +Path+ object, and calling +to_a+ on that object calls +paths+ because it's +alias+'d at the bottom of the +Path+ class definition:
-<ruby>
- alias to_a paths
-</ruby>
+The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this:
<ruby>
- def paths
- raise "You need to set a path root" unless @root.path
- result = @paths.map do |p|
- path = File.expand_path(p, @root.path)
- @glob ? Dir[File.join(path, @glob)] : path
- end
- result.flatten!
- result.uniq!
- result
+ def config
+ @config ||= Railtie::Configuration.new
end
</ruby>
-This returns an array of files according to our +path+ and +@glob+ which are +config/environments+ and +development.rb+ respectively, therefore we can determine that:
-
-<ruby>
- Dir[File.join(path, @glob)]
-</ruby>
-
-will return an +Array+ containing one element, +"config/enviroments/development.rb"+. Of course when we call +first+ on this Array we'll get the first element and because that exists, we now +require "config/environments/development.rb"+.
-
-This file contains the following by default:
+At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+:
<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
-
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
- end
+ autoload :Configuration, "rails/railtie/configuration"
</ruby>
-This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+:
-
-<ruby>
- alias :configure :class_eval
-</ruby>
+h4. +railties/lib/rails/railtie/configuration.rb+
-therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+.
+This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again.
-The +config+ object here is the same one that was set up when _config/application.rb_ was loaded, therefore the methods called in this object will fall to the +method_missing+ defined in +Rails::Configuration::Shared+:
+This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+:
<ruby>
def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
+ if name.to_s =~ /=$/
+ @@options[$`.to_sym] = args.first
+ elsif @@options.key?(name)
+ @@options[name]
+ else
+ super
end
- super
- end
-</ruby>
-
-This time we are using methods ending in +\=+, so it will set the key in the +options+ to be the value specified. The first couple of options, +cache_classes+, +whiny_nils+, +consider_all_requests_local+ are just simple keys on the +options+. If you recall how options were setup then you may be able to work out how the remaining +action_view+, +action_controller+ and +action_mailer+ methods work.
-
-Firstly, we'll cover how +config_key_regexp+ is defined:
-
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
-
-And also +config_keys+:
-
-<ruby>
- def config_keys
- (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq
end
</ruby>
-+config_keys+ in here returns:
+So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there.
-<ruby>
- [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit]
-</ruby>
-
-With all of those keys coming from +Railtie::railtie_names+. If you've elected to not load some of the frameworks here they won't be available as configuration keys, so you'll need to remove them too.
-
-Now a reminder of how the +options+ key is defined:
-
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
+h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+
-The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this:
+After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+.
<ruby>
- module ActiveSupport #:nodoc:
- class OrderedOptions < OrderedHash
- def []=(key, value)
- super(key.to_sym, value)
- end
-
- def [](key)
- super(key.to_sym)
- end
-
- def method_missing(name, *args)
- if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
- else
- self[name]
- end
- end
+ initializer "i18n.callbacks" do
+ ActionDispatch::Reloader.to_prepare do
+ I18n::Railtie.reloader.execute_if_updated
end
end
</ruby>
-We can determine when we call +config.action_view.debug_rjs+ it's falling back to the +method_missing+ defined on +ActiveSupport::OrderedOptions+, which ends up either setting or retrieving a key. In this case because we're using a setter, it will set the key for this hash. This completes the loading of _config/environments/development.rb_.
-
-h4. +load_all_active_support+
-
-This initializer does exactly what it says:
+The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on:
<ruby>
- initializer :load_all_active_support do
- require "active_support/all" unless config.active_support.bare
+ def initializer(name, opts = {}, &blk)
+ raise ArgumentError, "A block must be passed when defining an initializer" unless blk
+ opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
+ initializers << Initializer.new(name, nil, opts, &blk)
end
</ruby>
-If you don't want this to happen you can specify the +config.active_support.bare+ option to +true+ in either _config/application.rb_ or any of your environment files.
-
-h4. +preload_frameworks+
+An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer].
-Remember earlier how we had all that stuff +eager_autoload+'d for Active Support?
+The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables:
<ruby>
- initializer :preload_frameworks do
- require 'active_support/dependencies'
- ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
+ def initialize(name, context, options, &block)
+ @name, @context, @options, @block = name, context, options, block
end
</ruby>
-This is where it gets loaded. The +eager_autoload!+ method is defined like this:
+Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns:
<ruby>
- def self.eager_autoload!
- @@autoloads.values.each { |file| require file }
+ def initializers
+ @initializers ||= self.class.initializers_for(self)
end
</ruby>
-With +@@autoloads+ being
-
-
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
-
-h4. Active Support Initializers
-
-Active Support
-
-**Active Support Initializers**
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-**I18n Initializers**
-
-* i18n.initialize
-
-The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail.
-
-**Action Dispatch Initializers**
-
-* action_dispatch.prepare_dispatcher
-
-**Action Controller Initializers**
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-
-**Active Record Initializers**
-
-* active_record.initialize_time_zone
-* active_record.logger
-* active_record.set_configs
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-**Action View Initializers **
-
-* action_view.cache_asset_ids
-
-**Action Mailer Initializers **
-
-* action_mailer.logger
-* action_mailer.set_configs
-* action_mailer.url_for
-
-**Active Resource Initializers**
-
-* active_resource.set_configs
-
-**Rails::Engine Initializers**
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-
-
-h4. +Rails::Engine.new+
-
-The +new+ method doesn't exist, but in Ruby classes calling +new+ on the class instantiates a new instance of that class and calls the instance method +initialize+ on it. This method for +Rails::Application+ goes like this:
-
-<ruby>
- def initialize
- require_environment
- Rails.application ||= self
- @route_configuration_files = []
- end
-</ruby>
-
-h4. +Rails::Application#require_environment+
-
-This is not a crafty method like the previous ones, it just does as it says on the box:
+If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class.
<ruby>
- def require_environment
- require config.environment_path
- rescue LoadError
+ def initializers_for(binding)
+ Collection.new(initializers_chain.map { |i| i.bind(binding) })
end
</ruby>
-The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+:
-
-<ruby>
- delegate :config, :routes, :to => :'self.class'
-</ruby>
-
-So the method call is actually +self.class.config+.
+The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in.
+The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this:
-h4. +Rails::Application.config+
-
-Defined back inside the +class << self+ for +Rails::Application+, +config+ makes a new +Rails::Application::Configuration+ object and caches it in a variable called +@config+:
-
-<ruby>
- def config
- @config ||= Configuration.new(Plugin::Configuration.default)
+<rub>
+ def initializers_chain
+ initializers = Collection.new
+ ancestors.reverse_each do | klass |
+ next unless klass.respond_to?(:initializers)
+ initializers = initializers + klass.initializers
+ end
+ initializers
end
</ruby>
-h4. +Rails::Plugin::Configuration.default+
-
-The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first, but if you look for _plugin.rb_ in Rails, you'll find it in _railties/lib/rails/plugin.rb_. In this file, we see the following:
+This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the <tt>+</tt> method which is defined like this for the <tt>Collection</tt> class:
<ruby>
- module Rails
- class Plugin < Engine
- ...
- end
+ def +(other)
+ Collection.new(to_a + other.to_a)
end
</ruby>
-So we note here that +Rails::Plugin+ descends from +Rails::Railtie+ and secondly we note that the class +Configuration+ is not actually included in the +Plugin+ class, but it **is** in the +Railtie+ class!
-
-h4. +Rails::Railtie::Configuration+
+So this <tt>+</tt> method is overriden to return a new collection comprising of the existing collection as an array and then using the <tt>Array#+</tt> method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer.
-We've now tracked down the +Plugin::Configuration.default+ method to being +Railtie::Configuration.default+, which is defined like this in _railties/lib/rails/configuration.rb_:
+The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this:
<ruby>
- class Railtie::Configuration
- def self.default
- @default ||= new
- end
- ...
+ def after_initialize(&block)
+ ActiveSupport.on_load(:after_initialize, :yield => true, &block)
end
</ruby>
-In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why.
-
-h4. +Rails::Application::Configuration.new+
-
-TODO: CLEAN THIS UP! This subclassing is only temporary and will probably not be separate in Rails 3. This is based solely off what the comment at the top of the Railtie::Configuration class says!
-
-The first thing to note here is that this class is subclassed from +Railtie::Configuration+ and therefore the method here is actually +Railtie::Configuration.new+. As mentioned previously, calling +new+ will make a new object of this class and then call +initialize+ on it, which is defined like this:
+The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this:
<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
+ def self.on_load(name, options = {}, &block)
+ if base = @loaded[name]
+ execute_hook(base, options, block)
else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
+ @load_hooks[name] << [block, options]
end
end
</ruby>
-This method is not called with a +base+ argument for +Plugin::Configuration.default+ but it is for the +Configuration.new+ wrapped around it. We'll go for the internal one first, since that's the order Rails loads them in.
-
-h4. +default_middleware_stack+
-
-This method is defined like this:
+The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+:
<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency })
- middleware.use('::Rack::Runtime')
- middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local })
- middleware.use('ActionDispatch::Notifications')
- middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
- middleware.use('ActionDispatch::Cookies')
- middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
- middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
- middleware.use('ActionDispatch::ParamsParser')
- middleware.use('::Rack::MethodOverride')
- middleware.use('::ActionDispatch::Head')
- end
- end
+ @load_hooks = Hash.new {|h,k| h[k] = [] }
</ruby>
-To really understand this method we need to dig a little deeper, down into where +ActionDispatch::MiddlewareStack.new+ is defined and what in particular it does for us.
-
-h4. +ActionDispatch::MiddlewareStack.new+
-
-+ActionDispatch+ is our first foray outside of the +railties+ gem, as this is actually defined in the +actionpack+ part of Rails. The class definition is as important as the method:
+This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead:
<ruby>
- module ActionDispatch
- class MiddlewareStack < Array
-
- ...
-
- def initialize(*args, &block)
- super(*args)
- block.call(self) if block_given?
- end
- end
- end
+ @load_hooks[name] = []
+ @load_hooks[name] << [block, options]
</ruby>
-When it's calling +super+ here it's actually calling +initialize+ on the Array class and from this we can determine that an +ActionDispatch::MiddlewareStack+ object is just an +Array+ object with special powers. One of those special powers is the ability to take a block, and +call+ it with +self+, meaning the block's parameter is the object itself!
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Previously we saw a chunk of code that I'll re-show you stripped down:
+The value added to this array here consists of the block and options passed to +after_initialize+.
-<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- ...
- end
- end
-</ruby>
+We'll see these +@load_hooks+ used later on in the initialization process.
-As explained in the previous section, we know that the +new+ on +ActionDispatch::MiddlewareStack+ takes a block and that block has one parameter which is the object itself. On this object we call the +use+ method to include middleware into our application. The use method simply does this:
+This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+.
-<ruby>
- def use(*args, &block)
- middleware = Middleware.new(*args, &block)
- push(middleware)
- end
-</ruby>
+h4. Back to +activesupport/lib/active_support/railtie.rb+
-We'll come back to this method later on.
+This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support.
-h4. +ActionController::Middleware.new+
+Then this Railtie sets up three more initializers:
-This +initialize+ method also is in a class who's ancestry is important so once again I'll show the ancestry and we'll go up that particular chain:
+* +active_support.initialize_whiny_nils+
+* +active_support.deprecation_behavior+
+* +active_support.initialize_time_zone+
-<ruby>
- module ActionController
- class Middleware < Metal
+We will cover what each of these initializers do when they run.
- ...
+Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+.
- def initialize(app)
- super()
- @_app = app
- end
- end
- end
-</ruby>
+h4. +activesupport/lib/action_dispatch/railtie.rb+
-Here our method calls +super+ but with a difference: it's passing in no arguments intentionally by putting the two brackets at the end. The method called here is therefore +ActionController::Metal.initialize+.
+This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+.
-h4. +ActionController::Metal.initialize+
+h4. +activesupport/lib/action_dispatch.rb+
-This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means:
+This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are.
<ruby>
- class Metal < AbstractController::Base
-
- ...
-
- def initialize(*)
- @_headers = {}
- super
- end
- end
-</ruby>
-
-The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are.
-
-h4. +AbstractController::Base.initialize+
-
-This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object:
-
-<ruby>
- # Initialize controller with nil formats.
- def initialize #:nodoc:
- @_formats = nil
- end
-</ruby>
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Now we're back to this method, from our foray into the depths of how +Middleware.new+ works, we've showed that it is an instance of +AbstractController::Base+. Therefore it does
-
-TODO: ELABORATE ON THIS SECTION, including explaining what all the pieces of middleware do. Then explain how the default_middleware_stack does what it does, whatever that is.
-
-h4. Back to +Rails::Application::Configuration.new+
-
-Now that the first call to this method is complete (+Plugin::Configuration.default+), we can move onto the second call. Here's a refresher of what this method does:
+ activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
+ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
- else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
- end
- end
+ activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
+ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
</ruby>
-You'll note now that this method is being called now is +Configuration.new(Plugin::Configuration.default)+ and with the argument, it's going to perform differently than before, this time duplicating the +options+ and +middleware+ of the object it was passed.
-
-TODO: Find out what purpose the +@options+ and +@middleware+ variables serve.
-
-Finally, a +Rails::Application::Configuration+ object will be returned. On this class there are a couple of +attr_accessor+s and +attr_writer+s defined:
-
-<ruby>
- attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging,
- :consider_all_requests_local, :dependency_loading,
- :load_once_paths, :logger, :plugins,
- :preload_frameworks, :reload_plugins, :serve_static_assets,
- :time_zone, :whiny_nils
-
- attr_writer :cache_store, :controller_paths,
- :database_configuration_file, :eager_load_paths,
- :i18n, :load_paths, :log_level, :log_path, :paths,
- :routes_configuration_file, :view_path
-</ruby>
+In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more.
-Along with these are a lot of helper methods, and one of them is +environment_path+:
+The next two requires in this file are already done, so they are not run:
<ruby>
- def environment_path
- "#{root}/config/environments/#{Rails.env}.rb"
- end
+ require 'active_support'
+ require 'active_support/dependencies/autoload'
</ruby>
-h4. Back to +Rails::Application#require_environment+
-
-Now that we have a +Rails::Application::Configuration+ object for the +config+ method, we call the +environment_path+ which, as we've seen above, just requires the current environment file which in this case is _config/environments/development.rb_. If this file cannot be found, the +LoadError+ +require+ throws will be +rescue+'d and Rails will continue on its merry way.
-
-h4. _config/environments/development.rb_
-
-In a standard Rails application we have this in our _config/environments/development.rb_ file:
+The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant:
<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.action_controller.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
+ module ActionPack
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
+ end
end
</ruby>
-It's a little bit sneaky here, but +configure+ is +alias+'d to +class_eval+ on subclasses of +Rails::Application+ which of course includes +YourApp::Application+. This means that the code inside the +configure do+ block will be evaled within the context of +YourApp::Application+. The +config+ method here is the one mentioned before: the +Rails::Application::Configuration+ object. The methods on it should look familiar too: they're the ones that had +attr_accessor+ and +attr_writer+ definitions.
-
-The ones down the bottom, +config.action_controller+, +config.action_view+ and +config.action_mailer+ aren't defined by +attr_accessor+ or +attr_writer+, rather they're undefined methods and therefore will trigger the +method_missing+ on the +Rails::Application::Configuration+ option.
-
-h5. config.cache_classes=
-
-The first method call in this file, this tells Rails to not cache the classes for every request. This means for every single request Rails will reload the classes of your application. If you have a lot of classes, this will slow down the request cycle of your application. This is set to +false+ in the _development_ environment, and +true+ in the _test_ & _production_ environments.
+Once +action_pack+ is finished, then +active_model+ is required.
-h5. config.whiny_nils=
+h4. +activemodel/lib/active_model.rb+
-If this is set to +true+, like it is here in the _development_ environment, _activesupport/whiny_nil_ will be +require+'d. Have you ever seen this error:
+This file makes a require to +active_model/version+ which defines the version for Active Model:
<ruby>
- Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
-</ruby>
-
-Or perhaps this one?
-
-<ruby>
- You have a nil object when you didn't expect it!
- You might have expected an instance of Array.
- The error occurred while evaluating nil.flatten!
-</ruby>
-
-If you have, then this is _activesupport/whiny_nil_ at work.
-
-
-h5. The frameworks
-
-As mentioned before, the methods +action_controller+, +action_view+ and +action_mailer+ aren't defined on the +Rails::Application::Configuration+ object, rather they are caught by +method_missing+ which does this:
+ module ActiveModel
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? @options[$1] = args.first : @options[$1]
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
-
- super
end
</ruby>
-Whilst this code is not obvious at first, a little bit of further explanation will help you understand. +config_key_regexp+ is another method (a private one, like +method_missing+) defined here:
+Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required.
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
+h4. +activesupport/lib/active_support/i18n.rb+
-As is +config_keys+:
+This is where the +i18n+ gem is required and first configured:
<ruby>
- def config_keys
- ([ :active_support, :action_view ] +
- Railtie.plugin_names).map { |n| n.to_s }.uniq
+ begin
+ require 'i18n'
+ require 'active_support/lazy_load_hooks'
+ rescue LoadError => e
+ $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
end
-</ruby>
-
-Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks.
-
-h5. +Railtie.plugin_names+
-I'm going to show you two methods since the third one, +self.plugin_name+, calls the second one, +self.plugins+ and they're right after each other:
-
-<ruby>
- module Rails
- class Railtie
- def self.inherited(klass)
- @plugins ||= []
- @plugins << klass unless klass == Plugin
- end
-
- def self.plugins
- @plugins
- end
-
- def self.plugin_names
- plugins.map { |p| p.plugin_name }
- end
- end
- end
+ I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
</ruby>
-In here we see that we get the +plugin_names+ from a variable called +@plugins+... which we haven't seen yet. Through the power of the wonderful +inherited+ the +@plugins+ variable is populated. +inherited+ is called when a class inherits, or subclasses, from this class. Therefore we can determine that the other classes are probably inheriting or subclassing from +Rails::Railtie+.
-
-h3. Serving a Request
-
-Now that your application is fully initialized, it's now ready to start serving requests.
-
-h4. _rails server_
-
-For servers running through _rails server_ you may recall that this uses +Rails::Server+ which is a subclass of +Rack::Server+. Previously we covered the initialization process of Rack but not completely up to the point where the server was running. Now that's what we'll do. Back when the +Rack::Server+ class was first covered there was a mention of the +start+ method which we only touched on. It goes a little like this:
-
-<ruby>
- def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-
- if options[:warn]
- $-w = true
- end
+In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way.
- if includes = options[:include]
- $LOAD_PATH.unshift *includes
- end
+This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again.
- if library = options[:require]
- require library
- end
+If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded.
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
-</ruby>
+Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from.
-We were at the point of explaining what +wrapped_app+ was before we dived into the Rails initialization process.Now that we have a +wrapped_app+ we pass it as the first argument to +server.run+. +server+ in this instance is defined like this:
+The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+.
-<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
-</ruby>
+h4. Back to +activesupport/lib/action_dispatch.rb+
-Our +options+ Hash is still the default, and there is no +server+ key set in +default_options+, so it will default to +Rack::Handler.default+. This code works like this:
+The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
+ autoload_under 'testing' do
+ autoload :Assertions
+ ...
</ruby>
+The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+.
-We don't have +PHP_FCGI_CHILDREN+ in our +ENV+, so it's not going to be +FastCGI+. We also don't have +REQUEST_METHOD+ in there, so it's not going to be +CGI+. If we have Mongrel installed it'll default to that and then finally it'll use WEBrick. For this, we'll assume a bare-bones installation and assume WEBrick. So from this we can determine our default handler is +Rack::Handler::WEBrick+.
-
-(side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?)
-
-h5. +Rack::Handler::WEBrick+
+Finally, this file defines a top-level autoload, the +Mime+ constant.
-This class is subclassed from +WEBrick::HTTPServlet::AbstractServlet+ which is a class that comes with the Ruby standard library. This is the magical class that serves the requests and deals with the comings (requests) and goings (responses) for your server.
+h4. Back to +activesupport/lib/action_dispatch/railtie.rb+
+After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+.
-+Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is
+With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+.
-h3. Cruft!
+h4. Back to +railties/lib/rails.rb+
-The final line of _config/environment.rb_:
-
-<ruby>
- YourApp::Application.initialize!
-</ruby>
+With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+.
-gets down to actually initializing the application!
+h4. Back to +railties/lib/rails/all.rb+
-TODO: Cover the other +config.*+ methods in perhaps a "Bonus" section near the end. If they aren't referenced in a config file they aren't that important, right?
+Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+.
+h4. +activerecord/lib/active_record/railtie.rb+
-TODO: This belongs in the guide, I just don't know where yet. Maybe towards the end, since this is really the "final" thing to be done before being able to serve requests.
+Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+.
-<ruby>
- def build_app(app)
- middleware[options[:environment]].reverse_each do |middleware|
- middleware = middleware.call(self) if middleware.respond_to?(:call)
- next unless middleware
- klass = middleware.shift
- app = klass.new(app, *middleware)
- end
- app
- end
-</ruby>
+h4. +activerecord/lib/active_record.rb+
-Because we don't have any middleware for our application, this returns the application itself( Guessing here!! TODO: Investigate if this is really the case.)
+This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there.
-Now that we have an app instance, the last line in +start+ calls +server.run wrapped_app, options+. We know what our app is, and that our options are just the default options, so what is +server+? +server+ is this:
+The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module.
<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
+ require 'active_support'
+ require 'active_support/i18n'
+ require 'active_model'
+ require 'arel'
</ruby>
-Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this:
+The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
-</ruby>
-
-h3. +Rails::Paths+
-
-
-The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths:
+ module ActiveRecord
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.views "app/views"
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
</ruby>
-h3. Appendix A
-
-This file is _activesupport/lib/active_support/inflector/inflections.rb_ and defines the +ActiveSupport::Inflector::Inflections+ class which defines the +singularize+, +pluralize+, +humanize+, +tableize+, +titleize+ and +classify+ methods as well as the code to defining how to work out the irregular, singular, plural and human versions of words. These methods are called +irregular+, +singular+, +plural+ and +human+ respectively, as is the Rails way.
-
-This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+.
+Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads.
-This file first requires _activesupport/lib/active_support/core_ext/string/multibyte.rb_, which requires _activesupport/lib/active_support/multibyte.rb_, which subsequently requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is needed to gain access to the +mattr_accessor+ (module attribute accessor) method, which is called in _active_suport/multibyte.rb_. The file _active_support/multibyte.rb_ also autoloads three other classes:
+Near the end of the file, we see this line:
<ruby>
-module ActiveSupport #:nodoc:
- module Multibyte
- autoload :EncodingError, 'active_support/multibyte/exceptions'
- autoload :Chars, 'active_support/multibyte/chars'
- autoload :Unicode, 'active_support/multibyte/unicode'
- ...
+ ActiveSupport.on_load(:active_record) do
+ Arel::Table.engine = self
end
-end
</ruby>
-There are also these method definitions:
-
-<ruby>
- # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
- # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
- # an example how to do this.
- #
- # Example:
- # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
- def self.proxy_class=(klass)
- @proxy_class = klass
- end
-
- # Returns the currect proxy class
- def self.proxy_class
- @proxy_class ||= ActiveSupport::Multibyte::Chars
- end
-</ruby>
+This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+.
-These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_.
-
-The file _activesupport/lib/active_support/core_ext/string/chars.rb_ defines the default proxy class that will be returned by +mb_chars+.
-
-Because Ruby 1.9's +String+ class has support for multibyte encodings, some methods are defined only for Ruby 1.8:
-
-* +self.wants?+
-* +++
-* +=~+
-* +=~+
-* +center+
-* +include?+
-* +index+
-* +insert+
-* +ljust+
-* +lstrip+, +lstrip!+
-* +ord+
-* +rindex+
-* +rjust+
-* +rstrip+, +rstrip!+
-* +size+
-* +strip+, +strip!+
-
-However, Ruby 1.9 lacks support for some needed operations, so the following methods are defined for both Ruby 1.8 and Ruby 1.9:
-
-* +<=>+
-* +[]=+
-* +capitalize+, +capitalize!+
-* +compose+
-* +decompose+
-* +downcase+, +downcase!+
-* +g_length+
-* +limit+
-* +normalize+
-* +reverse+, +reverse+!
-* +slice+, +slice!+
-* +split+
-* +tidy_bytes+, +tidy_bytes!+
-* +titleize+
-* +upcase+, +upcase!+
+The file then finishes with this line:
<ruby>
- class String
- if RUBY_VERSION >= "1.9"
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.consumes?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- def is_utf8? #:nodoc
- case encoding
- when Encoding::UTF_8
- valid_encoding?
- when Encoding::ASCII_8BIT, Encoding::US_ASCII
- dup.force_encoding(Encoding::UTF_8).valid_encoding?
- else
- false
- end
- end
- else
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.wants?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have
- # them), returns false otherwise.
- def is_utf8?
- ActiveSupport::Multibyte::Chars.consumes?(self)
- end
- end
+ I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
</ruby>
-As you can see, +mb_chars+ is where the +proxy_class+ property comes in handy. This method will create a new instance of the configured proxy class using the instance of +String+ as a constructor argument. By default, the new +String+-like object will be an instance of the proxy class +ActiveSupport::Multibyte::Chars+. You can use +ActiveSupport::Multibyte.proxy_class=+ to set a different proxy class if you wish.
-
-Here, +mb_chars+ invokes +is_utf8?+ to checks if the string can be treated as UTF-8. On 1.9, the string's +encoding+ property is checked. On 1.8, +wants?+ checks to see if +$KCODE+ is "UTF-8" and, and +consumes?+ checks whether the string can be unpacked as UTF-8 without raising an error.
-
-The keen eye will have seen +ActiveSupport::Multibyte::Chars+ was specified as an +autoload+ earlier: _activesupport/lib/active_support/multibyte/chars.rb_ will be loaded without an explicit +require+ when we call +is_utf8+ on 1.8, or +mb_chars+ on any Ruby version. This file includes _activesupport/lib/active_support/string/access.rb_ which defines methods such as +at+, +from+, +to+, +first+ and +last+. These methods will return parts of the string depending on what is passed to them.
+This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded.
-The second file included is _activesupport/lib/active_support/string/behavior.rb_ which only defines +acts_like_string?+ on +String+, a method which always returns +true+. This method is used by +Object#acts_like?+, which accepts a single argument representing the downcased and symbolised version of a class, and returns true if the object's behavior is like that class. In this case the code would be +acts_like?(:string)+.
+h4. Back to +activerecord/lib/active_record/railtie.rb+
-The +Chars+ class also defines other important methods such as the "spaceship" method +<=>+, which is needed by the +Comparable+ module, in order to allow UTF-8-aware sorting.
-
-h3. Common Includes
-
-TODO: I feel this section would be better at the end of the guide as it breaks the flow.
-
-This section is for all the common includes in the Railties.
-
-h4. +require 'active_support/inflector'+
-
-This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place:
+The next two <tt>require</tt>s in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+.
<ruby>
- require 'active_support/inflector/inflections'
- require 'active_support/inflector/transliterate'
- require 'active_support/inflector/methods'
-
- require 'active_support/inflections'
- require 'active_support/core_ext/string/inflections'
+ require "rails"
+ require "active_model/railtie"
</ruby>
-The files included here define methods for modifying strings, such as +transliterate+ which will convert a Unicode string to its ASCII version, +parameterize+ for making strings into url-safe versions, +camelize+ for camel-casing a string such as +string_other+ into +StringOther+ and +ordinalize+ converting a string such as +101+ into +101st+. More information about these methods can be found in the Active Support Core Extensions Guide. TODO: Link to AS Guide.
-
-h4. +require 'active_support/core_ext/module/delegation'+
-
-_activesupport/lib/active_support/core_ext/module/delegation.rb_ defines the +delegate+ method which can be used to delegate methods to other methods in your code. Take the following code example:
+The next +require+ in this file is to +action_controller/railtie+.
-<ruby>
- class Client < ActiveRecord::Base
- has_one :address
-
- delegate :address_line_1, :to => :address
- end
-</ruby>
+h4. +actionpack/lib/action_controller/railtie.rb+
-This defines an +address_line_1+ method which is defined as:
+This file begins with a couple more requires to files that have already been loaded:
<ruby>
- def address_line_1(*args, &block)
- address.__send__(:address_line_1, *args, &block)
- rescue NoMethodError
- if address.nil?
- raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}"
- end
- end
+ require "rails"
+ require "action_controller"
+ require "action_dispatch/railtie"
</ruby>
-h4. +require 'active_support/core_ext/class/attribute_accessors'+
-
-The file, _activesupport/lib/active_support/core_ext/class/attribute_accessors.rb_, defines the class accessor methods +cattr_writer+, +cattr_reader+ and +cattr_accessor+. +cattr_accessor+ defines a +cattr_reader+ and +cattr_writer+ for the symbol passed in. These methods work by defining class variables when you call their dynamic methods.
-
-Throughout the Railties there a couple of common includes. They are listed here for your convenience.
-
-h4. +require 'active_support/core_ext/module/attr_internal+
-
-This file defines three methods +attr_internal_reader+, +attr_internal_writer+ and +attr_internal_accessor+. These work very similar to the +attr_reader+, +attr_writer+ and +attr_accessor+ methods, except the variables they define begin with +@_+. This was done to ensure that they do not clash with variables used people using Rails, as people are less-likely to define say, +@_request+ than they are to define +@request+. An example of where this method is used is for +params+ in the +ActionController::Metal+ class.
-
-h4. +require 'active_support/ruby/shim'+
-
-The _activesupport/lib/active_support/ruby/shim.rb_ file requires methods that have been implemented in Ruby versions greater than 1.9. This is done so you can use Rails 3 on versions earlier than 1.9, such as 1.8.7. These methods are:
-
-* +Date#next_month+
-* +Date#next_year+
-* +DateTime#to_date+
-* +DateTime#to_datetime+
-* +DateTime#xmlschema+
-* +Enumerable#group_by+
-* +Enumerable#each_with_object+
-* +Enumerable#none?+
-* +Process#daemon+
-* +String#ord+
-* +Time#to_date+
-* +Time.to_time+
-* +Time.to_datetime+
+However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+.
-For more information see the Active Support Core Extensions guide TODO: link to relevant sections for each method.
+h4. +actionpack/lib/action_view.rb+
-And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml]
++action_view.rb+
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
index bb62506f04..e924f2f6c0 100644
--- a/railties/guides/source/layout.html.erb
+++ b/railties/guides/source/layout.html.erb
@@ -12,6 +12,8 @@
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
+
+<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
</head>
<body class="guide">
<% if @edge %>
@@ -75,8 +77,8 @@
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
- <dt>Contributing to Rails</dt>
- <dd><a href="contributing_to_rails.html">Contributing to Rails</a></dd>
+ <dt>Contributing to Ruby on Rails</dt>
+ <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
@@ -106,14 +108,14 @@
<div class="wrapper">
<div id="mainCol">
<%= yield.html_safe %>
-
+
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
- patch please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
+ patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is
@@ -123,10 +125,10 @@
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %>
- guide for style and conventions.
+ for style and conventions.
</p>
<p>
- Issues may also be reported <%= link_to 'in Github', 'https://github.com/lifo/docrails/issues' %>.
+ Issues may also be reported in <%= link_to 'Github', 'https://github.com/lifo/docrails/issues' %>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <%= link_to 'rubyonrails-docs mailing list', 'http://groups.google.com/group/rubyonrails-docs' %>.
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index 80a1fdd38d..1548da0eb5 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -106,10 +106,10 @@ Perhaps the simplest thing you can do with +render+ is to render nothing at all:
render :nothing => true
</ruby>
-If you look at the response for this using Curl you will see the following:
+If you look at the response for this using cURL, you will see the following:
<shell>
- $ curl -i 127.0.0.1:3000/books
+$ curl -i 127.0.0.1:3000/books
HTTP/1.1 200 OK
Connection: close
Date: Sun, 24 Jan 2010 09:25:18 GMT
@@ -123,7 +123,7 @@ Cache-Control: no-cache
$
</shell>
-We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ options on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed.
+We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ option on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed.
TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
@@ -211,7 +211,7 @@ h5. Wrapping it up
The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
-In fact, in the BooksController class, inside of the edit action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
+In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
<ruby>
render :edit
@@ -339,14 +339,14 @@ render :layout => false
h6. The +:status+ Option
-Rails will automatically generate a response with the correct HTML status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
+Rails will automatically generate a response with the correct HTTP status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
<ruby>
render :status => 500
render :status => :forbidden
</ruby>
-Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in +actionpack/lib/action_controller/status_codes.rb+. You can also see there how Rails maps symbols to status codes.
+Rails understands both numeric status codes and symbols for status codes.
h6. The +:location+ Option
@@ -604,7 +604,7 @@ Which would detect that there are no books, populate the +@books+ instance varia
h4. Using +head+ To Build Header-Only Responses
-The +head+ method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:
+The +head+ method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header:
<ruby>
head :bad_request
@@ -651,11 +651,9 @@ When Rails renders a view as a response, it does so by combining the view with t
* +yield+ and +content_for+
* Partials
-I'll discuss each of these in turn.
-
h4. Asset Tags
-Asset tags provide methods for generating HTML that links views to assets like images, videos, audio, JavaScript, stylesheets, and feeds. There are six types of include tag:
+Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails:
* +auto_discovery_link_tag+
* +javascript_include_tag+
@@ -680,10 +678,10 @@ The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsread
There are three tag options available for +auto_discovery_link_tag+:
* +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
-* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically
+* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
* +:title+ specifies the title of the link
-h5. Linking to Javascript Files with +javascript_include_tag+
+h5. Linking to JavaScript Files with +javascript_include_tag+
The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
@@ -829,7 +827,7 @@ You can also supply an alternate image to show on mouseover:
<%= image_tag "home.gif", :onmouseover => "menu/home_highlight.gif" %>
</erb>
-Or alternate text if the user has rendering images turned off in their browser, if you do not specify an explicit alt tag, it defaults to the file name of the file, capitalized and with no extension, for example, these two image tags would return the same code:
+You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
<erb>
<%= image_tag "home.gif" %>
@@ -939,7 +937,7 @@ The main body of the view will always render into the unnamed +yield+. To render
h4. Using +content_for+
-The +content_for+ method allows you to insert content into a +yield+ block in your layout. You only use +content_for+ to insert content in named yields. For example, this view would work with the layout that you just saw:
+The +content_for+ method allows you to insert content into a named +yield+ block in your layout. For example, this view would work with the layout that you just saw:
<erb>
<% content_for :head do %>
@@ -966,7 +964,7 @@ The +content_for+ method is very helpful when your layout contains distinct regi
h4. Using Partials
-Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
+Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
h5. Naming Partials
@@ -1008,11 +1006,13 @@ h5. Partial Layouts
A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
<erb>
-<%= render "link_area", :layout => "graybar" %>
+<%= render :partial => "link_area", :layout => "graybar" %>
</erb>
This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder).
+Also note that explicitly specifying +:partial+ is required when passing additional options such as +:layout+.
+
h5. Passing Local Variables
You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
@@ -1086,15 +1086,13 @@ Partials are very useful in rendering collections. When you pass a collection to
When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered.
-In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+:
+In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+ to produce the same result:
<erb>
<h1>Products</h1>
<%= render @products %>
</erb>
-To produce the same result.
-
Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
* +index.html.erb+
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
index 0d13fbc10a..21784c5ba3 100644
--- a/railties/guides/source/migrations.textile
+++ b/railties/guides/source/migrations.textile
@@ -109,7 +109,7 @@ h4. Creating a Model
The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want then statements for adding those will also be created. For example, running
<shell>
-rails generate model Product name:string description:text
+$ rails generate model Product name:string description:text
</shell>
will create a migration that looks like this
@@ -139,7 +139,7 @@ h4. Creating a Standalone Migration
If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator:
<shell>
-rails generate migration AddPartNumberToProducts
+$ rails generate migration AddPartNumberToProducts
</shell>
This will create an empty but appropriately named migration:
@@ -157,7 +157,7 @@ end
If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate +add_column+ and +remove_column+ statements will be created.
<shell>
-rails generate migration AddPartNumberToProducts part_number:string
+$ rails generate migration AddPartNumberToProducts part_number:string
</shell>
will generate
@@ -177,7 +177,7 @@ end
Similarly,
<shell>
-rails generate migration RemovePartNumberFromProducts part_number:string
+$ rails generate migration RemovePartNumberFromProducts part_number:string
</shell>
generates
@@ -197,7 +197,7 @@ end
You are not limited to one magically generated column, for example
<shell>
-rails generate migration AddDetailsToProducts part_number:string price:decimal
+$ rails generate migration AddDetailsToProducts part_number:string price:decimal
</shell>
generates
@@ -383,7 +383,7 @@ If you specify a target version, Active Record will run the required migrations
version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run
<shell>
-rake db:migrate VERSION=20080906120000
+$ rake db:migrate VERSION=20080906120000
</shell>
If this is greater than the current version (i.e. it is migrating upwards) this will run the +up+ method on all migrations up to and including 20080906120000, if migrating downwards this will run the +down+ method on all the migrations down to, but not including, 20080906120000.
@@ -393,13 +393,13 @@ h4. Rolling Back
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
<shell>
-rake db:rollback
+$ rake db:rollback
</shell>
This will run the +down+ method from the latest migration. If you need to undo several migrations you can provide a +STEP+ parameter:
<shell>
-rake db:rollback STEP=3
+$ rake db:rollback STEP=3
</shell>
will run the +down+ method from the last 3 migrations.
@@ -407,7 +407,7 @@ will run the +down+ method from the last 3 migrations.
The +db:migrate:redo+ task is a shortcut for doing a rollback and then migrating back up again. As with the +db:rollback+ task you can use the +STEP+ parameter if you need to go more than one version back, for example
<shell>
-rake db:migrate:redo STEP=3
+$ rake db:migrate:redo STEP=3
</shell>
Neither of these Rake tasks do anything you could not do with +db:migrate+, they are simply more convenient since you do not need to explicitly specify the version to migrate to.
@@ -421,7 +421,7 @@ h4. Being Specific
If you need to run a specific migration up or down the +db:migrate:up+ and +db:migrate:down+ tasks will do that. Just specify the appropriate version and the corresponding migration will have its +up+ or +down+ method invoked, for example
<shell>
-rake db:migrate:up VERSION=20080906120000
+$ rake db:migrate:up VERSION=20080906120000
</shell>
will run the +up+ method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes that 20080906120000 has already been run.
diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile
index 1d44da4df1..55694c0eb4 100644
--- a/railties/guides/source/nested_model_forms.textile
+++ b/railties/guides/source/nested_model_forms.textile
@@ -1,6 +1,6 @@
h2. Rails nested model forms
-Creating a form for a model _and_ its associations can become quite tedious. Therefor Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
+Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
In this guide you will:
@@ -219,4 +219,4 @@ You can basically see the +projects_attributes+ hash as an array of attribute ha
NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep.
-TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example. \ No newline at end of file
+TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example.
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index 41bdd27e9b..32eebe863c 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -37,7 +37,7 @@ h4. Generating Performance Tests
Rails provides a generator called +test_unit:performance+ for creating new performance tests:
<shell>
-rails generate test_unit:performance homepage
+$ rails generate test_unit:performance homepage
</shell>
This generates +homepage_test.rb+ in the +test/performance+ directory:
@@ -60,8 +60,8 @@ Let's assume your application has the following controller and model:
<ruby>
# routes.rb
-map.root :controller => 'home'
-map.resources :posts
+root :to => 'home#index'
+resources :posts
# home_controller.rb
class HomeController < ApplicationController
@@ -316,16 +316,16 @@ Compile Ruby and apply this "GC Patch":http://rubyforge.org/tracker/download.php
h5. Download and Extract
<shell>
-[lifo@null ~]$ mkdir rubygc
-[lifo@null ~]$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby>
-[lifo@null ~]$ tar -xzvf <ruby-version.tar.gz>
-[lifo@null ~]$ cd <ruby-version>
+$ mkdir rubygc
+$ wget <download the latest stable ruby from ftp://ftp.ruby-lang.org/pub/ruby>
+$ tar -xzvf <ruby-version.tar.gz>
+$ cd <ruby-version>
</shell>
h5. Apply the Patch
<shell>
-[lifo@null ruby-version]$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
+$ curl http://rubyforge.org/tracker/download.php/1814/7062/17676/3291/ruby186gc.patch | patch -p0
</shell>
h5. Configure and Install
@@ -333,8 +333,8 @@ h5. 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.
<shell>
-[lifo@null ruby-version]$ ./configure --prefix=/<homedir>/rubygc
-[lifo@null ruby-version]$ make && make install
+$ ./configure --prefix=/<homedir>/rubygc
+$ make && make install
</shell>
h5. Prepare Aliases
@@ -364,8 +364,8 @@ Additionally, install the following gems:
If installing +mysql+ fails, you can try to install it manually:
<shell>
-[lifo@null mysql]$ gcruby extconf.rb --with-mysql-config
-[lifo@null mysql]$ make && make install
+$ gcruby extconf.rb --with-mysql-config
+$ make && make install
</shell>
And you're ready to go. Don't forget to use +gcruby+ and +gcrake+ aliases when running the performance tests.
@@ -398,7 +398,7 @@ $ rails benchmarker 'Item.first' 'Item.last'
h4. +profiler+
-+profiler+ is a wrapper around http://ruby-prof.rubyforge.org/[ruby-prof] gem.
++profiler+ is a wrapper around the "ruby-prof":http://ruby-prof.rubyforge.org gem.
Usage:
@@ -436,7 +436,7 @@ h4. Model
Project.benchmark("Creating project") do
project = Project.create("name" => "stuff")
project.create_manager("name" => "David")
- project.milestones << Milestone.find(:all)
+ project.milestones << Milestone.all
end
</ruby>
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index cb43282ace..daca50ee9e 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -10,274 +10,60 @@ After reading this guide you should be familiar with:
* Creating a plugin from scratch
* Writing and running tests for the plugin
-* Storing models, views, controllers, helpers and even other plugins in your plugins
-* Writing generators
-* Writing custom Rake tasks in your plugin
-* Generating RDoc documentation for your plugin
-* Avoiding common pitfalls with 'init.rb'
This guide describes how to build a test-driven plugin that will:
* Extend core ruby classes like Hash and String
* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
-* Add a view helper that can be used in erb templates
-* Add a new generator that will generate a migration
-* Add a custom generator command
-* A custom route method that can be used in routes.rb
+* Give you information about where to put generators in your plugin.
-For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
+For the purpose of this guide pretend for a moment that you are an avid bird watcher.
+Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle
+goodness.
endprologue.
h3. Setup
-h4. Create the Basic Application
+h4. Generating the Plugin Skeleton
-The examples in this guide require that you have a working rails application. To create a simple one execute:
+Rails currently ships with a generator to generate a plugin within a Rails application. Help text is available that will explain
+how this generator works.
<shell>
-gem install rails
-rails new yaffle_guide
-cd yaffle_guide
-bundle install
-rails generate scaffold bird name:string
-rake db:migrate
-rails server
+$ rails generate plugin --help
</shell>
-Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing.
+This generator places the plugin into the vendor/plugins directory.
-NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails application for other databases see the API docs.
+Vendored plugins are useful for quickly prototyping your plugin but current thinking in the Rails community is shifting towards
+packaging plugins as gems, especially with the inclusion of Bundler as the Rails dependency manager.
+Packaging a plugin as a gem may be overkill for any plugins that will not be shared across projects but doing so from the start makes it easier to share the plugin going forward without adding too much additional overhead during development.
-
-h4. Generate the Plugin Skeleton
-
-Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass +--generator+ to add an example generator also.
-
-This creates a plugin in +vendor/plugins+ including an +init.rb+ and +README+ as well as standard +lib+, +task+, and +test+ directories.
-
-Examples:
-<shell>
-rails generate plugin yaffle
-rails generate plugin yaffle --generator
-</shell>
-
-To get more detailed help on the plugin generator, type +rails generate plugin+.
-
-Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the +--generator+ option now:
-
-<shell>
-rails generate plugin yaffle --generator
-</shell>
-
-You should see the following output:
-
-<shell>
-create vendor/plugins/yaffle
-create vendor/plugins/yaffle/init.rb
-create vendor/plugins/yaffle/install.rb
-create vendor/plugins/yaffle/MIT-LICENSE
-create vendor/plugins/yaffle/Rakefile
-create vendor/plugins/yaffle/README
-create vendor/plugins/yaffle/uninstall.rb
-create vendor/plugins/yaffle/lib
-create vendor/plugins/yaffle/lib/yaffle.rb
-invoke generator
-inside vendor/plugins/yaffle
-create lib/generators
-create lib/generators/yaffle_generator.rb
-create lib/generators/USAGE
-create lib/generators/templates
-invoke test_unit
-inside vendor/plugins/yaffle
-create test
-create test/yaffle_test.rb
-create test/test_helper.rb
-</shell>
-
-h4. Organize Your Files
-
-To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:
+Rails 3.1 will ship with a plugin generator that will default to setting up a plugin
+as a gem. This tutorial will begin to bridge that gap by demonstrating how to create a gem based plugin using the
+"Enginex gem":http://www.github.com/josevalim/enginex.
<shell>
-|-- lib
-| |-- yaffle
-| `-- yaffle.rb
-`-- init.rb
+ gem install enginex
+ enginex --help
+ enginex yaffle
</shell>
-<ruby>
-# vendor/plugins/yaffle/init.rb
-
-require 'yaffle'
-</ruby>
-
-Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ clean.
-
-h3. Tests
-
-In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
-
- * A +database.yml+ file with all of your connection strings
- * A +schema.rb+ file with your table definitions
- * A test helper method that sets up the database
-
-h4. Test Setup
-
-<yaml>
-# vendor/plugins/yaffle/test/database.yml
-
-sqlite:
- adapter: sqlite
- database: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
-
-sqlite3:
- adapter: sqlite3
- database: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
-
-postgresql:
- adapter: postgresql
- username: postgres
- password: postgres
- database: yaffle_plugin_test
- min_messages: ERROR
-
-mysql:
- adapter: mysql
- host: localhost
- username: root
- password: password
- database: yaffle_plugin_test
-</yaml>
-
-For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
-
-<ruby>
-# vendor/plugins/yaffle/test/schema.rb
-
-ActiveRecord::Schema.define(:version => 0) do
- create_table :hickwalls, :force => true do |t|
- t.string :name
- t.string :last_squawk
- t.datetime :last_squawked_at
- end
- create_table :wickwalls, :force => true do |t|
- t.string :name
- t.string :last_tweet
- t.datetime :last_tweeted_at
- end
- create_table :woodpeckers, :force => true do |t|
- t.string :name
- end
-end
-</ruby>
-
-<ruby>
-# vendor/plugins/yaffle/test/test_helper.rb
-
-ENV['RAILS_ENV'] = 'test'
-ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
-
-require 'test/unit'
-require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
-
-def load_schema
- config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
- ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
-
- db_adapter = ENV['DB']
-
- # no db passed, try one of these fine config-free DBs before bombing.
- db_adapter ||=
- begin
- require 'rubygems'
- require 'sqlite'
- 'sqlite'
- rescue MissingSourceFile
- begin
- require 'sqlite3'
- 'sqlite3'
- rescue MissingSourceFile
- end
- end
-
- if db_adapter.nil?
- raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
- end
-
- ActiveRecord::Base.establish_connection(config[db_adapter])
- load(File.dirname(__FILE__) + "/schema.rb")
- require File.dirname(__FILE__) + '/../init'
-end
-</ruby>
-
-Now whenever you write a test that requires the database, you can call 'load_schema'.
-
-h4. Run the Plugin Tests
-
-Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in +vendor/plugins/yaffle/test/yaffle_test.rb+ with a sample test. Replace the contents of that file with:
-
-<ruby>
-# vendor/plugins/yaffle/test/yaffle_test.rb
-
-require 'test_helper'
-
-class YaffleTest < ActiveSupport::TestCase
- load_schema
-
- class Hickwall < ActiveRecord::Base
- end
-
- class Wickwall < ActiveRecord::Base
- end
-
- def test_schema_has_loaded_correctly
- assert_equal [], Hickwall.all
- assert_equal [], Wickwall.all
- end
-
-end
-</ruby>
-
-To run this, go to the plugin directory and run +rake+:
+This command will create a new directory named "yaffle" within the current directory.
-<shell>
-cd vendor/plugins/yaffle
-rake
-</shell>
-
-You should see output like:
+h3. Testing your newly generated plugin
-<shell>
-/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
- create_table(:hickwalls, {:force=>true})
- -> 0.0220s
--- create_table(:wickwalls, {:force=>true})
- -> 0.0077s
--- create_table(:woodpeckers, {:force=>true})
- -> 0.0069s
--- initialize_schema_migrations_table()
- -> 0.0007s
--- assume_migrated_upto_version(0, "db/migrate")
- -> 0.0007s
-Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
-Started
-.
-Finished in 0.002236 seconds.
-
-1 test, 2 assertion, 0 failures, 0 errors, 0 skips
-</shell>
+You can navigate to the directory that contains the plugin, run the +bundle install+ command
+ and run the one generated test using the +rake+ command.
-By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake:
+You should see:
<shell>
-rake DB=sqlite
-rake DB=sqlite3
-rake DB=mysql
-rake DB=postgresql
+ 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips
</shell>
-Now you are ready to test-drive your plugin!
+This will tell you that everything got generated properly and you are ready to start adding functionality.
h3. Extending Core Classes
@@ -286,9 +72,9 @@ This section will explain how to add a method to String that will be available a
In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions:
<ruby>
-# vendor/plugins/yaffle/test/core_ext_test.rb
+# yaffle/test/core_ext_test.rb
-require File.dirname(__FILE__) + '/test_helper'
+require 'test_helper'
class CoreExtTest < Test::Unit::TestCase
def test_to_squawk_prepends_the_word_squawk
@@ -297,20 +83,13 @@ class CoreExtTest < Test::Unit::TestCase
end
</ruby>
-Navigate to your plugin directory and run +rake test+:
+Run +rake+ to run the test. This test should fail because we haven't implemented the +to_squak+ method:
<shell>
-cd vendor/plugins/yaffle
-rake test
-</shell>
-
-The test above should fail with the message:
-
-<shell>
- 1) Error:
-test_to_squawk_prepends_the_word_squawk(CoreExtTest):
-NoMethodError: undefined method `to_squawk' for "Hello World":String
- ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
+ 1) Error:
+ test_to_squawk_prepends_the_word_squawk(CoreExtTest):
+ NoMethodError: undefined method `to_squawk' for "Hello World":String
+ test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
</shell>
Great - now you are ready to start development.
@@ -318,15 +97,18 @@ Great - now you are ready to start development.
Then in +lib/yaffle.rb+ require +lib/core_ext+:
<ruby>
-# vendor/plugins/yaffle/lib/yaffle.rb
+# yaffle/lib/yaffle.rb
require "yaffle/core_ext"
+
+module Yaffle
+end
</ruby>
Finally, create the +core_ext.rb+ file and add the +to_squawk+ method:
<ruby>
-# vendor/plugins/yaffle/lib/yaffle/core_ext.rb
+# yaffle/lib/yaffle/core_ext.rb
String.class_eval do
def to_squawk
@@ -335,7 +117,13 @@ String.class_eval do
end
</ruby>
-To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory. To see this in action, fire up a console and start squawking:
+To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory.
+
+<shell>
+ 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
+</shell>
+
+To see this in action, change to the test/dummy directory, fire up a console and start squawking:
<shell>
$ rails console
@@ -343,115 +131,56 @@ $ rails console
=> "squawk! Hello World"
</shell>
-h4. Working with +init.rb+
-
-When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior.
-
-NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned.
-
-Under certain circumstances if you reopen classes or modules in +init.rb+ you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from +init.rb+, as shown above.
-
-If you must reopen a class in +init.rb+ you can use +module_eval+ or +class_eval+ to avoid any issues:
-
-<ruby>
-# vendor/plugins/yaffle/init.rb
-
-Hash.class_eval do
- def is_a_special_hash?
- true
- end
-end
-</ruby>
-
-Another way is to explicitly define the top-level module space for all modules and classes, like +::Hash+:
-
-<ruby>
-# vendor/plugins/yaffle/init.rb
-
-class ::Hash
- def is_a_special_hash?
- true
- end
-end
-</ruby>
-
h3. Add an "acts_as" Method to Active Record
-A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you
+want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your Active Record models.
To begin, set up your files so that you have:
-* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
-
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
+# yaffle/test/acts_as_yaffle_test.rb
+
+require 'test_helper'
class ActsAsYaffleTest < Test::Unit::TestCase
end
</ruby>
-* *vendor/plugins/yaffle/lib/yaffle.rb*
-
<ruby>
-require 'yaffle/acts_as_yaffle'
-</ruby>
+# yaffle/lib/yaffle.rb
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+require "yaffle/core_ext"
+require 'yaffle/acts_as_yaffle'
-<ruby>
module Yaffle
- # your code will go here
end
</ruby>
-Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.
-
-One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so:
-
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
-
<ruby>
-module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
+# yaffle/lib/yaffle/acts_as_yaffle.rb
- module ClassMethods
- # any method placed here will apply to classes, like Hickwall
- def acts_as_something
- send :include, InstanceMethods
- end
- end
-
- module InstanceMethods
- # any method placed here will apply to instaces, like @hickwall
+module Yaffle
+ module ActsAsYaffle
+ # your code will go here
end
end
</ruby>
-With structure you can easily separate the methods that will be used for the class (like +Hickwall.some_method+) and the instance (like +@hickwell.some_method+).
-
h4. Add a Class Method
-This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the
+plugin users might have already defined a method on their model named 'last_squawk' that they use
+for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
To start out, write a failing test that shows the behavior you'd like:
-* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
-
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
+# yaffle/test/acts_as_yaffle_test.rb
-class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet
-end
+require 'test_helper'
class ActsAsYaffleTest < Test::Unit::TestCase
- load_schema
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
@@ -460,1058 +189,280 @@ class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
+
end
</ruby>
-To make these tests pass, you could modify your +acts_as_yaffle+ file like so:
+When you run +rake+, you should see the following:
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+<shell>
+ 1) Error:
+ test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
+ NameError: uninitialized constant ActsAsYaffleTest::Hickwall
+ test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
-<ruby>
-module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
+ 2) Error:
+ test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
+ NameError: uninitialized constant ActsAsYaffleTest::Wickwall
+ test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- end
- end
-end
+ 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
+</shell>
-ActiveRecord::Base.send :include, Yaffle
-</ruby>
+This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test.
+We can easily generate these models in our "dummy" Rails application by running the following commands from the
+test/dummy directory:
-h4. Add an Instance Method
+<shell>
+$ cd test/dummy
+$ rails generate model Hickwall last_squak:string
+$ rails generate model Wickwall last_squak:string last_tweet:string
+</shell>
-This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
+Now you can create the necessary database tables in your testing database by navigating to your dummy app
+and migrating the database. First
-To start out, write a failing test that shows the behavior you'd like:
+<shell>
+$ cd test/dummy
+$ rake db:migrate
+$ rake db:test:prepare
+</shell>
-* *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act
+like yaffles.
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
+# test/dummy/app/models/hickwall.rb
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
+# test/dummy/app/models/wickwall.rb
+
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet
end
-class ActsAsYaffleTest < Test::Unit::TestCase
- load_schema
-
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- 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
- end
-
- def test_hickwalls_squawk_should_populate_last_squawk
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", hickwall.last_squawk
- end
-
- def test_wickwalls_squawk_should_populate_last_tweeted_at
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
-end
</ruby>
-Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this:
-
-* *vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
+We will also add code to define the acts_as_yaffle method.
<ruby>
+# yaffle/lib/yaffle/acts_as_yaffle.rb
module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- send :include, InstanceMethods
+ included do
end
- end
- module InstanceMethods
- def squawk(string)
- write_attribute(self.class.yaffle_text_field, string.to_squawk)
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ # your code will go here
+ end
end
end
end
-ActiveRecord::Base.send :include, Yaffle
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
-NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
-
-h3. Models
-
-This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
+You can then return to the root directory (+cd ../..+) of your plugin and rerun the tests using +rake+.
<shell>
-vendor/plugins/yaffle/
-|-- lib
-| |-- app
-| | |-- controllers
-| | |-- helpers
-| | |-- models
-| | | `-- woodpecker.rb
-| | `-- views
-| |-- yaffle
-| | |-- acts_as_yaffle.rb
-| | |-- commands.rb
-| | `-- core_ext.rb
-| `-- yaffle.rb
-</shell>
-
-As always, start with a test:
-
-* *vendor/plugins/yaffle/test/woodpecker_test.rb:*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
+ 1) Error:
+ test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
+ NoMethodError: undefined method `yaffle_text_field' for #<Class:0x000001016661b8>
+ /Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
+ test/acts_as_yaffle_test.rb:5:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
-class WoodpeckerTest < Test::Unit::TestCase
- load_schema
+ 2) Error:
+ test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
+ NoMethodError: undefined method `yaffle_text_field' for #<Class:0x00000101653748>
+ Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
+ test/acts_as_yaffle_test.rb:9:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
- def test_woodpecker
- assert_kind_of Woodpecker, Woodpecker.new
- end
-end
-</ruby>
+ 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
-This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-%w{ models }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.autoload_paths << path
- ActiveSupport::Dependencies.autoload_once_paths.delete(path)
-end
-</ruby>
-
-Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
-
-* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
-
-<ruby>
-class Woodpecker < ActiveRecord::Base
-end
-</ruby>
-
-Finally, add the following to your plugin's 'schema.rb':
-
-* *vendor/plugins/yaffle/test/schema.rb:*
-
-<ruby>
-create_table :woodpeckers, :force => true do |t|
- t.string :name
-end
-</ruby>
-
-Now your test should be passing, and you should be able to use the Woodpecker model from within your rails application, and any changes made to it are reflected immediately when running in development mode.
-
-h3. Controllers
-
-This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
-
-You can test your plugin's controller as you would test any other controller:
-
-* *vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'woodpeckers_controller'
-require 'action_controller/test_process'
-
-class WoodpeckersController; def rescue_action(e) raise e end; end
-
-class WoodpeckersControllerTest < Test::Unit::TestCase
- def setup
- @controller = WoodpeckersController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
-
- ActionController::Routing::Routes.draw do |map|
- map.resources :woodpeckers
- end
- end
-
- def test_index
- get :index
- assert_response :success
- end
-end
-</ruby>
-
-This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-%w{ models controllers }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.autoload_paths << path
- ActiveSupport::Dependencies.autoload_once_paths.delete(path)
-end
-</ruby>
-
-* *vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:*
-
-<ruby>
-class WoodpeckersController < ActionController::Base
-
- def index
- render :text => "Squawk!"
- end
-
-end
-</ruby>
-
-Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
-
-h3. Helpers
-
-This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
-
-You can test your plugin's helper as you would test any other helper:
-
-* *vendor/plugins/yaffle/test/woodpeckers_helper_test.rb*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-include WoodpeckersHelper
-
-class WoodpeckersHelperTest < Test::Unit::TestCase
- def test_tweet
- assert_equal "Tweet! Hello", tweet("Hello")
- end
-end
-</ruby>
-
-This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-%w{ models controllers helpers }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.autoload_paths << path
- ActiveSupport::Dependencies.autoload_once_paths.delete(path)
-end
-</ruby>
-
-* *vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:*
-
-<ruby>
-module WoodpeckersHelper
-
- def tweet(text)
- "Tweet! #{text}"
- end
-
-end
-</ruby>
-
-Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
-
-h3. Routes
-
-In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'.
-
-Testing routes from plugins is slightly different from testing routes in a standard rails application. To begin, add a test like this:
+</shell>
-* *vendor/plugins/yaffle/test/routing_test.rb*
+Getting closer...now we will implement the code of the acts_as_yaffle method to make the tests pass.
<ruby>
-require "#{File.dirname(__FILE__)}/test_helper"
-
-class RoutingTest < Test::Unit::TestCase
-
- def setup
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
- end
-
- def test_yaffles_route
- assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
- end
+# yaffle/lib/yaffle/acts_as_yaffle.rb
- private
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
- def assert_recognition(method, path, options)
- result = ActionController::Routing::Routes.recognize_path(path, :method => method)
- assert_equal options, result
+ included do
end
-end
-</ruby>
-
-Once you see the tests fail by running 'rake', you can make them pass with:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb*
-
-<ruby>
-require "yaffle/routing"
-</ruby>
-* *vendor/plugins/yaffle/lib/yaffle/routing.rb*
-
-<ruby>
-module Yaffle #:nodoc:
- module Routing #:nodoc:
- module MapperExtensions
- def yaffles
- @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
end
end
end
end
-ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
-</ruby>
-
-* *config/routes.rb*
-
-<ruby>
-ActionController::Routing::Routes.draw do |map|
- map.yaffles
-end
-</ruby>
-
-You can also see if your routes work by running +rake routes+ from your app directory.
-
-h3. Generators
-
-Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
-
-Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.
-
-h4. Testing Generators
-
-Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
-
- * Creates a new fake rails root directory that will serve as destination
- * Runs the generator
- * Asserts that the correct files were generated
- * Removes the fake rails root
-
-This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
-
-* *vendor/plugins/yaffle/test/definition_generator_test.rb*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'rails_generator'
-require 'rails_generator/scripts/generate'
-
-class DefinitionGeneratorTest < Test::Unit::TestCase
-
- def setup
- FileUtils.mkdir_p(fake_rails_root)
- @original_files = file_list
- end
-
- def teardown
- FileUtils.rm_r(fake_rails_root)
- end
-
- def test_generates_correct_file_name
- Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root)
- new_file = (file_list - @original_files).first
- assert_equal "definition.txt", File.basename(new_file)
- end
-
- private
-
- def fake_rails_root
- File.join(File.dirname(__FILE__), 'rails_root')
- end
-
- def file_list
- Dir.glob(File.join(fake_rails_root, "*"))
- end
-
-end
-</ruby>
-
-You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
-
-To make it pass, create the generator:
-
-* *vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb*
-
-<ruby>
-class YaffleDefinitionGenerator < Rails::Generator::Base
- def manifest
- record do |m|
- m.file "definition.txt", "definition.txt"
- end
- end
-end
-</ruby>
-
-h4. The +USAGE+ File
-
-If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
-
-Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
-
-<shell>
-rails generate
-</shell>
-
-You should see something like this:
-
-<shell>
-Installed Generators
- Plugins (vendor/plugins): yaffle_definition
- Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
-</shell>
-
-When you run +rails generate yaffle_definition -h+ you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
-
-For this plugin, update the USAGE file could look like this:
-
-<shell>
-Description:
- Adds a file with the definition of a Yaffle to the app's main directory
-</shell>
-
-h3. Add a Custom Generator Command
-
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
-
-This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
-
-To start, add the following test method:
-
-* *vendor/plugins/yaffle/test/generator_test.rb*
-
-<ruby>
-def test_generates_definition
- Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
- definition = File.read(File.join(fake_rails_root, "definition.txt"))
- assert_match /Yaffle\:/, definition
-end
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
-Run +rake+ to watch the test fail, then make the test pass add the following:
-
-* *vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
+When you run +rake+ you should see the tests all pass:
<shell>
-Yaffle: A bird
+ 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips
</shell>
-* *vendor/plugins/yaffle/lib/yaffle.rb*
-
-<ruby>
-require "yaffle/commands"
-</ruby>
-
-* *vendor/plugins/yaffle/lib/commands.rb*
-
-<ruby>
-require 'rails_generator'
-require 'rails_generator/commands'
-
-module Yaffle #:nodoc:
- module Generator #:nodoc:
- module Commands #:nodoc:
- module Create
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module Destroy
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module List
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
-
- module Update
- def yaffle_definition
- file("definition.txt", "definition.txt")
- end
- end
- end
- end
-end
-
-Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
-Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
-Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
-Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
-</ruby>
-
-Finally, call your new method in the manifest:
-
-* *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
-
-<ruby>
-class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
-</ruby>
-
-h3. Generator Commands
-
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
-
-This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'.
+h4. Add an Instance Method
-To start, add the following test method:
+This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk'
+method will simply set the value of one of the fields in the database.
-* *vendor/plugins/yaffle/test/route_generator_test.rb*
+To start out, write a failing test that shows the behavior you'd like:
<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'rails_generator'
-require 'rails_generator/scripts/generate'
-require 'rails_generator/scripts/destroy'
+# yaffle/test/acts_as_yaffle_test.rb
+require 'test_helper'
-class RouteGeneratorTest < Test::Unit::TestCase
+class ActsAsYaffleTest < Test::Unit::TestCase
- def setup
- FileUtils.mkdir_p(File.join(fake_rails_root, "config"))
+ def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
+ assert_equal "last_squawk", Hickwall.yaffle_text_field
end
- def teardown
- FileUtils.rm_r(fake_rails_root)
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
+ assert_equal "last_tweet", Wickwall.yaffle_text_field
end
- def test_generates_route
- content = <<-END
- ActionController::Routing::Routes.draw do |map|
- map.connect ':controller/:action/:id'
- map.connect ':controller/:action/:id.:format'
- end
- END
- File.open(routes_path, 'wb') {|f| f.write(content) }
-
- Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root)
- assert_match /map\.yaffles/, File.read(routes_path)
+ def test_hickwalls_squawk_should_populate_last_squawk
+ hickwall = Hickwall.new
+ hickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", hickwall.last_squawk
end
- def test_destroys_route
- content = <<-END
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- map.connect ':controller/:action/:id'
- map.connect ':controller/:action/:id.:format'
- end
- END
- File.open(routes_path, 'wb') {|f| f.write(content) }
-
- Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root)
- assert_no_match /map\.yaffles/, File.read(routes_path)
+ def test_wickwalls_squawk_should_populate_last_tweeted_at
+ wickwall = Wickwall.new
+ wickwall.squawk("Hello World")
+ assert_equal "squawk! Hello World", wickwall.last_tweet
end
-
- private
-
- def fake_rails_root
- File.join(File.dirname(__FILE__), "rails_root")
- end
-
- def routes_path
- File.join(fake_rails_root, "config", "routes.rb")
- end
-
end
</ruby>
-Run +rake+ to watch the test fail, then make the test pass add the following:
-
-* *vendor/plugins/yaffle/lib/yaffle.rb*
+Run the test to make sure the last two tests fail the an error that contains "NoMethodError: undefined method `squawk'",
+then update 'acts_as_yaffle.rb' to look like this:
<ruby>
-require "yaffle/commands"
-</ruby>
-
-* *vendor/plugins/yaffle/lib/yaffle/commands.rb*
+# yaffle/lib/yaffle/acts_as_yaffle.rb
-<ruby>
-require 'rails_generator'
-require 'rails_generator/commands'
-
-module Yaffle #:nodoc:
- module Generator #:nodoc:
- module Commands #:nodoc:
- module Create
- def yaffle_route
- logger.route "map.yaffle"
- look_for = 'ActionController::Routing::Routes.draw do |map|'
- unless options[:pretend]
- gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"}
- end
- end
- end
-
- module Destroy
- def yaffle_route
- logger.route "map.yaffle"
- gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, ''
- end
- end
-
- module List
- def yaffle_route
- end
- end
+module Yaffle
+ module ActsAsYaffle
+ extend ActiveSupport::Concern
- module Update
- def yaffle_route
- end
- end
+ included do
end
- end
-end
-
-Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
-Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
-Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
-Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
-</ruby>
-
-* *vendor/plugins/yaffle/generators/yaffle_route/yaffle_route_generator.rb*
-<ruby>
-class YaffleRouteGenerator < Rails::Generator::Base
- def manifest
- record do |m|
- m.yaffle_route
+ module ClassMethods
+ def acts_as_yaffle(options = {})
+ cattr_accessor :yaffle_text_field
+ self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
+ end
end
- end
-end
-</ruby>
-
-To see this work, type:
-
-<shell>
-rails generate yaffle_route
-rails destroy yaffle_route
-</shell>
-
-NOTE: If you haven't set up the custom route from above, 'rails destroy' will fail and you'll have to remove it manually.
-
-h3. Migrations
-
-If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
-
-If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
-Let's say you have the following migration in your plugin:
-
-* *vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:*
-
-<ruby>
-class CreateBirdhouses < ActiveRecord::Migration
- def self.up
- create_table :birdhouses, :force => true do |t|
- t.string :name
- t.timestamps
+ def squawk(string)
+ write_attribute(self.class.yaffle_text_field, string.to_squawk)
end
- end
- def self.down
- drop_table :birdhouses
end
end
-</ruby>
-
-Here are a few possibilities for how to allow developers to use your plugin migrations:
-h4. Create a Custom Rake Task
-
-* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake:*
-
-<ruby>
-namespace :db do
- namespace :migrate do
- description = "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate"
- description << "and update db/schema.rb by invoking db:schema:dump."
- description << "Target specific version with VERSION=x. Turn off output with VERBOSE=false."
-
- desc description
- task :yaffle => :environment do
- ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
- ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
- Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
- end
- end
-end
+ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
-h4. Call Migrations Directly
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
- require file
-end
-</ruby>
-
-* *db/migrate/20081116181115_create_birdhouses.rb:*
-
-<ruby>
-class CreateBirdhouses < ActiveRecord::Migration
- def self.up
- Yaffle::CreateBirdhouses.up
- end
-
- def self.down
- Yaffle::CreateBirdhouses.down
- end
-end
-</ruby>
-
-NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
-
-h4. Generate Migrations
-
-Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
-
- * call your rails generate script and pass in whatever options they need
- * examine the generated migration, adding/removing columns or other options as necessary
-
-This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
-
-* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb*
-
-<ruby>
-require File.dirname(__FILE__) + '/test_helper'
-require 'rails_generator'
-require 'rails_generator/scripts/generate'
-
-class MigrationGeneratorTest < Test::Unit::TestCase
-
- def setup
- FileUtils.mkdir_p(fake_rails_root)
- @original_files = file_list
- end
-
- def teardown
- ActiveRecord::Base.pluralize_table_names = true
- FileUtils.rm_r(fake_rails_root)
- end
-
- def test_generates_correct_file_name
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
- :destination => fake_rails_root)
- new_file = (file_list - @original_files).first
- assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
- assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file)
- end
-
- def test_pluralizes_properly
- ActiveRecord::Base.pluralize_table_names = false
- Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"],
- :destination => fake_rails_root)
- new_file = (file_list - @original_files).first
- assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
- assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file)
- end
-
- private
- def fake_rails_root
- File.join(File.dirname(__FILE__), 'rails_root')
- end
-
- def file_list
- Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
- end
-
-end
-</ruby>
-
-NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
-
-After running the test with 'rake' you can make it pass with:
-
-* *vendor/plugins/yaffle/generators/yaffle_migration/yaffle_migration_generator.rb*
-
-<ruby>
-class YaffleMigrationGenerator < Rails::Generator::NamedBase
- def manifest
- record do |m|
- m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
- :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
- }
- end
- end
-
- private
- def custom_file_name
- custom_name = class_name.underscore.downcase
- custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
- custom_name
- end
-
- def yaffle_local_assigns
- {}.tap do |assigns|
- assigns[:migration_action] = "add"
- assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
- assigns[:table_name] = custom_file_name
- assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
- end
- end
-end
-</ruby>
-
-The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in rails +migration_template+ method, and reuses the built-in rails migration template.
-
-It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
-
-To run the generator, type the following at the command line:
-
+Run +rake+ one final time and you should see:
<shell>
-rails generate yaffle_migration bird
+ 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips
</shell>
-and you will see a new file:
-
-* *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
-
-<ruby>
-class AddYaffleFieldsToBirds < ActiveRecord::Migration
- def self.up
- add_column :birds, :last_squawk, :string
- end
-
- def self.down
- remove_column :birds, :last_squawk
- end
-end
-</ruby>
-
-h3. Rake tasks
-
-When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app.
+NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can
+interact with the model, and will not always be the right method to use. For example, you could also
+use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
-Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
-
-* *vendor/plugins/yaffle/tasks/yaffle_tasks.rake*
-
-<ruby>
-namespace :yaffle do
- desc "Prints out the word 'Yaffle'"
- task :squawk => :environment do
- puts "squawk!"
- end
-end
-</ruby>
+h3. Generators
-When you run +rake -T+ from your plugin you will see:
+Generators can be included in your gem simply by creating them in a lib/generators directory of your plugin. More information about
+the creation of generators can be found in the "Generators Guide":generators.html
-<shell>
-yaffle:squawk # Prints out the word 'Yaffle'
-</shell>
+h3. Publishing your Gem
-You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
+Gem plugins in progress can be 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 any application:
-Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the main app.
+gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
-h3. Plugins as Gems
+After running +bundle install+, your gem functionality will be available to the application.
-Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.
+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
-Rails 3 ignores both <tt>init.rb</tt> and <tt>rails/init.rb</tt> file of a gem. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option.
+h3. Non-Gem Plugins
-It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this:
+Non-gem plugins are useful for functionality that won't be shared with another project. Keeping your custom functionality in the
+vendor/plugins directory un-clutters the rest of the application.
-* *vendor/plugins/yaffle/Rakefile:*
+Move the directory that you created for the gem based plugin into the vendor/plugins directory of a generated Rails application, create a vendor/plugins/yaffle/init.rb file that contains "require 'yaffle'" and everything will still work.
<ruby>
-PKG_FILES = FileList[
- '[a-zA-Z]*',
- 'generators/**/*',
- 'lib/**/*',
- 'rails/**/*',
- 'tasks/**/*',
- 'test/**/*'
-]
-
-spec = Gem::Specification.new do |s|
- s.name = "yaffle"
- s.version = "0.0.1"
- s.author = "Gleeful Yaffler"
- s.email = "yaffle@example.com"
- s.homepage = "http://yafflers.example.com/"
- s.platform = Gem::Platform::RUBY
- s.summary = "Sharing Yaffle Goodness"
- s.files = PKG_FILES.to_a
- s.require_path = "lib"
- s.has_rdoc = false
- s.extra_rdoc_files = ["README"]
-end
+# yaffle/init.rb
-desc 'Turn this plugin into a gem.'
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
-end
+require 'yaffle'
</ruby>
-To build and install the gem locally, run the following commands:
-
+You can test this by changing to the Rails application that you added the plugin to and starting a rails console. Once in the
+console we can check to see if the String has an instance method of to_squawk.
<shell>
-cd vendor/plugins/yaffle
-rake gem
-sudo gem install pkg/yaffle-0.0.1.gem
+$ cd my_app
+$ rails console
+$ String.instance_methods.sort
</shell>
-To test this, create a new rails application, add +config.gem "yaffle"+ to +config/environment.rb+ and all of your plugin's functionality will be available to you.
+You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed.
h3. RDoc Documentation
Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
-The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
* Your name
* How to install
* How to add the functionality to the app (several examples of common use cases)
* Warning, gotchas or tips that might help save users 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 part of 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 part of the public api.
Once your comments are good to go, navigate to your plugin directory and run:
<shell>
-rake rdoc
+$ rake rdoc
</shell>
-h3. Appendix
-
-If you prefer to use RSpec instead of Test::Unit, you may be interested in the "RSpec Plugin Generator":http://github.com/patmaddox/rspec-plugin-generator.
+!!!!!!!!!!!!!! Make sure these still make sense. Add any references that you see fit. !!!!!!!!!!!!!
h4. References
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
-* http://github.com/technoweenie/attachment_fu/tree/master
-* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
-* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
-* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
-
-h4. Contents of +lib/yaffle.rb+
-
-* *vendor/plugins/yaffle/lib/yaffle.rb:*
-
-<ruby>
-require "yaffle/core_ext"
-require "yaffle/acts_as_yaffle"
-require "yaffle/commands"
-require "yaffle/routing"
-
-%w{ models controllers helpers }.each do |dir|
- path = File.join(File.dirname(__FILE__), 'app', dir)
- $LOAD_PATH << path
- ActiveSupport::Dependencies.autoload_paths << path
- ActiveSupport::Dependencies.autoload_once_paths.delete(path)
-end
-
-# optionally:
-# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
-# require file
-# end
-</ruby>
-
-h4. Final Plugin Directory Structure
-
-The final plugin should have a directory structure that looks something like this:
-
-<shell>
-|-- MIT-LICENSE
-|-- README
-|-- Rakefile
-|-- generators
-| |-- yaffle_definition
-| | |-- USAGE
-| | |-- templates
-| | | `-- definition.txt
-| | `-- yaffle_definition_generator.rb
-| |-- yaffle_migration
-| | |-- USAGE
-| | |-- templates
-| | `-- yaffle_migration_generator.rb
-| `-- yaffle_route
-| |-- USAGE
-| |-- templates
-| `-- yaffle_route_generator.rb
-|-- install.rb
-|-- lib
-| |-- app
-| | |-- controllers
-| | | `-- woodpeckers_controller.rb
-| | |-- helpers
-| | | `-- woodpeckers_helper.rb
-| | `-- models
-| | `-- woodpecker.rb
-| |-- db
-| | `-- migrate
-| | `-- 20081116181115_create_birdhouses.rb
-| |-- yaffle
-| | |-- acts_as_yaffle.rb
-| | |-- commands.rb
-| | |-- core_ext.rb
-| | `-- routing.rb
-| `-- yaffle.rb
-|-- pkg
-| `-- yaffle-0.0.1.gem
-|-- rails
-| `-- init.rb
-|-- tasks
-| `-- yaffle_tasks.rake
-|-- test
-| |-- acts_as_yaffle_test.rb
-| |-- core_ext_test.rb
-| |-- database.yml
-| |-- debug.log
-| |-- definition_generator_test.rb
-| |-- migration_generator_test.rb
-| |-- route_generator_test.rb
-| |-- routes_test.rb
-| |-- schema.rb
-| |-- test_helper.rb
-| |-- woodpecker_test.rb
-| |-- woodpeckers_controller_test.rb
-| |-- wookpeckers_helper_test.rb
-| |-- yaffle_plugin.sqlite3.db
-| `-- yaffle_test.rb
-`-- uninstall.rb
-</shell>
+* "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/
+* "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
+* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
h3. Changelog
+* February 13, 2011: Get guide in synch with Rails 3.0.3. Remove information not compatible with Rails 3. Send reader elsewhere
+for information that is covered elsewhere.
* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
* November 17, 2008: Major revision by Jeff Dean
diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile
index d4b887ad02..8e51f9e23b 100644
--- a/railties/guides/source/rails_application_templates.textile
+++ b/railties/guides/source/rails_application_templates.textile
@@ -20,7 +20,7 @@ $ rails new blog -m ~/template.rb
It's also possible to apply a template using a URL :
<shell>
-$ rails new blog -m http://gist.github.com/31208.txt
+$ rails new blog -m https://gist.github.com/755496.txt
</shell>
Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application :
@@ -37,7 +37,7 @@ Rails templates API is very self explanatory and easy to understand. Here's an e
# template.rb
run "rm public/index.html"
generate(:scaffold, "person name:string")
-route "map.root :controller => 'people'"
+route "root :to => 'people#index'"
rake("db:migrate")
git :init
@@ -49,7 +49,7 @@ The following sections outlines the primary methods provided by the API :
h4. gem(name, options = {})
-Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+.
+Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+.
For example, if your application depends on the gems +bj+ and +nokogiri+ :
@@ -66,6 +66,16 @@ rake "gems:install"
And let Rails take care of installing the required gems if they’re not already installed.
+h4. add_source(source, options = {})
+
+Adds the given source to the generated application's +Gemfile+.
+
+For example, if you need to source a gem from "http://code.whytheluckystiff.net":
+
+<ruby>
+add_source "http://code.whytheluckystiff.net"
+</ruby>
+
h4. plugin(name, options = {})
Installs a plugin to the generated application.
@@ -183,12 +193,12 @@ h4. route(routing_code)
This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application :
<ruby>
-route "map.root :controller => :person"
+route "root :to => 'person#index'"
</ruby>
h4. inside(dir)
-I have my edge rails lying at +~/commit-rails/rails+. So every time i have to manually symlink edge from my new app. But now :
+Enables you to run a command from the given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this:
<ruby>
inside('vendor') do
@@ -196,8 +206,6 @@ inside('vendor') do
end
</ruby>
-So +inside()+ runs the command from the given directory.
-
h4. ask(question)
+ask()+ gives you a chance to get some feedback from the user and use it in your templates. Lets say you want your user to name the new shiny library you’re adding :
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index f17e9b4798..b1db2942dd 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -17,12 +17,7 @@ bq. Rack provides a minimal, modular and adaptable interface for developing web
- "Rack API Documentation":http://rack.rubyforge.org/doc/
-Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the following links:
-
-* "Official Rack Website":http://rack.github.com
-* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below.
h3. Rails on Rack
@@ -68,13 +63,13 @@ run ActionController::Dispatcher.new
And start the server:
<shell>
-[lifo@null application]$ rackup config.ru
+$ rackup config.ru
</shell>
To find out more about different +rackup+ options:
<shell>
-[lifo@null application]$ rackup --help
+$ rackup --help
</shell>
h3. Action Controller Middleware Stack
@@ -165,7 +160,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|_.Middleware|_.Purpose|
|+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.|
|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.|
-|+ActiveRecord::QueryCache+|Enable the Active Record query cache.|
+|+ActiveRecord::QueryCache+|Enables the Active Record query cache.|
|+ActionController::Session::CookieStore+|Uses the cookie based session store.|
|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.|
|+ActiveRecord::SessionStore+|Uses the database based session store.|
@@ -228,8 +223,8 @@ h4. Learning Rack
* "Official Rack Website":http://rack.github.com
* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
+* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder
h4. Understanding Middlewares
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 7af9779ac7..d214031b31 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -85,6 +85,9 @@ creates seven different routes in your application, all mapping to the +Photos+
|PUT |/photos/:id |update |update a specific photo |
|DELETE |/photos/:id |destroy |delete a specific photo |
+
+NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first.
+
h4. Paths and URLs
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+:
@@ -388,6 +391,8 @@ NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment.
match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/
</ruby>
+TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash.
+
h4. Static Segments
You can specify static segments when creating a route:
@@ -495,7 +500,7 @@ You specify a request-based constraint the same way that you specify a segment c
match "photos", :constraints => {:subdomain => "admin"}
</ruby>
-You can also specify constrains in a block form:
+You can also specify constraints in a block form:
<ruby>
namespace :admin do
@@ -595,7 +600,7 @@ You can specify what Rails should route +"/"+ to with the +root+ method:
root :to => 'pages#main'
</ruby>
-You should put the +root+ route at the end of the file.
+You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect.
h3. Customizing Resourceful Routes
@@ -630,7 +635,7 @@ You can use the +:constraints+ option to specify a required format on the implic
resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
</ruby>
-This declaration constrains the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
+This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
You can specify a single constraint to apply to a number of routes by using the block form:
@@ -643,6 +648,8 @@ end
NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
+TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id => /[^\/]+/+ allows anything except a slash.
+
h4. Overriding the Named Helpers
The +:as+ option lets you override the normal naming for the named route helpers. For example:
@@ -701,7 +708,7 @@ resources :photos
This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc.
-To prefix a group of routes, use +:as+ with +scope+:
+To prefix a group of route helpers, use +:as+ with +scope+:
<ruby>
scope "admin", :as => "admin" do
@@ -711,8 +718,20 @@ end
resources :photos, :accounts
</ruby>
+This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively.
+
NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes.
+You can prefix routes with a named parameter also:
+
+<ruby>
+scope ":username" do
+ resources :posts
+end
+</ruby>
+
+This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views.
+
h4. Restricting the Routes Created
By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes:
@@ -837,12 +856,6 @@ You can supply a +:method+ argument to specify the HTTP verb:
assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post })
</ruby>
-You can also use the resourceful helpers to test recognition of a RESTful route:
-
-<ruby>
-assert_recognizes new_photo_url, { :path => "photos", :method => :post }
-</ruby>
-
h5. The +assert_routing+ Assertion
The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+.
diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
index 0bc409cbda..6576758856 100644
--- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile
+++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
@@ -16,7 +16,7 @@ h3. Titles
The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc.
-Capitalize all words except for internal articles, prepositions, conjuctions, and forms of the verb to be:
+Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be:
<plain>
h5. Middleware Stack is an Array
@@ -45,24 +45,30 @@ h3. HTML Generation
To generate all the guides just cd into the +railties+ directory and execute
<plain>
-rake generate_guides
+bundle exec rake generate_guides
</plain>
-You'll need the gems erubis, i18n, and RedCloth.
+You'll need the gems erubis, i18n, and RedCloth.
To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable:
<plain>
-rake generate_guides ONLY=my_guide
+bundle exec rake generate_guides ONLY=my_guide
</plain>
Although by default guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice.
-To force process of al the guides pass +ALL=1+.
+To force process of all the guides, pass +ALL=1+.
It is also recommended that you work with +WARNINGS=1+, this detects duplicate IDs and warns about broken internal links.
-h3. HTML validation
+If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +LANGUAGE+ environment variable.
+
+<plain>
+rake generate_guides LANGUAGE=es
+</plain>
+
+h3. HTML Validation
Please do validate the generated HTML with
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index 528c8861d4..5613156245 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -240,7 +240,7 @@ There are many other possibilities, including Ajax to attack the victim in the b
protect_from_forgery :secret => "123456789012345678901234567890..."
</ruby>
-This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. It will raise an ActionController::InvalidAuthenticityToken error, if the security token doesn't match what was expected.
+This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an <tt>ActionController::InvalidAuthenticityToken</tt> error.
Note that _(highlight)cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later.
@@ -524,10 +524,10 @@ h4. Logging
-- _Tell Rails not to put passwords in the log files._
-By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by the filter_parameter_logging method in a controller. These parameters will be marked [FILTERED] in the log.
+By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
<ruby>
-filter_parameter_logging :password
+config.filter_parameters << :password
</ruby>
h4. Good Passwords
@@ -616,7 +616,7 @@ h5(#sql-injection-introduction). Introduction
SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:
@@ -632,7 +632,7 @@ h5. Bypassing Authorization
Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
<ruby>
-User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'")
+User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
</ruby>
If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be:
@@ -648,7 +648,7 @@ h5. Unauthorized Reading
The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
And now let's inject another query using the UNION statement:
@@ -675,13 +675,13 @@ Ruby on Rails has a built-in filter for special SQL characters, which will escap
Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
<ruby>
-Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
+Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
</ruby>
As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
<ruby>
-Model.find(:first, :conditions => {:login => entered_user_name, :password => entered_password})
+Model.first(:conditions => {:login => entered_user_name, :password => entered_password})
</ruby>
The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_.
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index 733c8a755e..a6d70da76c 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -229,13 +229,13 @@ $ rake db:test:load
Above +rake db:migrate+ runs any pending migrations on the _development_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately.
-NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exists.
+NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
h5. Rake Tasks for Preparing your Application for Testing
|_.Tasks |_.Description|
|+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
-|+rake db:test:clone_structure+ |Recreate the test databases from the development structure|
+|+rake db:test:clone_structure+ |Recreate the test database from the development structure|
|+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
|+rake db:test:prepare+ |Check for pending migrations and load the test schema|
|+rake db:test:purge+ |Empty the test database.|
@@ -512,12 +512,12 @@ After a request has been made by using one of the 5 methods (+get+, +post+, etc.
As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
<ruby>
- flash["gordon"] flash[:gordon]
- session["shmession"] session[:shmession]
- cookies["are_good_for_u"] cookies[:are_good_for_u]
+flash["gordon"] flash[:gordon]
+session["shmession"] session[:shmession]
+cookies["are_good_for_u"] cookies[:are_good_for_u]
# Because you can't use assigns[:something] for historical reasons:
- assigns["something"] assigns(:something)
+assigns["something"] assigns(:something)
</ruby>
h4. Instance Variables Available
@@ -582,7 +582,7 @@ assert_select "ol" do
end
</ruby>
-The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionController/Assertions/SelectorAssertions.html.
+The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
h5. Additional View-Based Assertions
diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb
index da5200c0b7..f1fe1e0f33 100644
--- a/railties/guides/w3c_validator.rb
+++ b/railties/guides/w3c_validator.rb
@@ -21,7 +21,7 @@
#
# Separate many using commas:
#
-# # validates only
+# # validates only association_basics.html and migrations.html
# ONLY=assoc,migrations rake validate_guides
#
# ---------------------------------------------------------------------------
@@ -88,4 +88,4 @@ module RailsGuides
end
end
-RailsGuides::Validator.new.validate \ No newline at end of file
+RailsGuides::Validator.new.validate
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index b248bc737c..94819820bc 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -122,7 +122,8 @@ module Rails
@env_config ||= super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
"action_dispatch.secret_token" => config.secret_token,
- "action_dispatch.asset_path" => nil
+ "action_dispatch.asset_path" => nil,
+ "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
})
end
@@ -149,14 +150,18 @@ module Rails
require "action_dispatch/http/rack_cache" if rack_cache
middleware.use ::Rack::Cache, rack_cache if rack_cache
- middleware.use ::ActionDispatch::Static, config.static_asset_paths if config.serve_static_assets
+ if config.serve_static_assets
+ asset_paths = ActiveSupport::OrderedHash[config.static_asset_paths.to_a.reverse]
+ middleware.use ::ActionDispatch::Static, asset_paths
+ end
middleware.use ::Rack::Lock unless config.allow_concurrency
middleware.use ::Rack::Runtime
middleware.use ::Rails::Rack::Logger
- middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local if config.action_dispatch.show_exceptions
+ middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
- middleware.use ::ActionDispatch::Callbacks, !config.cache_classes
+ middleware.use ::ActionDispatch::Reloader unless config.cache_classes
+ middleware.use ::ActionDispatch::Callbacks
middleware.use ::ActionDispatch::Cookies
if config.session_store
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 213aa0768a..9c9d85eed6 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -51,11 +51,9 @@ module Rails
end
initializer :set_clear_dependencies_hook do
- unless config.cache_classes
- ActionDispatch::Callbacks.after do
- ActiveSupport::DescendantsTracker.clear
- ActiveSupport::Dependencies.clear
- end
+ ActionDispatch::Reloader.to_cleanup do
+ ActiveSupport::DescendantsTracker.clear
+ ActiveSupport::Dependencies.clear
end
end
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 8cd496781b..c74bcbedf2 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -6,25 +6,28 @@ module Rails
class Configuration < ::Rails::Engine::Configuration
attr_accessor :allow_concurrency, :asset_host, :cache_classes, :cache_store,
:encoding, :consider_all_requests_local, :dependency_loading,
- :filter_parameters, :helpers_paths, :log_level, :logger,
+ :filter_parameters, :helpers_paths, :logger,
:preload_frameworks, :reload_plugins,
:secret_token, :serve_static_assets, :session_options,
:time_zone, :whiny_nils
+ attr_writer :log_level
+
def initialize(*)
super
self.encoding = "utf-8"
- @allow_concurrency = false
+ @allow_concurrency = false
@consider_all_requests_local = false
- @filter_parameters = []
- @helpers_paths = []
- @dependency_loading = true
- @serve_static_assets = true
- @session_store = :cookie_store
- @session_options = {}
- @time_zone = "UTC"
- @middleware = app_middleware
- @generators = app_generators
+ @filter_parameters = []
+ @helpers_paths = []
+ @dependency_loading = true
+ @serve_static_assets = true
+ @session_store = :cookie_store
+ @session_options = {}
+ @time_zone = "UTC"
+ @log_level = nil
+ @middleware = app_middleware
+ @generators = app_generators
end
def compiled_asset_path
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index e3342be7ee..a45b61c99c 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -21,7 +21,7 @@ module Rails
initializer :add_to_prepare_blocks do
config.to_prepare_blocks.each do |block|
- ActionDispatch::Callbacks.to_prepare(&block)
+ ActionDispatch::Reloader.to_prepare(&block)
end
end
@@ -37,6 +37,10 @@ module Rails
build_middleware_stack
end
+ initializer :run_prepare_callbacks do
+ ActionDispatch::Reloader.prepare!
+ end
+
initializer :eager_load! do
if config.cache_classes && !$rails_rake_task
ActiveSupport.run_load_hooks(:before_eager_load, self)
@@ -52,7 +56,7 @@ module Rails
initializer :set_routes_reloader do |app|
reloader = lambda { app.routes_reloader.execute_if_updated }
reloader.call
- ActionDispatch::Callbacks.to_prepare(&reloader)
+ ActionDispatch::Reloader.to_prepare(&reloader)
end
# Disable dependency loading during request cycle
diff --git a/railties/lib/rails/cli.rb b/railties/lib/rails/cli.rb
index 2b32f7edf1..443d6f47ad 100644
--- a/railties/lib/rails/cli.rb
+++ b/railties/lib/rails/cli.rb
@@ -6,7 +6,7 @@ require 'rails/script_rails_loader'
Rails::ScriptRailsLoader.exec_script_rails!
require 'rails/ruby_version_check'
-Signal.trap("INT") { puts; exit }
+Signal.trap("INT") { puts; exit(1) }
if ARGV.first == 'plugin'
ARGV.shift
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index 46363d7921..02ccdf8060 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -62,6 +62,7 @@ when 'application', 'runner'
when 'new'
puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
puts "Type 'rails' for help."
+ exit(1)
when '--version', '-v'
ARGV.unshift '--version'
@@ -91,4 +92,5 @@ In addition to those, there are:
All commands can be run with -h for more information.
EOT
+ exit(1)
end
diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb
index 47c6752ca3..3b57b925ba 100644
--- a/railties/lib/rails/commands/application.rb
+++ b/railties/lib/rails/commands/application.rb
@@ -15,4 +15,16 @@ require 'rubygems' if ARGV.include?("--dev")
require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
+module Rails
+ module Generators
+ class AppGenerator
+ # We want to exit on failure to be kind to other libraries
+ # This is only when accessing via CLI
+ def self.exit_on_failure?
+ true
+ end
+ end
+ end
+end
+
Rails::Generators::AppGenerator.start
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 14d245ab2e..f0d6ea1687 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -1,4 +1,10 @@
require 'erb'
+
+begin
+ require 'psych'
+rescue LoadError
+end
+
require 'yaml'
require 'optparse'
require 'rbconfig'
@@ -74,7 +80,7 @@ module Rails
exec(find_cmd('mysql', 'mysql5'), *args)
- when "postgresql"
+ when "postgresql", "postgres"
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
@@ -113,5 +119,5 @@ end
# Has to set the RAILS_ENV before config/application is required
if ARGV.first && !ARGV.first.index("-") && env = ARGV.first
- ENV['RAILS_ENV'] = %w(production development test).find { |e| e.index(env) } || env
+ ENV['RAILS_ENV'] = %w(production development test).detect {|e| e =~ /^#{env}/} || env
end
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 8b2cd1bdba..048af7cbef 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -276,12 +276,11 @@ end
require 'optparse'
module Commands
class Plugin
- attr_reader :environment, :script_name, :sources
+ attr_reader :environment, :script_name
def initialize
@environment = RailsEnvironment.default
@rails_root = RailsEnvironment.default.root
@script_name = File.basename($0)
- @sources = []
end
def environment=(value)
@@ -301,8 +300,6 @@ module Commands
o.on("-r", "--root=DIR", String,
"Set an explicit rails app directory.",
"Default: #{@rails_root}") { |rails_root| @rails_root = rails_root; self.environment = RailsEnvironment.new(@rails_root) }
- o.on("-s", "--source=URL1,URL2", Array,
- "Use the specified plugin repositories instead of the defaults.") { |sources| @sources = sources}
o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
o.on("-h", "--help", "Show this help message.") { puts o; exit }
@@ -315,8 +312,6 @@ module Commands
o.separator ""
o.separator "EXAMPLES"
- o.separator " Install a plugin:"
- o.separator " #{@script_name} plugin install continuous_builder\n"
o.separator " Install a plugin from a subversion URL:"
o.separator " #{@script_name} plugin install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder\n"
o.separator " Install a plugin from a git URL:"
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index c3927b6613..e447209242 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -42,6 +42,10 @@ module Rails
set_environment
end
+ def app
+ @app ||= super.instance
+ end
+
def opt_parser
Options.new
end
diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb
index 9d9763699d..95c74baae2 100644
--- a/railties/lib/rails/console/app.rb
+++ b/railties/lib/rails/console/app.rb
@@ -26,7 +26,7 @@ end
# reloads the environment
def reload!(print=true)
puts "Reloading..." if print
- # This triggers the to_prepare callbacks
- ActionDispatch::Callbacks.new(Proc.new {}, false).call({})
+ ActionDispatch::Reloader.cleanup!
+ ActionDispatch::Reloader.prepare!
true
end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index cda0e0a135..7c26234750 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -5,19 +5,20 @@ require 'rbconfig'
require 'rails/engine/railties'
module Rails
- # Rails::Engine allows you to wrap a specific Rails application and share it accross
- # different applications. Since Rails 3.0, every Rails::Application is nothing
- # more than an Engine, allowing you to share it very easily.
+ # Rails::Engine allows you to wrap a specific Rails application and share it across
+ # different applications. Since Rails 3.0, every <tt>Rails::Application</tt> is nothing
+ # more than an engine, allowing you to share it very easily.
#
- # Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and
- # generators) and configuration available in the latter can also be used in the former.
+ # Any <tt>Rails::Engine</tt> is also a <tt>Rails::Railtie</tt>, so the same methods
+ # (like <tt>rake_tasks</tt> and +generators+) and configuration available in the
+ # latter can also be used in the former.
#
# == Creating an Engine
#
- # In Rails versions before to 3.0, your gems automatically behaved as Engine, however
+ # In Rails versions prior to 3.0, your gems automatically behaved as engines, however,
# this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically
- # behave as Engine, you have to specify an Engine for it somewhere inside your plugin
- # lib folder (similar to how we specify a Railtie):
+ # behave as an engine, you have to specify an +Engine+ for it somewhere inside
+ # your plugin's +lib+ folder (similar to how we specify a +Railtie+):
#
# # lib/my_engine.rb
# module MyEngine
@@ -25,16 +26,17 @@ module Rails
# end
# end
#
- # Then ensure that this file is loaded at the top of your config/application.rb (or in
- # your Gemfile) and it will automatically load models, controllers and helpers
- # inside app, load routes at "config/routes.rb", load locales at "config/locales/*",
- # load tasks at "lib/tasks/*".
+ # Then ensure that this file is loaded at the top of your <tt>config/application.rb</tt>
+ # (or in your +Gemfile+) and it will automatically load models, controllers and helpers
+ # inside +app+, load routes at <tt>config/routes.rb</tt>, load locales at
+ # <tt>config/locales/*</tt>, and load tasks at <tt>lib/tasks/*</tt>.
#
# == Configuration
#
- # Besides the Railtie configuration which is shared across the application, in a
- # Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths,
- # which differently from a Railtie, are scoped to the current Engine.
+ # Besides the +Railtie+ configuration which is shared across the application, in a
+ # <tt>Rails::Engine</tt> you can access <tt>autoload_paths</tt>, <tt>eager_load_paths</tt>
+ # and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
+ # the current engine.
#
# Example:
#
@@ -49,7 +51,7 @@ module Rails
#
# == Generators
#
- # You can set up generators for engine with config.generators method:
+ # You can set up generators for engines with <tt>config.generators</tt> method:
#
# class MyEngine < Rails::Engine
# config.generators do |g|
@@ -59,7 +61,7 @@ module Rails
# end
# end
#
- # You can also set generators for application by using config.app_generators:
+ # You can also set generators for an application by using <tt>config.app_generators</tt>:
#
# class MyEngine < Rails::Engine
# # note that you can also pass block to app_generators in the same way you
@@ -69,25 +71,25 @@ module Rails
#
# == Paths
#
- # Since Rails 3.0, both your Application and Engines do not have hardcoded paths.
- # This means that you are not required to place your controllers at "app/controllers",
+ # Since Rails 3.0, both your application and engines do not have hardcoded paths.
+ # This means that you are not required to place your controllers at <tt>app/controllers</tt>,
# but in any place which you find convenient.
#
- # For example, let's suppose you want to lay your controllers at lib/controllers, all
- # you need to do is:
+ # For example, let's suppose you want to place your controllers in <tt>lib/controllers</tt>.
+ # All you would need to do is:
#
# class MyEngine < Rails::Engine
# paths["app/controllers"] = "lib/controllers"
# end
#
- # You can also have your controllers being loaded from both "app/controllers" and
- # "lib/controllers":
+ # You can also have your controllers loaded from both <tt>app/controllers</tt> and
+ # <tt>lib/controllers</tt>:
#
# class MyEngine < Rails::Engine
# paths["app/controllers"] << "lib/controllers"
# end
#
- # The available paths in an Engine are:
+ # The available paths in an engine are:
#
# class MyEngine < Rails::Engine
# paths["app"] #=> ["app"]
@@ -103,16 +105,17 @@ module Rails
# paths["config/routes"] #=> ["config/routes.rb"]
# end
#
- # Your Application class adds a couple more paths to this set. And as in your Application,
- # all folders under "app" are automatically added to the load path. So if you have
- # "app/observers", it's added by default.
+ # Your <tt>Application</tt> class adds a couple more paths to this set. And as in your
+ # <tt>Application</tt>,all folders under +app+ are automatically added to the load path.
+ # So if you have <tt>app/observers</tt>, it's added by default.
#
# == Endpoint
#
- # Engine can be also a rack application. It can be useful if you have a rack application that
- # you would like to wrap with Engine and provide some of the Engine's features.
+ # An engine can be also a rack application. It can be useful if you have a rack application that
+ # you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
+ #
+ # To do that, use the +endpoint+ method:
#
- # To do that, use endpoint method:
# module MyEngine
# class Engine < Rails::Engine
# endpoint MyRackApplication
@@ -121,14 +124,14 @@ module Rails
#
# Now you can mount your engine in application's routes just like that:
#
- # MyRailsApp::Application.routes.draw do
- # mount MyEngine::Engine => "/engine"
- # end
+ # MyRailsApp::Application.routes.draw do
+ # mount MyEngine::Engine => "/engine"
+ # end
#
# == Middleware stack
#
- # As Engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly
- # the same as in application:
+ # As an engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly
+ # the same as in <tt>Application</tt>:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -138,8 +141,8 @@ module Rails
#
# == Routes
#
- # If you don't specify endpoint, routes will be used as default endpoint. You can use them
- # just like you use application's routes:
+ # If you don't specify an endpoint, routes will be used as the default endpoint. You can use them
+ # just like you use an application's routes:
#
# # ENGINE/config/routes.rb
# MyEngine::Engine.routes.draw do
@@ -148,30 +151,31 @@ module Rails
#
# == Mount priority
#
- # Note that now there can be more than one router in you application and it's better to avoid
- # passing requests through many routers. Consider such situation:
+ # Note that now there can be more than one router in your application, and it's better to avoid
+ # passing requests through many routers. Consider this situation:
#
# MyRailsApp::Application.routes.draw do
# mount MyEngine::Engine => "/blog"
# match "/blog/omg" => "main#omg"
# end
#
- # MyEngine is mounted at "/blog" path and additionaly "/blog/omg" points application's controller.
- # In such situation request to "/blog/omg" will go through MyEngine and if there is no such route
- # in Engine's routes, it will be dispatched to "main#omg". It's much better to swap that:
+ # +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
+ # controller. In such a situation, requests to <tt>/blog/omg</tt> will go through +MyEngine+,
+ # and if there is no such route in +Engine+'s routes, it will be dispatched to <tt>main#omg</tt>.
+ # It's much better to swap that:
#
# MyRailsApp::Application.routes.draw do
# match "/blog/omg" => "main#omg"
# mount MyEngine::Engine => "/blog"
# end
#
- # Now, Engine will get only requests that were not handled by application.
+ # Now, +Engine+ will get only requests that were not handled by +Application+.
#
# == Asset path
#
- # When you use engine with its own public directory, you will probably want to copy or symlink it
- # to application's public directory. To simplify generating paths for assets, you can set asset_path
- # for an Engine:
+ # When you use +Engine+ with its own public directory, you will probably want to copy or symlink it
+ # to application's public directory. To simplify generating paths for assets, you can set <tt>asset_path</tt>
+ # for an engine:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -179,27 +183,30 @@ module Rails
# end
# end
#
- # With such config, asset paths will be automatically modified inside Engine:
- # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
+ # With such a config, asset paths will be automatically modified inside +Engine+:
+ #
+ # image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"
#
# == Serving static files
#
- # By default, rails use ActionDispatch::Static to serve static files in development mode. This is ok
- # while you develop your application, but when you want to deploy it, assets from engine will not be
+ # By default, Rails uses <tt>ActionDispatch::Static</tt> to serve static files in development mode. This is ok
+ # while you develop your application, but when you want to deploy it, assets from an engine will not be
# served by default. You should choose one of the two following strategies:
#
# * enable serving static files by setting config.serve_static_assets to true
- # * copy engine's public files to application's public folder with rake ENGINE_NAME:install:assets, for example
- # rake my_engine:install:assets
+ # * copy engine's public files to application's public folder with <tt>rake ENGINE_NAME:install:assets</tt>, for example
+ # <tt>rake my_engine:install:assets</tt>
#
# == Engine name
#
- # There are some places where engine's name is used:
- # * routes: when you mount engine with mount(MyEngine::Engine => '/my_engine'), it's used as default :as option
- # * some of the rake tasks are based on engine name, e.g. my_engine:install:migrations, my_engine:install:assets
+ # There are some places where an Engine's name is used:
+ # * 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>
#
- # Engine name is set by default based on class name. For MyEngine::Engine it will be my_engine_engine.
- # You can change it manually it manually using engine_name method:
+ # 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 it manually using the <tt>engine_name</tt> method:
#
# module MyEngine
# class Engine < Rails::Engine
@@ -207,14 +214,14 @@ module Rails
# end
# end
#
- # == Namespaced Engine
+ # == Isolated Engine
#
- # Normally when you create controllers, helpers and models inside engine, they are treated
- # as they were created inside the application. This means all applications helpers and named routes
- # will be available to your engine controllers.
+ # Normally when you create controllers, helpers and models inside an engine, they are treated
+ # as they were created inside the application. This means all application helpers and named routes
+ # will be available to your engine's controllers.
#
- # However, sometimes you want to isolate your engine from the application, specially if your engine
- # have its own router. To do that, you simply need to call +isolate_namespace+. This method requires
+ # However, sometimes you want to isolate your engine from the application, especially if your engine
+ # has its own router. To do that, you simply need to call +isolate_namespace+. This method requires
# you to pass a module where all your controllers, helpers and models should be nested to:
#
# module MyEngine
@@ -223,7 +230,8 @@ module Rails
# end
# end
#
- # With such Engine, everything that is inside MyEngine module, will be isolated from application.
+ # With such an engine, everything that is inside the +MyEngine+ module will be isolated from
+ # the application.
#
# Consider such controller:
#
@@ -232,24 +240,24 @@ module Rails
# end
# end
#
- # If engine is marked as isolated, FooController has access only to helpers from engine and
- # url_helpers from MyEngine::Engine.routes.
+ # If an engine is marked as isolated, +FooController+ has access only to helpers from +Engine+ and
+ # <tt>url_helpers</tt> from <tt>MyEngine::Engine.routes</tt>.
#
- # The next thing that changes in isolated engine is routes behaviour. Normally, when you namespace
- # your controllers, you also need to do namespace all your routes. With isolated engine,
+ # The next thing that changes in isolated engines is the behaviour of routes. Normally, when you namespace
+ # your controllers, you also need to do namespace all your routes. With an isolated engine,
# the namespace is applied by default, so you can ignore it in routes:
#
# MyEngine::Engine.routes.draw do
# resources :articles
# end
- #
- # The routes above will automatically point to MyEngine::ApplicationContoller. Further more, you don't
- # need to use longer url helpers like "my_engine_articles_path". Instead, you shuold simply use
- # articles_path as you would do with your application.
- #
- # To make that behaviour consistent with other parts of framework, isolated engine has influence also on
- # ActiveModel::Naming. When you use namespaced model, like MyEngine::Article, it will normally
- # use the prefix "my_engine". In isolated engine, the prefix will be ommited in url helpers and
+ #
+ # The routes above will automatically point to <tt>MyEngine::ApplicationContoller</tt>. Furthermore, you don't
+ # need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you shuold simply use
+ # <tt>articles_path</tt> as you would do with your application.
+ #
+ # To make that behaviour consistent with other parts of the framework, an isolated engine also has influence on
+ # <tt>ActiveModel::Naming</tt>. When you use a namespaced model, like <tt>MyEngine::Article</tt>, it will normally
+ # use the prefix "my_engine". In an isolated engine, the prefix will be ommited in url helpers and
# form fields for convenience.
#
# polymorphic_url(MyEngine::Article.new) #=> "articles_path"
@@ -264,9 +272,9 @@ module Rails
#
# == Using Engine's routes outside Engine
#
- # Since now you can mount engine inside application's routes, you do not have direct access to engine's
- # url_helpers inside application. When you mount Engine in application's routes, a special helper is
- # created to allow you to do that. Consider such scenario:
+ # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s
+ # <tt>url_helpers</tt> inside +Application+. When you mount an engine in an application's routes, a special helper is
+ # created to allow you to do that. Consider such a scenario:
#
# # APP/config/routes.rb
# MyApplication::Application.routes.draw do
@@ -274,7 +282,7 @@ module Rails
# match "/foo" => "foo#index"
# end
#
- # Now, you can use my_engine helper inside your application:
+ # Now, you can use the <tt>my_engine</tt> helper inside your application:
#
# class FooController < ApplicationController
# def index
@@ -282,7 +290,7 @@ module Rails
# end
# end
#
- # There is also 'main_app' helper that gives you access to application's routes inside Engine:
+ # There is also a <tt>main_app</tt> helper that gives you access to application's routes inside Engine:
#
# module MyEngine
# class BarController
@@ -292,34 +300,34 @@ module Rails
# end
# end
#
- # Note that the :as option given to mount takes the engine_name as default, so most of the time
- # you can simply ommit it.
+ # Note that the <tt>:as</tt> option given to mount takes the <tt>engine_name</tT> as default, so most of the time
+ # you can simply omit it.
#
- # Finally, if you want to generate url to engine's route using polymorphic_url, you also need
+ # Finally, if you want to generate a url to an engine's route using <tt>polymorphic_url</tt>, you also need
# to pass the engine helper. Let's say that you want to create a form pointing to one of the
# engine's routes. All you need to do is pass the helper as the first element in array with
# attributes for url:
#
- # form_for([my_engine, @user])
+ # form_for([my_engine, @user])
#
- # This code will use my_engine.user_path(@user) to generate the proper route.
+ # This code will use <tt>my_engine.user_path(@user)</tt> to generate the proper route.
#
# == Migrations & seed data
#
- # Engines can have their own migrations. Default path for migrations is exactly the same
- # as in application: db/migrate
+ # Engines can have their own migrations. The default path for migrations is exactly the same
+ # as in application: <tt>db/migrate</tt>
#
# To use engine's migrations in application you can use rake task, which copies them to
# application's dir:
#
# rake ENGINE_NAME:install:migrations
#
- # Note that some of the migrations may be skipped if migration with the same name already exists
- # in application. In such situation you must decide whether to leave that migration or rename the
+ # Note that some of the migrations may be skipped if a migration with the same name already exists
+ # in application. In such a situation you must decide whether to leave that migration or rename the
# migration in application and rerun copying migrations.
#
# If your engine has migrations, you may also want to prepare data for the database in
- # seeds.rb file. You can load that data using load_seed method, e.g.
+ # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
#
# MyEngine::Engine.load_seed
#
@@ -374,7 +382,10 @@ module Rails
# Finds engine with given path
def find(path)
- Rails::Engine::Railties.engines.find { |r| File.expand_path(r.root.to_s) == File.expand_path(path.to_s) }
+ path = path.to_s
+ Rails::Engine::Railties.engines.find { |r|
+ File.expand_path(r.root.to_s) == File.expand_path(path)
+ }
end
end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 66c4088a68..29e693dfb0 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -155,7 +155,7 @@ module Rails
# commands.
def self.invoke(namespace, args=ARGV, config={})
names = namespace.to_s.split(':')
- if klass = find_by_namespace(names.pop, names.shift)
+ if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
klass.start(args, config)
else
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 2d0c10efca..ab7ed4eb9e 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -112,12 +112,7 @@ module Rails
end
def database_gemfile_entry
- entry = ""
- unless options[:skip_active_record]
- entry = "gem '#{gem_for_database}'"
- entry << ", :require => '#{require_for_database}'" if require_for_database
- end
- entry
+ options[:skip_active_record] ? "" : "gem '#{gem_for_database}'"
end
def rails_gemfile_entry
@@ -150,19 +145,12 @@ gem 'rails', '#{Rails::VERSION::STRING}'
case options[:database]
when "oracle" then "ruby-oci8"
when "postgresql" then "pg"
- when "sqlite3" then "sqlite3-ruby"
when "frontbase" then "ruby-frontbase"
when "mysql" then "mysql2"
else options[:database]
end
end
- def require_for_database
- case options[:database]
- when "sqlite3" then "sqlite3"
- end
- end
-
def bundle_if_dev_or_edge
bundle_command = File.basename(Thor::Util.ruby_command).sub(/ruby/, 'bundle')
run "#{bundle_command} install" if dev_or_edge?
@@ -171,6 +159,12 @@ gem 'rails', '#{Rails::VERSION::STRING}'
def dev_or_edge?
options.dev? || options.edge?
end
+
+ def empty_directory_with_gitkeep(destination, config = {})
+ empty_directory(destination, config)
+ create_file("#{destination}/.gitkeep") unless options[:skip_git]
+ end
+
end
end
end
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index f97f3db588..dfecd2a6e4 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -3,7 +3,7 @@ begin
rescue LoadError
puts "Thor is not available.\nIf you ran this command from a git checkout " \
"of Rails, please make sure thor is installed,\nand run this command " \
- "as `ruby #{$0} #{ARGV.join(" ")} --dev`"
+ "as `ruby #{$0} #{(ARGV | ['--dev']).join(" ")}`"
exit
end
@@ -274,7 +274,7 @@ module Rails
# Use Rails default banner.
#
def self.banner
- "rails generate #{generator_name} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]"
+ "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
end
# Sets the base_name taking into account the current class namespace.
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index e0dde4360f..2af7f85463 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -42,7 +42,7 @@ module Rails
end
def wrap_with_namespace(content)
- content = indent(content)
+ content = indent(content).chomp
"module #{namespace.name}\n#{content}\nend\n"
end
@@ -118,11 +118,11 @@ module Rails
end
def singular_table_name
- @singular_table_name ||= table_name.singularize
+ @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name)
end
def plural_table_name
- @plural_table_name ||= table_name.pluralize
+ @plural_table_name ||= (pluralize_table_names? ? table_name : table_name.pluralize)
end
def plural_file_name
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index ef1eb8d237..3f6ff35a86 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -63,7 +63,7 @@ module Rails
end
def database_yml
- template "config/databases/#{@options[:database]}.yml", "config/database.yml"
+ template "config/databases/#{options[:database]}.yml", "config/database.yml"
end
def db
@@ -104,18 +104,18 @@ module Rails
def javascripts
empty_directory "public/javascripts"
-
+
unless options[:skip_javascript]
- copy_file "public/javascripts/#{@options[:javascript]}.js"
- copy_file "public/javascripts/#{@options[:javascript]}_ujs.js", "public/javascripts/rails.js"
-
- if options[:prototype]
+ copy_file "public/javascripts/#{options[:javascript]}.js"
+ copy_file "public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js"
+
+ if options[:javascript] == "prototype"
copy_file "public/javascripts/controls.js"
copy_file "public/javascripts/dragdrop.js"
copy_file "public/javascripts/effects.js"
end
end
-
+
copy_file "public/javascripts/application.js"
end
@@ -284,6 +284,7 @@ module Rails
def app_const_base
@app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, '_').squeeze('_').camelize
end
+ alias :camelized :app_const_base
def app_const
@app_const ||= "#{app_const_base}::Application"
@@ -317,11 +318,6 @@ module Rails
].find { |f| File.exist?(f) } unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
end
- def empty_directory_with_gitkeep(destination, config = {})
- empty_directory(destination, config)
- create_file("#{destination}/.gitkeep") unless options[:skip_git]
- end
-
def get_builder_class
defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 86b9e8f40c..c383d4842f 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -12,13 +12,13 @@ source 'http://rubygems.org'
# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
-# gem 'ruby-debug19'
+# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
-# gem 'sqlite3-ruby', :require => 'sqlite3'
-# gem 'aws-s3', :require => 'aws/s3'
+# gem 'sqlite3'
+# gem 'rack-bug', :require => 'rack/bug'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
@@ -26,3 +26,6 @@ source 'http://rubygems.org'
# group :development, :test do
# gem 'webrat'
# end
+
+# Needed for guides generation
+# gem "RedCloth", "~> 4.2"
diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README
index fe7013d52d..9f0f1d0e38 100644
--- a/railties/lib/rails/generators/rails/app/templates/README
+++ b/railties/lib/rails/generators/rails/app/templates/README
@@ -91,7 +91,7 @@ mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
- @posts = Post.find(:all)
+ @posts = Post.all
debugger
end
end
@@ -139,7 +139,7 @@ To reload your controllers and models after launching the console run
<tt>reload!</tt>
More information about irb can be found at:
-link:http://www.rubycentral.com/pickaxe/irb.html
+link:http://www.rubycentral.org/pickaxe/irb.html
== dbconsole
diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
index 1de78eecae..6d56c331c1 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
@@ -1,7 +1,7 @@
<!DOCTYPE html>
<html>
<head>
- <title><%= app_const_base %></title>
+ <title><%= camelized %></title>
<%%= stylesheet_link_tag :all %>
<%%= javascript_include_tag :defaults %>
<%%= csrf_meta_tags %>
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 6e515756fe..b7f64af339 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -57,5 +57,10 @@ module <%= app_const_base %>
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
+
+<% unless options[:skip_active_record] -%>
+ # Enable IdentityMap for Active Record, to disable set to false or remove the line below.
+ config.active_record.identity_map = true
+<% end -%>
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/boot.rb b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
index ab6cb374de..4489e58688 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/boot.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
@@ -1,13 +1,6 @@
require 'rubygems'
# Set up gems listed in the Gemfile.
-gemfile = File.expand_path('../../Gemfile', __FILE__)
-begin
- ENV['BUNDLE_GEMFILE'] = gemfile
- require 'bundler'
- Bundler.setup
-rescue Bundler::GemNotFound => e
- STDERR.puts e.message
- STDERR.puts "Try running `bundle install`."
- exit!
-end if File.exist?(gemfile)
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
index 025d62a8d8..90d87cc295 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml
@@ -1,5 +1,5 @@
# SQLite version 3.x
-# gem install sqlite3-ruby (not necessary on OS X Leopard)
+# gem install sqlite3
development:
adapter: sqlite3
database: db/development.sqlite3
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index af64fae5e7..f0fa30c536 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -1,4 +1,4 @@
.bundle
db/*.sqlite3
log/*.log
-tmp/**/*
+tmp/
diff --git a/railties/lib/rails/generators/rails/app/templates/public/index.html b/railties/lib/rails/generators/rails/app/templates/public/index.html
index 75d5edd06d..13a203dd08 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/index.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/index.html
@@ -52,7 +52,6 @@
clear: both;
}
-
#header, #about, #getting-started {
padding-left: 75px;
padding-right: 30px;
@@ -168,6 +167,9 @@
margin-bottom: 5px;
}
+ .filename {
+ font-style: italic;
+ }
</style>
<script type="text/javascript">
function about() {
@@ -190,10 +192,10 @@
<li>
<h3>Browse the documentation</h3>
<ul class="links">
- <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
- <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
- <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
<li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
+ <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
+ <li><a href="http://www.ruby-doc.org/core/">Ruby core</a></li>
+ <li><a href="http://www.ruby-doc.org/stdlib/">Ruby standard library</a></li>
</ul>
</li>
</ul>
@@ -221,13 +223,13 @@
</li>
<li>
- <h2>Set up a default route and remove or rename this file</h2>
- <p>Routes are set up in config/routes.rb.</p>
+ <h2>Set up a default route and remove <span class="filename">public/index.html</span></h2>
+ <p>Routes are set up in <span class="filename">config/routes.rb</span>.</p>
</li>
<li>
<h2>Create your database</h2>
- <p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
+ <p>Run <code>rake db:create</code> to create your database. If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p>
</li>
</ol>
</div>
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
index a4f114586c..aa3a4f34fd 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery.js
@@ -1,17 +1,17 @@
/*!
- * jQuery JavaScript Library v1.4.4
+ * jQuery JavaScript Library v1.5
* http://jquery.com/
*
- * Copyright 2010, John Resig
+ * Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
- * Copyright 2010, The Dojo Foundation
+ * Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
- * Date: Thu Nov 11 19:04:53 2010 -0500
+ * Date: Mon Jan 31 08:31:29 2011 -0500
*/
(function( window, undefined ) {
@@ -22,7 +22,7 @@ var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
- return new jQuery.fn.init( selector, context );
+ return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
@@ -38,20 +38,13 @@ var jQuery = function( selector, context ) {
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
- // Is it a simple selector
- isSimple = /^.[^:#\[\.,]*$/,
-
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
- rwhite = /\s/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
- // Check for non-word characters
- rnonword = /\W/,
-
// Check for digits
rdigit = /\d/,
@@ -75,12 +68,15 @@ var jQuery = function( selector, context ) {
// For matching the engine and version of the browser
browserMatch,
-
+
// Has the ready events already been bound?
readyBound = false,
-
- // The functions to execute on DOM ready
- readyList = [],
+
+ // The deferred used on DOM ready
+ readyList,
+
+ // Promise methods
+ promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
// The ready event handler
DOMContentLoaded,
@@ -92,12 +88,13 @@ var jQuery = function( selector, context ) {
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
-
+
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
- init: function( selector, context ) {
+ constructor: jQuery,
+ init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
@@ -111,7 +108,7 @@ jQuery.fn = jQuery.prototype = {
this.length = 1;
return this;
}
-
+
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
@@ -131,6 +128,7 @@ jQuery.fn = jQuery.prototype = {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
@@ -148,11 +146,11 @@ jQuery.fn = jQuery.prototype = {
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
- selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
+ selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
-
+
return jQuery.merge( this, selector );
-
+
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
@@ -176,13 +174,6 @@ jQuery.fn = jQuery.prototype = {
return this;
}
- // HANDLE: $("TAG")
- } else if ( !context && !rnonword.test( selector ) ) {
- this.selector = selector;
- this.context = document;
- selector = document.getElementsByTagName( selector );
- return jQuery.merge( this, selector );
-
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
@@ -190,7 +181,7 @@ jQuery.fn = jQuery.prototype = {
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
- return jQuery( context ).find( selector );
+ return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
@@ -211,7 +202,7 @@ jQuery.fn = jQuery.prototype = {
selector: "",
// The current version of jQuery being used
- jquery: "1.4.4",
+ jquery: "1.5",
// The default length of a jQuery object is 0
length: 0,
@@ -234,18 +225,18 @@ jQuery.fn = jQuery.prototype = {
this.toArray() :
// Return just the object
- ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
+ ( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
- var ret = jQuery();
+ var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
-
+
} else {
jQuery.merge( ret, elems );
}
@@ -271,25 +262,17 @@ jQuery.fn = jQuery.prototype = {
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
-
+
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
- // If the DOM is already ready
- if ( jQuery.isReady ) {
- // Execute the function immediately
- fn.call( document, jQuery );
-
- // Otherwise, remember the function for later
- } else if ( readyList ) {
- // Add the function to the wait list
- readyList.push( fn );
- }
+ // Add the callback
+ readyList.done( fn );
return this;
},
-
+
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
@@ -314,9 +297,9 @@ jQuery.fn = jQuery.prototype = {
return callback.call( elem, i, elem );
}));
},
-
+
end: function() {
- return this.prevObject || jQuery(null);
+ return this.prevObject || this.constructor(null);
},
// For internal use only.
@@ -403,14 +386,14 @@ jQuery.extend({
return jQuery;
},
-
+
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
-
+
// Handle when the DOM is ready
ready: function( wait ) {
// A third-party is pushing the ready event forwards
@@ -434,27 +417,15 @@ jQuery.extend({
}
// If there are functions bound, to execute
- if ( readyList ) {
- // Execute all of them
- var fn,
- i = 0,
- ready = readyList;
-
- // Reset the list of functions
- readyList = null;
-
- while ( (fn = ready[ i++ ]) ) {
- fn.call( document, jQuery );
- }
+ readyList.resolveWith( document, [ jQuery ] );
- // Trigger any bound ready events
- if ( jQuery.fn.trigger ) {
- jQuery( document ).trigger( "ready" ).unbind( "ready" );
- }
+ // Trigger any bound ready events
+ if ( jQuery.fn.trigger ) {
+ jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
-
+
bindReady: function() {
if ( readyBound ) {
return;
@@ -473,7 +444,7 @@ jQuery.extend({
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
-
+
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
@@ -482,7 +453,7 @@ jQuery.extend({
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
-
+
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
@@ -533,20 +504,20 @@ jQuery.extend({
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
-
+
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
-
+
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
-
+
var key;
for ( key in obj ) {}
-
+
return key === undefined || hasOwn.call( obj, key );
},
@@ -556,11 +527,11 @@ jQuery.extend({
}
return true;
},
-
+
error: function( msg ) {
throw msg;
},
-
+
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
@@ -568,7 +539,7 @@ jQuery.extend({
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
-
+
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test(data.replace(rvalidescape, "@")
@@ -585,6 +556,28 @@ jQuery.extend({
}
},
+ // Cross-browser xml parsing
+ // (xml & tmp used internally)
+ parseXML: function( data , xml , tmp ) {
+
+ if ( window.DOMParser ) { // Standard
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data , "text/xml" );
+ } else { // IE
+ xml = new ActiveXObject( "Microsoft.XMLDOM" );
+ xml.async = "false";
+ xml.loadXML( data );
+ }
+
+ tmp = xml.documentElement;
+
+ if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+
+ return xml;
+ },
+
noop: function() {},
// Evalulates a script in a global context
@@ -597,7 +590,7 @@ jQuery.extend({
script.type = "text/javascript";
- if ( jQuery.support.scriptEval ) {
+ if ( jQuery.support.scriptEval() ) {
script.appendChild( document.createTextNode( data ) );
} else {
script.text = data;
@@ -710,7 +703,7 @@ jQuery.extend({
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
-
+
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
@@ -752,6 +745,7 @@ jQuery.extend({
}
}
+ // Flatten any nested arrays
return ret.concat.apply( [], ret );
},
@@ -790,7 +784,7 @@ jQuery.extend({
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
-
+
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
@@ -798,19 +792,19 @@ jQuery.extend({
}
return elems;
}
-
+
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
-
+
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
-
+
return elems;
}
-
+
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
@@ -819,6 +813,155 @@ jQuery.extend({
return (new Date()).getTime();
},
+ // Create a simple deferred (one callbacks list)
+ _Deferred: function() {
+ var // callbacks list
+ callbacks = [],
+ // stored [ context , args ]
+ fired,
+ // to avoid firing when already doing so
+ firing,
+ // flag to know if the deferred has been cancelled
+ cancelled,
+ // the deferred itself
+ deferred = {
+
+ // done( f1, f2, ...)
+ done: function() {
+ if ( !cancelled ) {
+ var args = arguments,
+ i,
+ length,
+ elem,
+ type,
+ _fired;
+ if ( fired ) {
+ _fired = fired;
+ fired = 0;
+ }
+ for ( i = 0, length = args.length; i < length; i++ ) {
+ elem = args[ i ];
+ type = jQuery.type( elem );
+ if ( type === "array" ) {
+ deferred.done.apply( deferred, elem );
+ } else if ( type === "function" ) {
+ callbacks.push( elem );
+ }
+ }
+ if ( _fired ) {
+ deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
+ }
+ }
+ return this;
+ },
+
+ // resolve with given context and args
+ resolveWith: function( context, args ) {
+ if ( !cancelled && !fired && !firing ) {
+ firing = 1;
+ try {
+ while( callbacks[ 0 ] ) {
+ callbacks.shift().apply( context, args );
+ }
+ }
+ finally {
+ fired = [ context, args ];
+ firing = 0;
+ }
+ }
+ return this;
+ },
+
+ // resolve with this as context and given arguments
+ resolve: function() {
+ deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments );
+ return this;
+ },
+
+ // Has this deferred been resolved?
+ isResolved: function() {
+ return !!( firing || fired );
+ },
+
+ // Cancel
+ cancel: function() {
+ cancelled = 1;
+ callbacks = [];
+ return this;
+ }
+ };
+
+ return deferred;
+ },
+
+ // Full fledged deferred (two callbacks list)
+ Deferred: function( func ) {
+ var deferred = jQuery._Deferred(),
+ failDeferred = jQuery._Deferred(),
+ promise;
+ // Add errorDeferred methods, then and promise
+ jQuery.extend( deferred, {
+ then: function( doneCallbacks, failCallbacks ) {
+ deferred.done( doneCallbacks ).fail( failCallbacks );
+ return this;
+ },
+ fail: failDeferred.done,
+ rejectWith: failDeferred.resolveWith,
+ reject: failDeferred.resolve,
+ isRejected: failDeferred.isResolved,
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj , i /* internal */ ) {
+ if ( obj == null ) {
+ if ( promise ) {
+ return promise;
+ }
+ promise = obj = {};
+ }
+ i = promiseMethods.length;
+ while( i-- ) {
+ obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ];
+ }
+ return obj;
+ }
+ } );
+ // Make sure only one callback list will be used
+ deferred.then( failDeferred.cancel, deferred.cancel );
+ // Unexpose cancel
+ delete deferred.cancel;
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( object ) {
+ var args = arguments,
+ length = args.length,
+ deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
+ object :
+ jQuery.Deferred(),
+ promise = deferred.promise(),
+ resolveArray;
+
+ if ( length > 1 ) {
+ resolveArray = new Array( length );
+ jQuery.each( args, function( index, element ) {
+ jQuery.when( element ).then( function( value ) {
+ resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
+ if( ! --length ) {
+ deferred.resolveWith( promise, resolveArray );
+ }
+ }, deferred.reject );
+ } );
+ } else if ( deferred !== object ) {
+ deferred.resolve( object );
+ }
+ return promise;
+ },
+
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
@@ -833,9 +976,33 @@ jQuery.extend({
return { browser: match[1] || "", version: match[2] || "0" };
},
+ sub: function() {
+ function jQuerySubclass( selector, context ) {
+ return new jQuerySubclass.fn.init( selector, context );
+ }
+ jQuery.extend( true, jQuerySubclass, this );
+ jQuerySubclass.superclass = this;
+ jQuerySubclass.fn = jQuerySubclass.prototype = this();
+ jQuerySubclass.fn.constructor = jQuerySubclass;
+ jQuerySubclass.subclass = this.subclass;
+ jQuerySubclass.fn.init = function init( selector, context ) {
+ if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
+ context = jQuerySubclass(context);
+ }
+
+ return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
+ };
+ jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
+ var rootjQuerySubclass = jQuerySubclass(document);
+ return jQuerySubclass;
+ },
+
browser: {}
});
+// Create readyList deferred
+readyList = jQuery._Deferred();
+
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
@@ -858,9 +1025,8 @@ if ( indexOf ) {
};
}
-// Verify that \s matches non-breaking spaces
-// (IE fails on this test)
-if ( !rwhite.test( "\xA0" ) ) {
+// IE doesn't match non-breaking spaces with \s
+if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
@@ -914,10 +1080,7 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support = {};
- var root = document.documentElement,
- script = document.createElement("script"),
- div = document.createElement("div"),
- id = "script" + jQuery.now();
+ var div = document.createElement("div");
div.style.display = "none";
div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
@@ -974,7 +1137,7 @@ return (window.jQuery = window.$ = jQuery);
deleteExpando: true,
optDisabled: false,
checkClone: false,
- scriptEval: false,
+ _scriptEval: null,
noCloneEvent: true,
boxModel: null,
inlineBlockNeedsLayout: false,
@@ -987,32 +1150,46 @@ return (window.jQuery = window.$ = jQuery);
select.disabled = true;
jQuery.support.optDisabled = !opt.disabled;
- script.type = "text/javascript";
- try {
- script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
- } catch(e) {}
+ jQuery.support.scriptEval = function() {
+ if ( jQuery.support._scriptEval === null ) {
+ var root = document.documentElement,
+ script = document.createElement("script"),
+ id = "script" + jQuery.now();
- root.insertBefore( script, root.firstChild );
+ script.type = "text/javascript";
+ try {
+ script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
+ } catch(e) {}
- // Make sure that the execution of code works by injecting a script
- // tag with appendChild/createTextNode
- // (IE doesn't support this, fails, and uses .text instead)
- if ( window[ id ] ) {
- jQuery.support.scriptEval = true;
- delete window[ id ];
- }
+ root.insertBefore( script, root.firstChild );
+
+ // Make sure that the execution of code works by injecting a script
+ // tag with appendChild/createTextNode
+ // (IE doesn't support this, fails, and uses .text instead)
+ if ( window[ id ] ) {
+ jQuery.support._scriptEval = true;
+ delete window[ id ];
+ } else {
+ jQuery.support._scriptEval = false;
+ }
+
+ root.removeChild( script );
+ // release memory in IE
+ root = script = id = null;
+ }
+
+ return jQuery.support._scriptEval;
+ };
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
- delete script.test;
+ delete div.test;
} catch(e) {
jQuery.support.deleteExpando = false;
}
- root.removeChild( script );
-
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function click() {
// Cloning a node shouldn't copy over any
@@ -1035,10 +1212,16 @@ return (window.jQuery = window.$ = jQuery);
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function() {
- var div = document.createElement("div");
- div.style.width = div.style.paddingLeft = "1px";
+ var div = document.createElement("div"),
+ body = document.getElementsByTagName("body")[0];
- document.body.appendChild( div );
+ // Frameset documents with no body should not run this code
+ if ( !body ) {
+ return;
+ }
+
+ div.style.width = div.style.paddingLeft = "1px";
+ body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
@@ -1057,7 +1240,7 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
}
- div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";
+ div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
var tds = div.getElementsByTagName("td");
// Check if table cells still have offsetWidth/Height when they are set
@@ -1077,7 +1260,7 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
div.innerHTML = "";
- document.body.removeChild( div ).style.display = "none";
+ body.removeChild( div ).style.display = "none";
div = tds = null;
});
@@ -1087,6 +1270,14 @@ return (window.jQuery = window.$ = jQuery);
var el = document.createElement("div");
eventName = "on" + eventName;
+ // We only care about the case where non-standard event systems
+ // are used, namely in IE. Short-circuiting here helps us to
+ // avoid an eval call (in setAttribute) which can cause CSP
+ // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
+ if ( !el.attachEvent ) {
+ return true;
+ }
+
var isSupported = (eventName in el);
if ( !isSupported ) {
el.setAttribute(eventName, "return;");
@@ -1101,13 +1292,12 @@ return (window.jQuery = window.$ = jQuery);
jQuery.support.changeBubbles = eventSupported("change");
// release memory in IE
- root = script = div = all = a = null;
+ div = all = a = null;
})();
-var windowData = {},
- rbrace = /^(?:\{.*\}|\[.*\])$/;
+var rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
cache: {},
@@ -1115,8 +1305,9 @@ jQuery.extend({
// Please use with caution
uuid: 0,
- // Unique for each copy of jQuery on the page
- expando: "jQuery" + jQuery.now(),
+ // Unique for each copy of jQuery on the page
+ // Non-digits removed to match rinlinejQuery
+ expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
@@ -1127,103 +1318,171 @@ jQuery.extend({
"applet": true
},
- data: function( elem, name, data ) {
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+
+ return !!elem && !jQuery.isEmptyObject(elem);
+ },
+
+ data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
- elem = elem == window ?
- windowData :
- elem;
+ var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
- var isNode = elem.nodeType,
- id = isNode ? elem[ jQuery.expando ] : null,
- cache = jQuery.cache, thisCache;
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
- if ( isNode && !id && typeof name === "string" && data === undefined ) {
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
+
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
+
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
- // Get the data from the object directly
- if ( !isNode ) {
- cache = elem;
+ if ( !id ) {
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ } else {
+ id = jQuery.expando;
+ }
+ }
- // Compute a unique ID for the element
- } else if ( !id ) {
- elem[ jQuery.expando ] = id = ++jQuery.uuid;
+ if ( !cache[ id ] ) {
+ cache[ id ] = {};
}
- // Avoid generating a new cache unless none exists and we
- // want to manipulate it.
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
if ( typeof name === "object" ) {
- if ( isNode ) {
+ if ( pvt ) {
+ cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
+ } else {
cache[ id ] = jQuery.extend(cache[ id ], name);
+ }
+ }
- } else {
- jQuery.extend( cache, name );
+ thisCache = cache[ id ];
+
+ // Internal jQuery data is stored in a separate object inside the object's data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data
+ if ( pvt ) {
+ if ( !thisCache[ internalKey ] ) {
+ thisCache[ internalKey ] = {};
}
- } else if ( isNode && !cache[ id ] ) {
- cache[ id ] = {};
+ thisCache = thisCache[ internalKey ];
}
- thisCache = isNode ? cache[ id ] : cache;
-
- // Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
- return typeof name === "string" ? thisCache[ name ] : thisCache;
+ // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
+ // not attempt to inspect the internal events object using jQuery.data, as this
+ // internal data object is undocumented and subject to change.
+ if ( name === "events" && !thisCache[name] ) {
+ return thisCache[ internalKey ] && thisCache[ internalKey ].events;
+ }
+
+ return getByName ? thisCache[ name ] : thisCache;
},
- removeData: function( elem, name ) {
+ removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
- elem = elem == window ?
- windowData :
- elem;
+ var internalKey = jQuery.expando, isNode = elem.nodeType,
- var isNode = elem.nodeType,
- id = isNode ? elem[ jQuery.expando ] : elem,
- cache = jQuery.cache,
- thisCache = isNode ? cache[ id ] : id;
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+
+ // See jQuery.data for more information
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
+ }
- // If we want to remove a specific section of the element's data
if ( name ) {
+ var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
+
if ( thisCache ) {
- // Remove the section of cache data
delete thisCache[ name ];
- // If we've removed all the data, remove the element's cache
- if ( isNode && jQuery.isEmptyObject(thisCache) ) {
- jQuery.removeData( elem );
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( !jQuery.isEmptyObject(thisCache) ) {
+ return;
}
}
+ }
+
+ // See jQuery.data for more information
+ if ( pvt ) {
+ delete cache[ id ][ internalKey ];
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !jQuery.isEmptyObject(cache[ id ]) ) {
+ return;
+ }
+ }
- // Otherwise, we want to remove all of the element's data
+ var internalCache = cache[ id ][ internalKey ];
+
+ // Browsers that fail expando deletion also refuse to delete expandos on
+ // the window, but it will allow it on all other JS objects; other browsers
+ // don't care
+ if ( jQuery.support.deleteExpando || cache != window ) {
+ delete cache[ id ];
} else {
- if ( isNode && jQuery.support.deleteExpando ) {
- delete elem[ jQuery.expando ];
+ cache[ id ] = null;
+ }
+ // We destroyed the entire user cache at once because it's faster than
+ // iterating through each key, but we need to continue to persist internal
+ // data if it existed
+ if ( internalCache ) {
+ cache[ id ] = {};
+ cache[ id ][ internalKey ] = internalCache;
+
+ // Otherwise, we need to eliminate the expando on the node to avoid
+ // false lookups in the cache for entries that no longer exist
+ } else if ( isNode ) {
+ // IE does not allow us to delete expando properties from nodes,
+ // nor does it have a removeAttribute function on Document nodes;
+ // we must handle all of these cases
+ if ( jQuery.support.deleteExpando ) {
+ delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
-
- // Completely remove the data cache
- } else if ( isNode ) {
- delete cache[ id ];
-
- // Remove all fields from the object
} else {
- for ( var n in elem ) {
- delete elem[ n ];
- }
+ elem[ jQuery.expando ] = null;
}
}
},
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return jQuery.data( elem, name, data, true );
+ },
+
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
@@ -1244,15 +1503,17 @@ jQuery.fn.extend({
if ( typeof key === "undefined" ) {
if ( this.length ) {
- var attr = this[0].attributes, name;
data = jQuery.data( this[0] );
- for ( var i = 0, l = attr.length; i < l; i++ ) {
- name = attr[i].name;
+ if ( this[0].nodeType === 1 ) {
+ var attr = this[0].attributes, name;
+ for ( var i = 0, l = attr.length; i < l; i++ ) {
+ name = attr[i].name;
- if ( name.indexOf( "data-" ) === 0 ) {
- name = name.substr( 5 );
- dataAttr( this[0], name, data[ name ] );
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = name.substr( 5 );
+ dataAttr( this[0], name, data[ name ] );
+ }
}
}
}
@@ -1337,7 +1598,7 @@ jQuery.extend({
}
type = (type || "fx") + "queue";
- var q = jQuery.data( elem, type );
+ var q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( !data ) {
@@ -1345,7 +1606,7 @@ jQuery.extend({
}
if ( !q || jQuery.isArray(data) ) {
- q = jQuery.data( elem, type, jQuery.makeArray(data) );
+ q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
@@ -1376,6 +1637,10 @@ jQuery.extend({
jQuery.dequeue(elem, type);
});
}
+
+ if ( !queue.length ) {
+ jQuery.removeData( elem, type + "queue", true );
+ }
}
});
@@ -1425,7 +1690,7 @@ jQuery.fn.extend({
-var rclass = /[\n\t]/g,
+var rclass = /[\n\t\r]/g,
rspaces = /\s+/,
rreturn = /\r/g,
rspecialurl = /^(?:href|src|style)$/,
@@ -1558,11 +1823,11 @@ jQuery.fn.extend({
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
- jQuery.data( this, "__className__", this.className );
+ jQuery._data( this, "__className__", this.className );
}
// toggle whole className
- this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
+ this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
@@ -1607,7 +1872,7 @@ jQuery.fn.extend({
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
- if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
+ if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
@@ -1630,7 +1895,6 @@ jQuery.fn.extend({
if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
-
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
@@ -1696,10 +1960,10 @@ jQuery.extend({
height: true,
offset: true
},
-
+
attr: function( elem, name, value, pass ) {
- // don't set attributes on text and comment nodes
- if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) {
return undefined;
}
@@ -1714,88 +1978,96 @@ jQuery.extend({
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
- // These attributes require special treatment
- var special = rspecialurl.test( name );
+ // Only do all the following if this is a node (faster for style)
+ if ( elem.nodeType === 1 ) {
+ // These attributes require special treatment
+ var special = rspecialurl.test( name );
+
+ // Safari mis-reports the default selected property of an option
+ // Accessing the parent's selectedIndex property fixes it
+ if ( name === "selected" && !jQuery.support.optSelected ) {
+ var parent = elem.parentNode;
+ if ( parent ) {
+ parent.selectedIndex;
+
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ }
- // Safari mis-reports the default selected property of an option
- // Accessing the parent's selectedIndex property fixes it
- if ( name === "selected" && !jQuery.support.optSelected ) {
- var parent = elem.parentNode;
- if ( parent ) {
- parent.selectedIndex;
+ // If applicable, access the attribute via the DOM 0 way
+ // 'in' checks fail in Blackberry 4.7 #6931
+ if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
+ if ( set ) {
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
+ jQuery.error( "type property can't be changed" );
+ }
- // Make sure that it also works with optgroups, see #5701
- if ( parent.parentNode ) {
- parent.parentNode.selectedIndex;
+ if ( value === null ) {
+ if ( elem.nodeType === 1 ) {
+ elem.removeAttribute( name );
+ }
+
+ } else {
+ elem[ name ] = value;
+ }
}
- }
- }
- // If applicable, access the attribute via the DOM 0 way
- // 'in' checks fail in Blackberry 4.7 #6931
- if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
- if ( set ) {
- // We can't allow the type property to be changed (since it causes problems in IE)
- if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
- jQuery.error( "type property can't be changed" );
+ // browsers index elements by id/name on forms, give priority to attributes.
+ if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
+ return elem.getAttributeNode( name ).nodeValue;
}
- if ( value === null ) {
- if ( elem.nodeType === 1 ) {
- elem.removeAttribute( name );
- }
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ if ( name === "tabIndex" ) {
+ var attributeNode = elem.getAttributeNode( "tabIndex" );
- } else {
- elem[ name ] = value;
+ return attributeNode && attributeNode.specified ?
+ attributeNode.value :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ undefined;
}
- }
- // browsers index elements by id/name on forms, give priority to attributes.
- if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
- return elem.getAttributeNode( name ).nodeValue;
+ return elem[ name ];
}
- // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
- // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
- if ( name === "tabIndex" ) {
- var attributeNode = elem.getAttributeNode( "tabIndex" );
+ if ( !jQuery.support.style && notxml && name === "style" ) {
+ if ( set ) {
+ elem.style.cssText = "" + value;
+ }
- return attributeNode && attributeNode.specified ?
- attributeNode.value :
- rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
- 0 :
- undefined;
+ return elem.style.cssText;
}
- return elem[ name ];
- }
-
- if ( !jQuery.support.style && notxml && name === "style" ) {
if ( set ) {
- elem.style.cssText = "" + value;
+ // convert the value to a string (all browsers do this but IE) see #1070
+ elem.setAttribute( name, "" + value );
}
- return elem.style.cssText;
- }
+ // Ensure that missing attributes return undefined
+ // Blackberry 4.7 returns "" from getAttribute #6938
+ if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
+ return undefined;
+ }
- if ( set ) {
- // convert the value to a string (all browsers do this but IE) see #1070
- elem.setAttribute( name, "" + value );
- }
+ var attr = !jQuery.support.hrefNormalized && notxml && special ?
+ // Some attributes require a special call on IE
+ elem.getAttribute( name, 2 ) :
+ elem.getAttribute( name );
- // Ensure that missing attributes return undefined
- // Blackberry 4.7 returns "" from getAttribute #6938
- if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
- return undefined;
+ // Non-existent attributes return null, we normalize to undefined
+ return attr === null ? undefined : attr;
}
-
- var attr = !jQuery.support.hrefNormalized && notxml && special ?
- // Some attributes require a special call on IE
- elem.getAttribute( name, 2 ) :
- elem.getAttribute( name );
-
- // Non-existent attributes return null, we normalize to undefined
- return attr === null ? undefined : attr;
+ // Handle everything which isn't a DOM element node
+ if ( set ) {
+ elem[ name ] = value;
+ }
+ return elem[ name ];
}
});
@@ -1810,7 +2082,7 @@ var rnamespaces = /\.(.*)$/,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
},
- focusCounts = { focusin: 0, focusout: 0 };
+ eventKey = "events";
/*
* A number of helper functions used for managing events.
@@ -1852,7 +2124,7 @@ jQuery.event = {
}
// Init the element's event structure
- var elemData = jQuery.data( elem );
+ var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
@@ -1860,14 +2132,11 @@ jQuery.event = {
return;
}
- // Use a key less likely to result in collisions for plain JS objects.
- // Fixes bug #7150.
- var eventKey = elem.nodeType ? "events" : "__events__",
- events = elemData[ eventKey ],
+ var events = elemData[ eventKey ],
eventHandle = elemData.handle;
-
+
if ( typeof events === "function" ) {
- // On plain objects events is a fn that holds the the data
+ // On plain objects events is a fn that holds the data
// which prevents this data from being JSON serialized
// the function does not need to be called, it just contains the data
eventHandle = events.handle;
@@ -1945,9 +2214,9 @@ jQuery.event = {
}
}
}
-
- if ( special.add ) {
- special.add.call( elem, handleObj );
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
@@ -1979,14 +2248,13 @@ jQuery.event = {
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
- eventKey = elem.nodeType ? "events" : "__events__",
- elemData = jQuery.data( elem ),
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData[ eventKey ];
if ( !elemData || !events ) {
return;
}
-
+
if ( typeof events === "function" ) {
elemData = events;
events = events.events;
@@ -2024,7 +2292,7 @@ jQuery.event = {
namespaces = type.split(".");
type = namespaces.shift();
- namespace = new RegExp("(^|\\.)" +
+ namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
@@ -2092,10 +2360,10 @@ jQuery.event = {
delete elemData.handle;
if ( typeof elemData === "function" ) {
- jQuery.removeData( elem, eventKey );
+ jQuery.removeData( elem, eventKey, true );
} else if ( jQuery.isEmptyObject( elemData ) ) {
- jQuery.removeData( elem );
+ jQuery.removeData( elem, undefined, true );
}
}
},
@@ -2127,9 +2395,16 @@ jQuery.event = {
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
+ // XXX This code smells terrible. event.js should not be directly
+ // inspecting the data cache
jQuery.each( jQuery.cache, function() {
- if ( this.events && this.events[type] ) {
- jQuery.event.trigger( event, data, this.handle.elem );
+ // internalKey variable is just used to make it easier to find
+ // and potentially change this stuff later; currently it just
+ // points to jQuery.expando
+ var internalKey = jQuery.expando,
+ internalCache = this[ internalKey ];
+ if ( internalCache && internalCache.events && internalCache.events[type] ) {
+ jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
}
@@ -2155,8 +2430,8 @@ jQuery.event = {
// Trigger the event, it is assumed that "handle" is a function
var handle = elem.nodeType ?
- jQuery.data( elem, "handle" ) :
- (jQuery.data( elem, "__events__" ) || {}).handle;
+ jQuery._data( elem, "handle" ) :
+ (jQuery._data( elem, eventKey ) || {}).handle;
if ( handle ) {
handle.apply( elem, data );
@@ -2186,7 +2461,7 @@ jQuery.event = {
isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
- if ( (!special._default || special._default.call( elem, event ) === false) &&
+ if ( (!special._default || special._default.call( elem, event ) === false) &&
!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
try {
@@ -2234,7 +2509,7 @@ jQuery.event = {
event.namespace = event.namespace || namespace_sort.join(".");
- events = jQuery.data(this, this.nodeType ? "events" : "__events__");
+ events = jQuery._data(this, eventKey);
if ( typeof events === "function" ) {
events = events.events;
@@ -2256,7 +2531,7 @@ jQuery.event = {
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
-
+
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
@@ -2355,7 +2630,7 @@ jQuery.event = {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
- jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
+ jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
@@ -2385,7 +2660,7 @@ jQuery.removeEvent = document.removeEventListener ?
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
- } :
+ } :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
@@ -2402,6 +2677,12 @@ jQuery.Event = function( src ) {
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
+ src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
+
// Event type
} else {
this.type = src;
@@ -2432,7 +2713,7 @@ jQuery.Event.prototype = {
if ( !e ) {
return;
}
-
+
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
@@ -2518,7 +2799,7 @@ if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
- if ( this.nodeName.toLowerCase() !== "form" ) {
+ if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
@@ -2528,7 +2809,7 @@ if ( !jQuery.support.submitBubbles ) {
return trigger( "submit", this, arguments );
}
});
-
+
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
@@ -2583,14 +2864,14 @@ if ( !jQuery.support.changeBubbles ) {
return;
}
- data = jQuery.data( elem, "_change_data" );
+ data = jQuery._data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
- jQuery.data( elem, "_change_data", val );
+ jQuery._data( elem, "_change_data", val );
}
-
+
if ( data === undefined || val === data ) {
return;
}
@@ -2604,7 +2885,7 @@ if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
filters: {
- focusout: testChange,
+ focusout: testChange,
beforedeactivate: testChange,
@@ -2633,7 +2914,7 @@ if ( !jQuery.support.changeBubbles ) {
// information
beforeactivate: function( e ) {
var elem = e.target;
- jQuery.data( elem, "_change_data", getVal(elem) );
+ jQuery._data( elem, "_change_data", getVal(elem) );
}
},
@@ -2672,21 +2953,17 @@ if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
- if ( focusCounts[fix]++ === 0 ) {
- document.addEventListener( orig, handler, true );
- }
+ this.addEventListener( orig, handler, true );
},
teardown: function() {
- if ( --focusCounts[fix] === 0 ) {
- document.removeEventListener( orig, handler, true );
- }
+ this.removeEventListener( orig, handler, true );
}
};
- function handler( e ) {
+ function handler( e ) {
e = jQuery.event.fix( e );
e.type = fix;
- return jQuery.event.trigger( e, null, e.target );
+ return jQuery.event.handle.call( this, e );
}
});
}
@@ -2700,7 +2977,7 @@ jQuery.each(["bind", "one"], function( i, name ) {
}
return this;
}
-
+
if ( jQuery.isFunction( data ) || data === false ) {
fn = data;
data = undefined;
@@ -2740,20 +3017,20 @@ jQuery.fn.extend({
return this;
},
-
+
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
-
+
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
-
+
} else {
return this.die( types, null, fn, selector );
}
},
-
+
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
@@ -2782,8 +3059,8 @@ jQuery.fn.extend({
return this.click( jQuery.proxy( fn, function( event ) {
// Figure out which function to execute
- var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
- jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
+ var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
+ jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
@@ -2810,12 +3087,12 @@ jQuery.each(["live", "die"], function( i, name ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
-
+
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
-
+
return this;
}
@@ -2862,7 +3139,7 @@ jQuery.each(["live", "die"], function( i, name ) {
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
-
+
return this;
};
});
@@ -2871,17 +3148,17 @@ function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
- events = jQuery.data( this, this.nodeType ? "events" : "__events__" );
+ events = jQuery._data( this, eventKey );
if ( typeof events === "function" ) {
events = events.events;
}
- // Make sure we avoid non-left-click bubbling in Firefox (#3861)
- if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
+ // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
+ if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
-
+
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
@@ -2979,27 +3256,10 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl
}
});
-// Prevent memory leaks in IE
-// Window isn't included so as not to unbind existing unload events
-// More info:
-// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
-if ( window.attachEvent && !window.addEventListener ) {
- jQuery(window).bind("unload", function() {
- for ( var id in jQuery.cache ) {
- if ( jQuery.cache[ id ].handle ) {
- // Try/Catch is to handle iframes being unloaded, see #4280
- try {
- jQuery.event.remove( jQuery.cache[ id ].handle.elem );
- } catch(e) {}
- }
- }
- });
-}
-
/*!
- * Sizzle CSS Selector Engine - v1.0
- * Copyright 2009, The Dojo Foundation
+ * Sizzle CSS Selector Engine
+ * Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
@@ -3220,7 +3480,9 @@ Sizzle.find = function( expr, context, isXML ) {
}
if ( !set ) {
- set = context.getElementsByTagName( "*" );
+ set = typeof context.getElementsByTagName !== "undefined" ?
+ context.getElementsByTagName( "*" ) :
+ [];
}
return { set: set, expr: expr };
@@ -3328,9 +3590,9 @@ var Expr = Sizzle.selectors = {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
- ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
- CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
+ CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
@@ -3463,7 +3725,9 @@ var Expr = Sizzle.selectors = {
},
TAG: function( match, context ) {
- return context.getElementsByTagName( match[1] );
+ if ( typeof context.getElementsByTagName !== "undefined" ) {
+ return context.getElementsByTagName( match[1] );
+ }
}
},
preFilter: {
@@ -3476,7 +3740,7 @@ var Expr = Sizzle.selectors = {
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
- if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
+ if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
@@ -3500,8 +3764,14 @@ var Expr = Sizzle.selectors = {
CHILD: function( match ) {
if ( match[1] === "nth" ) {
+ if ( !match[2] ) {
+ Sizzle.error( match[0] );
+ }
+
+ match[2] = match[2].replace(/^\+|\s*/g, '');
+
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
- var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+ var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
@@ -3509,6 +3779,9 @@ var Expr = Sizzle.selectors = {
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
+ else if ( match[2] ) {
+ Sizzle.error( match[0] );
+ }
// TODO: Move to normal caching system
match[0] = done++;
@@ -3517,12 +3790,15 @@ var Expr = Sizzle.selectors = {
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
- var name = match[1].replace(/\\/g, "");
+ var name = match[1] = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
+ // Handle if an un-quoted value was used
+ match[4] = ( match[4] || match[5] || "" ).replace(/\\/g, "");
+
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
@@ -3691,7 +3967,7 @@ var Expr = Sizzle.selectors = {
return true;
} else {
- Sizzle.error( "Syntax error, unrecognized expression: " + name );
+ Sizzle.error( name );
}
},
@@ -4081,13 +4357,47 @@ if ( document.querySelectorAll ) {
Sizzle = function( query, context, extra, seed ) {
context = context || document;
- // Make sure that attribute selectors are quoted
- query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
-
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
+ // See if we find a selector to speed up
+ var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
+
+ if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
+ // Speed-up: Sizzle("TAG")
+ if ( match[1] ) {
+ return makeArray( context.getElementsByTagName( query ), extra );
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
+ return makeArray( context.getElementsByClassName( match[2] ), extra );
+ }
+ }
+
if ( context.nodeType === 9 ) {
+ // Speed-up: Sizzle("body")
+ // The body element only exists once, optimize finding it
+ if ( query === "body" && context.body ) {
+ return makeArray( [ context.body ], extra );
+
+ // Speed-up: Sizzle("#ID")
+ } else if ( match && match[3] ) {
+ var elem = context.getElementById( match[3] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id === match[3] ) {
+ return makeArray( [ elem ], extra );
+ }
+
+ } else {
+ return makeArray( [], extra );
+ }
+ }
+
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
@@ -4098,14 +4408,23 @@ if ( document.querySelectorAll ) {
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var old = context.getAttribute( "id" ),
- nid = old || id;
+ nid = old || id,
+ hasParent = context.parentNode,
+ relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
+ } else {
+ nid = nid.replace( /'/g, "\\$&" );
+ }
+ if ( relativeHierarchySelector && hasParent ) {
+ context = context.parentNode;
}
try {
- return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra );
+ if ( !relativeHierarchySelector || hasParent ) {
+ return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
+ }
} catch(pseudoError) {
} finally {
@@ -4328,7 +4647,14 @@ var runtil = /Until$/,
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
- POS = jQuery.expr.match.POS;
+ POS = jQuery.expr.match.POS,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
jQuery.fn.extend({
find: function( selector ) {
@@ -4373,7 +4699,7 @@ jQuery.fn.extend({
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
-
+
is: function( selector ) {
return !!selector && jQuery.filter( selector, this ).length > 0;
},
@@ -4391,7 +4717,7 @@ jQuery.fn.extend({
selector = selectors[i];
if ( !matches[selector] ) {
- matches[selector] = jQuery.expr.match.POS.test( selector ) ?
+ matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
@@ -4414,7 +4740,7 @@ jQuery.fn.extend({
return ret;
}
- var pos = POS.test( selectors ) ?
+ var pos = POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;
for ( i = 0, l = this.length; i < l; i++ ) {
@@ -4435,10 +4761,10 @@ jQuery.fn.extend({
}
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
-
+
return this.pushStack( ret, "closest", selectors );
},
-
+
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
@@ -4456,7 +4782,7 @@ jQuery.fn.extend({
add: function( selector, context ) {
var set = typeof selector === "string" ?
- jQuery( selector, context || this.context ) :
+ jQuery( selector, context ) :
jQuery.makeArray( selector ),
all = jQuery.merge( this.get(), set );
@@ -4518,8 +4844,13 @@ jQuery.each({
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
- var ret = jQuery.map( this, fn, until );
-
+ var ret = jQuery.map( this, fn, until ),
+ // The variable 'args' was introduced in
+ // https://github.com/jquery/jquery/commit/52a0238
+ // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
+ // http://code.google.com/p/v8/issues/detail?id=1050
+ args = slice.call(arguments);
+
if ( !runtil.test( name ) ) {
selector = until;
}
@@ -4528,13 +4859,13 @@ jQuery.each({
ret = jQuery.filter( selector, ret );
}
- ret = this.length > 1 ? jQuery.unique( ret ) : ret;
+ ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
- return this.pushStack( ret, name, slice.call(arguments).join(",") );
+ return this.pushStack( ret, name, args.join(",") );
};
});
@@ -4548,7 +4879,7 @@ jQuery.extend({
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
-
+
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
@@ -4630,7 +4961,6 @@ var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked (html5)
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
- raction = /\=([^="'>\s]+\/)>/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
@@ -4770,7 +5100,7 @@ jQuery.fn.extend({
return set;
}
},
-
+
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
@@ -4785,7 +5115,7 @@ jQuery.fn.extend({
}
}
}
-
+
return this;
},
@@ -4801,48 +5131,17 @@ jQuery.fn.extend({
elem.removeChild( elem.firstChild );
}
}
-
+
return this;
},
- clone: function( events ) {
- // Do the clone
- var ret = this.map(function() {
- if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
- // IE copies events bound via attachEvent when
- // using cloneNode. Calling detachEvent on the
- // clone will also remove the events from the orignal
- // In order to get around this, we use innerHTML.
- // Unfortunately, this means some modifications to
- // attributes in IE that are actually only stored
- // as properties will not be copied (such as the
- // the name attribute on an input).
- var html = this.outerHTML,
- ownerDocument = this.ownerDocument;
-
- if ( !html ) {
- var div = ownerDocument.createElement("div");
- div.appendChild( this.cloneNode(true) );
- html = div.innerHTML;
- }
-
- return jQuery.clean([html.replace(rinlinejQuery, "")
- // Handle the case in IE 8 where action=/test/> self-closes a tag
- .replace(raction, '="$1">')
- .replace(rleadingWhitespace, "")], ownerDocument)[0];
- } else {
- return this.cloneNode(true);
- }
- });
+ clone: function( dataAndEvents, deepDataAndEvents ) {
+ dataAndEvents = dataAndEvents == null ? true : dataAndEvents;
+ deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
- // Copy the events from the original to the clone
- if ( events === true ) {
- cloneCopyEvent( this, ret );
- cloneCopyEvent( this.find("*"), ret.find("*") );
- }
-
- // Return the cloned set
- return ret;
+ return this.map( function () {
+ return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+ });
},
html: function( value ) {
@@ -4952,9 +5251,9 @@ jQuery.fn.extend({
} else {
results = jQuery.buildFragment( args, this, scripts );
}
-
+
fragment = results.fragment;
-
+
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
@@ -4964,13 +5263,20 @@ jQuery.fn.extend({
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
- for ( var i = 0, l = this.length; i < l; i++ ) {
+ for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
- i > 0 || results.cacheable || this.length > 1 ?
- fragment.cloneNode(true) :
+ // Make sure that we do not leak memory by inadvertently discarding
+ // the original fragment (which might have attached data) instead of
+ // using it; in addition, use the original fragment object for the last
+ // item instead of first because it can end up being emptied incorrectly
+ // in certain situations (Bug #8070).
+ // Fragments from the fragment cache must always be cloned and never used
+ // in place.
+ results.cacheable || (l > 1 && i < lastIndex) ?
+ jQuery.clone( fragment, true, true ) :
fragment
);
}
@@ -4992,41 +5298,97 @@ function root( elem, cur ) {
elem;
}
-function cloneCopyEvent(orig, ret) {
- var i = 0;
+function cloneCopyEvent( src, dest ) {
- ret.each(function() {
- if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
- return;
- }
+ if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
+ return;
+ }
- var oldData = jQuery.data( orig[i++] ),
- curData = jQuery.data( this, oldData ),
- events = oldData && oldData.events;
+ var internalKey = jQuery.expando,
+ oldData = jQuery.data( src ),
+ curData = jQuery.data( dest, oldData );
+
+ // Switch to use the internal data object, if it exists, for the next
+ // stage of data copying
+ if ( (oldData = oldData[ internalKey ]) ) {
+ var events = oldData.events;
+ curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
- for ( var handler in events[ type ] ) {
- jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
+ for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add( dest, type, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
- });
+ }
+}
+
+function cloneFixAttributes(src, dest) {
+ // We do not need to do anything for non-Elements
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ var nodeName = dest.nodeName.toLowerCase();
+
+ // clearAttributes removes the attributes, which we don't want,
+ // but also removes the attachEvent events, which we *do* want
+ dest.clearAttributes();
+
+ // mergeAttributes, in contrast, only merges back on the
+ // original attributes, not the events
+ dest.mergeAttributes(src);
+
+ // IE6-8 fail to clone children inside object elements that use
+ // the proprietary classid attribute value (rather than the type
+ // attribute) to identify the type of content to display
+ if ( nodeName === "object" ) {
+ dest.outerHTML = src.outerHTML;
+
+ } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
+ // IE6-8 fails to persist the checked state of a cloned checkbox
+ // or radio button. Worse, IE6-7 fail to give the cloned element
+ // a checked appearance if the defaultChecked value isn't also set
+ if ( src.checked ) {
+ dest.defaultChecked = dest.checked = src.checked;
+ }
+
+ // IE6-7 get confused and end up setting the value of a cloned
+ // checkbox/radio button to an empty string instead of "on"
+ if ( dest.value !== src.value ) {
+ dest.value = src.value;
+ }
+
+ // IE6-8 fails to return the selected option to the default selected
+ // state when cloning options
+ } else if ( nodeName === "option" ) {
+ dest.selected = src.defaultSelected;
+
+ // IE6-8 fails to set the defaultValue to the correct value when
+ // cloning other types of input fields
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+
+ // Event data gets referenced instead of copied if the expando
+ // gets copied too
+ dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
- // Only cache "small" (1/2 KB) strings that are associated with the main document
+ // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
- !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
+ args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
@@ -5062,24 +5424,72 @@ jQuery.each({
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
-
+
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
-
+
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
-
+
return this.pushStack( ret, name, insert.selector );
}
};
});
jQuery.extend({
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var clone = elem.cloneNode(true),
+ srcElements,
+ destElements,
+ i;
+
+ if ( !jQuery.support.noCloneEvent && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
+ // IE copies events bound via attachEvent when using cloneNode.
+ // Calling detachEvent on the clone will also remove the events
+ // from the original. In order to get around this, we use some
+ // proprietary methods to clear the events. Thanks to MooTools
+ // guys for this hotness.
+
+ // Using Sizzle here is crazy slow, so we use getElementsByTagName
+ // instead
+ srcElements = elem.getElementsByTagName("*");
+ destElements = clone.getElementsByTagName("*");
+
+ // Weird iteration because IE will replace the length property
+ // with an element if you are cloning the body and one of the
+ // elements on the page has a name or id of "length"
+ for ( i = 0; srcElements[i]; ++i ) {
+ cloneFixAttributes( srcElements[i], destElements[i] );
+ }
+
+ cloneFixAttributes( elem, clone );
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+
+ cloneCopyEvent( elem, clone );
+
+ if ( deepDataAndEvents && "getElementsByTagName" in elem ) {
+
+ srcElements = elem.getElementsByTagName("*");
+ destElements = clone.getElementsByTagName("*");
+
+ if ( srcElements.length ) {
+ for ( i = 0; srcElements[i]; ++i ) {
+ cloneCopyEvent( srcElements[i], destElements[i] );
+ }
+ }
+ }
+ }
+ // Return the cloned set
+ return clone;
+ },
clean: function( elems, context, fragment, scripts ) {
context = context || document;
@@ -5161,7 +5571,7 @@ jQuery.extend({
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
-
+
} else {
if ( ret[i].nodeType === 1 ) {
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
@@ -5173,40 +5583,45 @@ jQuery.extend({
return ret;
},
-
+
cleanData: function( elems ) {
- var data, id, cache = jQuery.cache,
- special = jQuery.event.special,
+ var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
-
+
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
-
+
if ( id ) {
- data = cache[ id ];
-
+ data = cache[ id ] && cache[ id ][ internalKey ];
+
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
+ // This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
+
+ // Null the DOM reference to avoid IE6/7/8 leak (#7054)
+ if ( data.handle ) {
+ data.handle.elem = null;
+ }
}
-
+
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
-
+
delete cache[ id ];
}
}
@@ -5495,8 +5910,9 @@ if ( document.defaultView && document.defaultView.getComputedStyle ) {
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
- var left, rsLeft,
+ var left,
ret = elem.currentStyle && elem.currentStyle[ name ],
+ rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
@@ -5507,16 +5923,19 @@ if ( document.documentElement.currentStyle ) {
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
- rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
- elem.runtimeStyle.left = elem.currentStyle.left;
+ if ( rsLeft ) {
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ }
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
- elem.runtimeStyle.left = rsLeft;
+ if ( rsLeft ) {
+ elem.runtimeStyle.left = rsLeft;
+ }
}
return ret === "" ? "auto" : ret;
@@ -5565,21 +5984,117 @@ if ( jQuery.expr && jQuery.expr.filters ) {
-var jsc = jQuery.now(),
- rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
- rselectTextarea = /^(?:select|textarea)/i,
+var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rhash = /#.*$/,
+ rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rnoContent = /^(?:GET|HEAD)$/,
- rbracket = /\[\]$/,
- jsre = /\=\?(&|$)/,
+ rprotocol = /^\/\//,
rquery = /\?/,
+ rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
+ rselectTextarea = /^(?:select|textarea)/i,
+ rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
- rurl = /^(\w+:)?\/\/([^\/?#]+)/,
- r20 = /%20/g,
- rhash = /#.*$/,
+ rurl = /^(\w+:)\/\/([^\/?#:]+)(?::(\d+))?/,
// Keep a copy of the old load method
- _load = jQuery.fn.load;
+ _load = jQuery.fn.load,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {};
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ if ( jQuery.isFunction( func ) ) {
+ var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
+ i = 0,
+ length = dataTypes.length,
+ dataType,
+ list,
+ placeBefore;
+
+ // For each dataType in the dataTypeExpression
+ for(; i < length; i++ ) {
+ dataType = dataTypes[ i ];
+ // We control if we're asked to add before
+ // any existing element
+ placeBefore = /^\+/.test( dataType );
+ if ( placeBefore ) {
+ dataType = dataType.substr( 1 ) || "*";
+ }
+ list = structure[ dataType ] = structure[ dataType ] || [];
+ // then we add to the structure accordingly
+ list[ placeBefore ? "unshift" : "push" ]( func );
+ }
+ }
+ };
+}
+
+//Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jXHR,
+ dataType /* internal */, inspected /* internal */ ) {
+
+ dataType = dataType || options.dataTypes[ 0 ];
+ inspected = inspected || {};
+
+ inspected[ dataType ] = true;
+
+ var list = structure[ dataType ],
+ i = 0,
+ length = list ? list.length : 0,
+ executeOnly = ( structure === prefilters ),
+ selection;
+
+ for(; i < length && ( executeOnly || !selection ); i++ ) {
+ selection = list[ i ]( options, originalOptions, jXHR );
+ // If we got redirected to another dataType
+ // we try there if not done already
+ if ( typeof selection === "string" ) {
+ if ( inspected[ selection ] ) {
+ selection = undefined;
+ } else {
+ options.dataTypes.unshift( selection );
+ selection = inspectPrefiltersOrTransports(
+ structure, options, originalOptions, jXHR, selection, inspected );
+ }
+ }
+ }
+ // If we're only executing or nothing was selected
+ // we try the catchall dataType if not done already
+ if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
+ selection = inspectPrefiltersOrTransports(
+ structure, options, originalOptions, jXHR, "*", inspected );
+ }
+ // unnecessary when only executing (prefilters)
+ // but it'll be ignored by the caller in that case
+ return selection;
+}
jQuery.fn.extend({
load: function( url, params, callback ) {
@@ -5591,10 +6106,10 @@ jQuery.fn.extend({
return this;
}
- var off = url.indexOf(" ");
+ var off = url.indexOf( " " );
if ( off >= 0 ) {
- var selector = url.slice(off, url.length);
- url = url.slice(0, off);
+ var selector = url.slice( off, url.length );
+ url = url.slice( 0, off );
}
// Default to a GET request
@@ -5623,26 +6138,34 @@ jQuery.fn.extend({
type: type,
dataType: "html",
data: params,
- complete: function( res, status ) {
+ // Complete callback (responseText is used internally)
+ complete: function( jXHR, status, responseText ) {
+ // Store the response as specified by the jXHR object
+ responseText = jXHR.responseText;
// If successful, inject the HTML into all the matched elements
- if ( status === "success" || status === "notmodified" ) {
+ if ( jXHR.isResolved() ) {
+ // #4825: Get the actual response in case
+ // a dataFilter is present in ajaxSettings
+ jXHR.done(function( r ) {
+ responseText = r;
+ });
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
- .append(res.responseText.replace(rscript, ""))
+ .append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
- res.responseText );
+ responseText );
}
if ( callback ) {
- self.each( callback, [res.responseText, status, res] );
+ self.each( callback, [ responseText, status, jXHR ] );
}
}
});
@@ -5651,42 +6174,42 @@ jQuery.fn.extend({
},
serialize: function() {
- return jQuery.param(this.serializeArray());
+ return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
- return this.map(function() {
- return this.elements ? jQuery.makeArray(this.elements) : this;
+ return this.map(function(){
+ return this.elements ? jQuery.makeArray( this.elements ) : this;
})
- .filter(function() {
+ .filter(function(){
return this.name && !this.disabled &&
- (this.checked || rselectTextarea.test(this.nodeName) ||
- rinput.test(this.type));
+ ( this.checked || rselectTextarea.test( this.nodeName ) ||
+ rinput.test( this.type ) );
})
- .map(function( i, elem ) {
- var val = jQuery(this).val();
+ .map(function( i, elem ){
+ var val = jQuery( this ).val();
return val == null ?
null :
- jQuery.isArray(val) ?
- jQuery.map( val, function( val, i ) {
- return { name: elem.name, value: val };
+ jQuery.isArray( val ) ?
+ jQuery.map( val, function( val, i ){
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
- { name: elem.name, value: val };
+ { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
-jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
- jQuery.fn[o] = function( f ) {
- return this.bind(o, f);
+jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
+ jQuery.fn[ o ] = function( f ){
+ return this.bind( o, f );
};
-});
+} );
-jQuery.extend({
- get: function( url, data, callback, type ) {
- // shift arguments if data argument was omited
+jQuery.each( [ "get", "post" ], function( i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+ // shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
@@ -5694,41 +6217,30 @@ jQuery.extend({
}
return jQuery.ajax({
- type: "GET",
+ type: method,
url: url,
data: data,
success: callback,
dataType: type
});
- },
+ };
+} );
+
+jQuery.extend({
getScript: function( url, callback ) {
- return jQuery.get(url, null, callback, "script");
+ return jQuery.get( url, null, callback, "script" );
},
getJSON: function( url, data, callback ) {
- return jQuery.get(url, data, callback, "json");
- },
-
- post: function( url, data, callback, type ) {
- // shift arguments if data argument was omited
- if ( jQuery.isFunction( data ) ) {
- type = type || callback;
- callback = data;
- data = {};
- }
-
- return jQuery.ajax({
- type: "POST",
- url: url,
- data: data,
- success: callback,
- dataType: type
- });
+ return jQuery.get( url, data, callback, "json" );
},
ajaxSetup: function( settings ) {
- jQuery.extend( jQuery.ajaxSettings, settings );
+ jQuery.extend( true, jQuery.ajaxSettings, settings );
+ if ( settings.context ) {
+ jQuery.ajaxSettings.context = settings.context;
+ }
},
ajaxSettings: {
@@ -5741,332 +6253,408 @@ jQuery.extend({
/*
timeout: 0,
data: null,
+ dataType: null,
username: null,
password: null,
+ cache: null,
traditional: false,
+ headers: {},
+ crossDomain: null,
*/
- // This function can be overriden by calling jQuery.ajaxSetup
- xhr: function() {
- return new window.XMLHttpRequest();
- },
+
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
- script: "text/javascript, application/javascript",
- json: "application/json, text/javascript",
text: "text/plain",
- _default: "*/*"
- }
- },
+ json: "application/json, text/javascript",
+ "*": "*/*"
+ },
- ajax: function( origSettings ) {
- var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
- jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
- s.url = s.url.replace( rhash, "" );
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText"
+ },
- // Use original (not extended) context object if it was provided
- s.context = origSettings && origSettings.context != null ? origSettings.context : s;
+ // List of data converters
+ // 1) key format is "source_type destination_type" (a single space in-between)
+ // 2) the catchall symbol "*" can be used for source_type
+ converters: {
+
+ // Convert anything to text
+ "* text": window.String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": jQuery.parseJSON,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ }
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If options is not an object,
+ // we simulate pre-1.5 signature
+ if ( typeof options !== "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var // Create the final options object
+ s = jQuery.extend( true, {}, jQuery.ajaxSettings, options ),
+ // Callbacks contexts
+ // We force the original context if it exists
+ // or take it from jQuery.ajaxSettings otherwise
+ // (plain objects used as context get extended)
+ callbackContext =
+ ( s.context = ( "context" in options ? options : jQuery.ajaxSettings ).context ) || s,
+ globalEventContext = callbackContext === s ? jQuery.event : jQuery( callbackContext ),
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery._Deferred(),
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ // Response headers
+ responseHeadersString,
+ responseHeaders,
+ // transport
+ transport,
+ // timeout handle
+ timeoutTimer,
+ // Cross-domain detection vars
+ loc = document.location,
+ protocol = loc.protocol || "http:",
+ parts,
+ // The jXHR state
+ state = 0,
+ // Loop variable
+ i,
+ // Fake xhr
+ jXHR = {
+
+ readyState: 0,
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ if ( state === 0 ) {
+ requestHeaders[ name.toLowerCase() ] = value;
+ }
+ return this;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( state === 2 ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while( ( match = rheaders.exec( responseHeadersString ) ) ) {
+ responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() ];
+ }
+ return match || null;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ statusText = statusText || "abort";
+ if ( transport ) {
+ transport.abort( statusText );
+ }
+ done( 0, statusText );
+ return this;
+ }
+ };
- // convert data if not already a string
- if ( s.data && s.processData && typeof s.data !== "string" ) {
- s.data = jQuery.param( s.data, s.traditional );
- }
+ // Callback for when everything is done
+ // It is defined here because jslint complains if it is declared
+ // at the end of the function (which would be more logical and readable)
+ function done( status, statusText, responses, headers) {
- // Handle JSONP Parameter Callbacks
- if ( s.dataType === "jsonp" ) {
- if ( type === "GET" ) {
- if ( !jsre.test( s.url ) ) {
- s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
- }
- } else if ( !s.data || !jsre.test(s.data) ) {
- s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
+ // Called once
+ if ( state === 2 ) {
+ return;
}
- s.dataType = "json";
- }
- // Build temporary JSONP function
- if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
- jsonp = s.jsonpCallback || ("jsonp" + jsc++);
+ // State is "done" now
+ state = 2;
- // Replace the =? sequence both in the query string and the data
- if ( s.data ) {
- s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+ // Clear timeout if it exists
+ if ( timeoutTimer ) {
+ clearTimeout( timeoutTimer );
}
- s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+ // Dereference transport for early garbage collection
+ // (no matter how long the jXHR object will be used)
+ transport = undefined;
- // We need to make sure
- // that a JSONP style response is executed properly
- s.dataType = "script";
+ // Cache response headers
+ responseHeadersString = headers || "";
- // Handle JSONP-style loading
- var customJsonp = window[ jsonp ];
+ // Set readyState
+ jXHR.readyState = status ? 4 : 0;
- window[ jsonp ] = function( tmp ) {
- if ( jQuery.isFunction( customJsonp ) ) {
- customJsonp( tmp );
+ var isSuccess,
+ success,
+ error,
+ response = responses ? ajaxHandleResponses( s, jXHR, responses ) : undefined,
+ lastModified,
+ etag;
- } else {
- // Garbage collect
- window[ jsonp ] = undefined;
+ // If successful, handle type chaining
+ if ( status >= 200 && status < 300 || status === 304 ) {
- try {
- delete window[ jsonp ];
- } catch( jsonpError ) {}
- }
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
- data = tmp;
- jQuery.handleSuccess( s, xhr, status, data );
- jQuery.handleComplete( s, xhr, status, data );
-
- if ( head ) {
- head.removeChild( script );
+ if ( ( lastModified = jXHR.getResponseHeader( "Last-Modified" ) ) ) {
+ jQuery.lastModified[ s.url ] = lastModified;
+ }
+ if ( ( etag = jXHR.getResponseHeader( "Etag" ) ) ) {
+ jQuery.etag[ s.url ] = etag;
+ }
}
- };
- }
- if ( s.dataType === "script" && s.cache === null ) {
- s.cache = false;
- }
+ // If not modified
+ if ( status === 304 ) {
- if ( s.cache === false && noContent ) {
- var ts = jQuery.now();
+ statusText = "notmodified";
+ isSuccess = true;
- // try replacing _= if it is there
- var ret = s.url.replace(rts, "$1_=" + ts);
+ // If we have data
+ } else {
- // if nothing was replaced, add timestamp to the end
- s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
- }
+ try {
+ success = ajaxConvert( s, response );
+ statusText = "success";
+ isSuccess = true;
+ } catch(e) {
+ // We have a parsererror
+ statusText = "parsererror";
+ error = e;
+ }
+ }
+ } else {
+ // We extract error from statusText
+ // then normalize statusText and status for non-aborts
+ error = statusText;
+ if( status ) {
+ statusText = "error";
+ if ( status < 0 ) {
+ status = 0;
+ }
+ }
+ }
- // If data is available, append data to url for GET/HEAD requests
- if ( s.data && noContent ) {
- s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
- }
+ // Set data for the fake xhr object
+ jXHR.status = status;
+ jXHR.statusText = statusText;
- // Watch for a new set of requests
- if ( s.global && jQuery.active++ === 0 ) {
- jQuery.event.trigger( "ajaxStart" );
- }
+ // Success/Error
+ if ( isSuccess ) {
+ deferred.resolveWith( callbackContext, [ success, statusText, jXHR ] );
+ } else {
+ deferred.rejectWith( callbackContext, [ jXHR, statusText, error ] );
+ }
- // Matches an absolute URL, and saves the domain
- var parts = rurl.exec( s.url ),
- remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
+ // Status-dependent callbacks
+ jXHR.statusCode( statusCode );
+ statusCode = undefined;
- // If we're requesting a remote document
- // and trying to load JSON or Script with a GET
- if ( s.dataType === "script" && type === "GET" && remote ) {
- var head = document.getElementsByTagName("head")[0] || document.documentElement;
- var script = document.createElement("script");
- if ( s.scriptCharset ) {
- script.charset = s.scriptCharset;
+ if ( s.global ) {
+ globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
+ [ jXHR, s, isSuccess ? success : error ] );
}
- script.src = s.url;
- // Handle Script loading
- if ( !jsonp ) {
- var done = false;
+ // Complete
+ completeDeferred.resolveWith( callbackContext, [ jXHR, statusText ] );
- // Attach handlers for all browsers
- script.onload = script.onreadystatechange = function() {
- if ( !done && (!this.readyState ||
- this.readyState === "loaded" || this.readyState === "complete") ) {
- done = true;
- jQuery.handleSuccess( s, xhr, status, data );
- jQuery.handleComplete( s, xhr, status, data );
+ if ( s.global ) {
+ globalEventContext.trigger( "ajaxComplete", [ jXHR, s] );
+ // Handle the global AJAX counter
+ if ( !( --jQuery.active ) ) {
+ jQuery.event.trigger( "ajaxStop" );
+ }
+ }
+ }
- // Handle memory leak in IE
- script.onload = script.onreadystatechange = null;
- if ( head && script.parentNode ) {
- head.removeChild( script );
- }
+ // Attach deferreds
+ deferred.promise( jXHR );
+ jXHR.success = jXHR.done;
+ jXHR.error = jXHR.fail;
+ jXHR.complete = completeDeferred.done;
+
+ // Status-dependent callbacks
+ jXHR.statusCode = function( map ) {
+ if ( map ) {
+ var tmp;
+ if ( state < 2 ) {
+ for( tmp in map ) {
+ statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
- };
+ } else {
+ tmp = map[ jXHR.status ];
+ jXHR.then( tmp, tmp );
+ }
}
+ return this;
+ };
- // Use insertBefore instead of appendChild to circumvent an IE6 bug.
- // This arises when a base node is used (#2709 and #4378).
- head.insertBefore( script, head.firstChild );
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+ // We also use the url parameter if available
+ s.url = ( "" + ( url || s.url ) ).replace( rhash, "" ).replace( rprotocol, protocol + "//" );
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
+
+ // Determine if a cross-domain request is in order
+ if ( !s.crossDomain ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] != protocol || parts[ 2 ] != loc.hostname ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
+ ( loc.port || ( protocol === "http:" ? 80 : 443 ) ) )
+ );
+ }
- // We handle everything using the script element injection
- return undefined;
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
}
- var requestDone = false;
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jXHR );
- // Create the request object
- var xhr = s.xhr();
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
- if ( !xhr ) {
- return;
- }
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
- // Open the socket
- // Passing null username, generates a login popup on Opera (#2865)
- if ( s.username ) {
- xhr.open(type, s.url, s.async, s.username, s.password);
- } else {
- xhr.open(type, s.url, s.async);
+ // Watch for a new set of requests
+ if ( s.global && jQuery.active++ === 0 ) {
+ jQuery.event.trigger( "ajaxStart" );
}
- // Need an extra try/catch for cross domain requests in Firefox 3
- try {
- // Set content-type if data specified and content-body is valid for this type
- if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
- xhr.setRequestHeader("Content-Type", s.contentType);
- }
-
- // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
- if ( s.ifModified ) {
- if ( jQuery.lastModified[s.url] ) {
- xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
- }
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
- if ( jQuery.etag[s.url] ) {
- xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
- }
+ // If data is available, append data to url
+ if ( s.data ) {
+ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
- // Set header so the called script knows that it's an XMLHttpRequest
- // Only send the header if it's not a remote XHR
- if ( !remote ) {
- xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
- }
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
- // Set the Accepts header for the server, depending on the dataType
- xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
- s.accepts[ s.dataType ] + ", */*; q=0.01" :
- s.accepts._default );
- } catch( headerError ) {}
+ var ts = jQuery.now(),
+ // try replacing _= if it is there
+ ret = s.url.replace( rts, "$1_=" + ts );
- // Allow custom headers/mimetypes and early abort
- if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
- // Handle the global AJAX counter
- if ( s.global && jQuery.active-- === 1 ) {
- jQuery.event.trigger( "ajaxStop" );
+ // if nothing was replaced, add timestamp to the end
+ s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
-
- // close opended socket
- xhr.abort();
- return false;
}
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ requestHeaders[ "content-type" ] = s.contentType;
}
- // Wait for a response to come back
- var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
- // The request was aborted
- if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
- // Opera doesn't call onreadystatechange before this point
- // so we simulate the call
- if ( !requestDone ) {
- jQuery.handleComplete( s, xhr, status, data );
- }
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ s.url ] ) {
+ requestHeaders[ "if-modified-since" ] = jQuery.lastModified[ s.url ];
+ }
+ if ( jQuery.etag[ s.url ] ) {
+ requestHeaders[ "if-none-match" ] = jQuery.etag[ s.url ];
+ }
+ }
- requestDone = true;
- if ( xhr ) {
- xhr.onreadystatechange = jQuery.noop;
- }
+ // Set the Accepts header for the server, depending on the dataType
+ requestHeaders.accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
+ s.accepts[ "*" ];
- // The transfer is complete and the data is available, or the request timed out
- } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
- requestDone = true;
- xhr.onreadystatechange = jQuery.noop;
+ // Check for headers option
+ for ( i in s.headers ) {
+ requestHeaders[ i.toLowerCase() ] = s.headers[ i ];
+ }
- status = isTimeout === "timeout" ?
- "timeout" :
- !jQuery.httpSuccess( xhr ) ?
- "error" :
- s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
- "notmodified" :
- "success";
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already
+ done( 0, "abort" );
+ // Return false
+ jXHR = false;
- var errMsg;
+ } else {
- if ( status === "success" ) {
- // Watch for, and catch, XML document parse errors
- try {
- // process the data (runs the xml through httpData regardless of callback)
- data = jQuery.httpData( xhr, s.dataType, s );
- } catch( parserError ) {
- status = "parsererror";
- errMsg = parserError;
- }
- }
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jXHR[ i ]( s[ i ] );
+ }
- // Make sure that the request was successful or notmodified
- if ( status === "success" || status === "notmodified" ) {
- // JSONP handles its own success callback
- if ( !jsonp ) {
- jQuery.handleSuccess( s, xhr, status, data );
- }
- } else {
- jQuery.handleError( s, xhr, status, errMsg );
- }
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jXHR );
- // Fire the complete handlers
- if ( !jsonp ) {
- jQuery.handleComplete( s, xhr, status, data );
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ // Set state as sending
+ state = jXHR.readyState = 1;
+ // Send global event
+ if ( s.global ) {
+ globalEventContext.trigger( "ajaxSend", [ jXHR, s ] );
}
-
- if ( isTimeout === "timeout" ) {
- xhr.abort();
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = setTimeout( function(){
+ jXHR.abort( "timeout" );
+ }, s.timeout );
}
- // Stop memory leaks
- if ( s.async ) {
- xhr = null;
+ try {
+ transport.send( requestHeaders, done );
+ } catch (e) {
+ // Propagate exception as error if not done
+ if ( status < 2 ) {
+ done( -1, e );
+ // Simply rethrow otherwise
+ } else {
+ jQuery.error( e );
+ }
}
}
- };
-
- // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
- // Opera doesn't fire onreadystatechange at all on abort
- try {
- var oldAbort = xhr.abort;
- xhr.abort = function() {
- if ( xhr ) {
- // oldAbort has no call property in IE7 so
- // just do it this way, which works in all
- // browsers
- Function.prototype.call.call( oldAbort, xhr );
- }
-
- onreadystatechange( "abort" );
- };
- } catch( abortError ) {}
-
- // Timeout checker
- if ( s.async && s.timeout > 0 ) {
- setTimeout(function() {
- // Check to see if the request is still happening
- if ( xhr && !requestDone ) {
- onreadystatechange( "timeout" );
- }
- }, s.timeout);
- }
-
- // Send the data
- try {
- xhr.send( noContent || s.data == null ? null : s.data );
-
- } catch( sendError ) {
- jQuery.handleError( s, xhr, null, sendError );
-
- // Fire the complete handlers
- jQuery.handleComplete( s, xhr, status, data );
- }
-
- // firefox 1.5 doesn't fire statechange for sync requests
- if ( !s.async ) {
- onreadystatechange();
}
-
- // return XMLHttpRequest to allow aborting the request etc.
- return xhr;
+ return jXHR;
},
// Serialize an array of form elements or a set of
@@ -6075,37 +6663,37 @@ jQuery.extend({
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
- value = jQuery.isFunction(value) ? value() : value;
- s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
+ value = jQuery.isFunction( value ) ? value() : value;
+ s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
-
+
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
-
+
// If an array was passed in, assume that it is an array of form elements.
- if ( jQuery.isArray(a) || a.jquery ) {
+ if ( jQuery.isArray( a ) || a.jquery ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
- });
-
+ } );
+
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
- buildParams( prefix, a[prefix], traditional, add );
+ buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
- return s.join("&").replace(r20, "+");
+ return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
- if ( jQuery.isArray(obj) && obj.length ) {
+ if ( jQuery.isArray( obj ) && obj.length ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
@@ -6123,9 +6711,11 @@ function buildParams( prefix, obj, traditional, add ) {
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
-
+
} else if ( !traditional && obj != null && typeof obj === "object" ) {
- if ( jQuery.isEmptyObject( obj ) ) {
+ // If we see an array here, it is empty and should be treated as an empty
+ // object
+ if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item.
@@ -6134,7 +6724,7 @@ function buildParams( prefix, obj, traditional, add ) {
buildParams( prefix + "[" + k + "]", v, traditional, add );
});
}
-
+
} else {
// Serialize scalar item.
add( prefix, obj );
@@ -6150,143 +6740,548 @@ jQuery.extend({
// Last-Modified header cache for next request
lastModified: {},
- etag: {},
+ etag: {}
- handleError: function( s, xhr, status, e ) {
- // If a local callback was specified, fire it
- if ( s.error ) {
- s.error.call( s.context, xhr, status, e );
- }
+});
- // Fire the global callback
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
+/* Handles responses to an ajax request:
+ * - sets all responseXXX fields accordingly
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jXHR, responses ) {
+
+ var contents = s.contents,
+ dataTypes = s.dataTypes,
+ responseFields = s.responseFields,
+ ct,
+ type,
+ finalDataType,
+ firstDataType;
+
+ // Fill responseXXX fields
+ for( type in responseFields ) {
+ if ( type in responses ) {
+ jXHR[ responseFields[type] ] = responses[ type ];
}
- },
+ }
- handleSuccess: function( s, xhr, status, data ) {
- // If a local callback was specified, fire it and pass it the data
- if ( s.success ) {
- s.success.call( s.context, data, status, xhr );
+ // Remove auto dataType and get content-type in the process
+ while( dataTypes[ 0 ] === "*" ) {
+ dataTypes.shift();
+ if ( ct === undefined ) {
+ ct = jXHR.getResponseHeader( "content-type" );
}
+ }
- // Fire the global callback
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
+ // Check if we're dealing with a known content-type
+ if ( ct ) {
+ for ( type in contents ) {
+ if ( contents[ type ] && contents[ type ].test( ct ) ) {
+ dataTypes.unshift( type );
+ break;
+ }
}
- },
+ }
- handleComplete: function( s, xhr, status ) {
- // Process result
- if ( s.complete ) {
- s.complete.call( s.context, xhr, status );
+ // Check to see if we have a response for the expected dataType
+ if ( dataTypes[ 0 ] in responses ) {
+ finalDataType = dataTypes[ 0 ];
+ } else {
+ // Try convertible dataTypes
+ for ( type in responses ) {
+ if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+ finalDataType = type;
+ break;
+ }
+ if ( !firstDataType ) {
+ firstDataType = type;
+ }
}
+ // Or just use first one
+ finalDataType = finalDataType || firstDataType;
+ }
- // The request was completed
- if ( s.global ) {
- jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
+ // If we found a dataType
+ // We add the dataType to the list if needed
+ // and return the corresponding response
+ if ( finalDataType ) {
+ if ( finalDataType !== dataTypes[ 0 ] ) {
+ dataTypes.unshift( finalDataType );
}
+ return responses[ finalDataType ];
+ }
+}
+
+// Chain conversions given the request and the original response
+function ajaxConvert( s, response ) {
- // Handle the global AJAX counter
- if ( s.global && jQuery.active-- === 1 ) {
- jQuery.event.trigger( "ajaxStop" );
+ // Apply the dataFilter if provided
+ if ( s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ var dataTypes = s.dataTypes,
+ converters = s.converters,
+ i,
+ length = dataTypes.length,
+ tmp,
+ // Current and previous dataTypes
+ current = dataTypes[ 0 ],
+ prev,
+ // Conversion expression
+ conversion,
+ // Conversion function
+ conv,
+ // Conversion functions (transitive conversion)
+ conv1,
+ conv2;
+
+ // For each dataType in the chain
+ for( i = 1; i < length; i++ ) {
+
+ // Get the dataTypes
+ prev = current;
+ current = dataTypes[ i ];
+
+ // If current is auto dataType, update it to prev
+ if( current === "*" ) {
+ current = prev;
+ // If no auto and dataTypes are actually different
+ } else if ( prev !== "*" && prev !== current ) {
+
+ // Get the converter
+ conversion = prev + " " + current;
+ conv = converters[ conversion ] || converters[ "* " + current ];
+
+ // If there is no direct converter, search transitively
+ if ( !conv ) {
+ conv2 = undefined;
+ for( conv1 in converters ) {
+ tmp = conv1.split( " " );
+ if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
+ conv2 = converters[ tmp[1] + " " + current ];
+ if ( conv2 ) {
+ conv1 = converters[ conv1 ];
+ if ( conv1 === true ) {
+ conv = conv2;
+ } else if ( conv2 === true ) {
+ conv = conv1;
+ }
+ break;
+ }
+ }
+ }
+ }
+ // If we found no converter, dispatch an error
+ if ( !( conv || conv2 ) ) {
+ jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
+ }
+ // If found converter is not an equivalence
+ if ( conv !== true ) {
+ // Convert with 1 or 2 converters accordingly
+ response = conv ? conv( response ) : conv2( conv1(response) );
+ }
}
- },
-
- triggerGlobal: function( s, type, args ) {
- (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
- },
+ }
+ return response;
+}
- // Determines if an XMLHttpRequest was successful or not
- httpSuccess: function( xhr ) {
- try {
- // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
- return !xhr.status && location.protocol === "file:" ||
- xhr.status >= 200 && xhr.status < 300 ||
- xhr.status === 304 || xhr.status === 1223;
- } catch(e) {}
- return false;
- },
- // Determines if an XMLHttpRequest returns NotModified
- httpNotModified: function( xhr, url ) {
- var lastModified = xhr.getResponseHeader("Last-Modified"),
- etag = xhr.getResponseHeader("Etag");
- if ( lastModified ) {
- jQuery.lastModified[url] = lastModified;
- }
+var jsc = jQuery.now(),
+ jsre = /(\=)\?(&|$)|()\?\?()/i;
- if ( etag ) {
- jQuery.etag[url] = etag;
+// Default jsonp settings
+jQuery.ajaxSetup({
+ jsonp: "callback",
+ jsonpCallback: function() {
+ return jQuery.expando + "_" + ( jsc++ );
+ }
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, dataIsString /* internal */ ) {
+
+ dataIsString = ( typeof s.data === "string" );
+
+ if ( s.dataTypes[ 0 ] === "jsonp" ||
+ originalSettings.jsonpCallback ||
+ originalSettings.jsonp != null ||
+ s.jsonp !== false && ( jsre.test( s.url ) ||
+ dataIsString && jsre.test( s.data ) ) ) {
+
+ var responseContainer,
+ jsonpCallback = s.jsonpCallback =
+ jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
+ previous = window[ jsonpCallback ],
+ url = s.url,
+ data = s.data,
+ replace = "$1" + jsonpCallback + "$2";
+
+ if ( s.jsonp !== false ) {
+ url = url.replace( jsre, replace );
+ if ( s.url === url ) {
+ if ( dataIsString ) {
+ data = data.replace( jsre, replace );
+ }
+ if ( s.data === data ) {
+ // Add callback manually
+ url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
+ }
+ }
}
- return xhr.status === 304;
- },
+ s.url = url;
+ s.data = data;
- httpData: function( xhr, type, s ) {
- var ct = xhr.getResponseHeader("content-type") || "",
- xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
- data = xml ? xhr.responseXML : xhr.responseText;
+ window[ jsonpCallback ] = function( response ) {
+ responseContainer = [ response ];
+ };
- if ( xml && data.documentElement.nodeName === "parsererror" ) {
- jQuery.error( "parsererror" );
- }
+ s.complete = [ function() {
- // Allow a pre-filtering function to sanitize the response
- // s is checked to keep backwards compatibility
- if ( s && s.dataFilter ) {
- data = s.dataFilter( data, type );
- }
+ // Set callback back to previous value
+ window[ jsonpCallback ] = previous;
- // The filter can actually parse the response
- if ( typeof data === "string" ) {
- // Get the JavaScript object, if JSON is used.
- if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
- data = jQuery.parseJSON( data );
+ // Call if it was a function and we have a response
+ if ( previous) {
+ if ( responseContainer && jQuery.isFunction( previous ) ) {
+ window[ jsonpCallback ] ( responseContainer[ 0 ] );
+ }
+ } else {
+ // else, more memory leak avoidance
+ try{
+ delete window[ jsonpCallback ];
+ } catch( e ) {}
+ }
+
+ }, s.complete ];
- // If the type is "script", eval it in global context
- } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
- jQuery.globalEval( data );
+ // Use data converter to retrieve json after script execution
+ s.converters["script json"] = function() {
+ if ( ! responseContainer ) {
+ jQuery.error( jsonpCallback + " was not called" );
}
- }
+ return responseContainer[ 0 ];
+ };
+
+ // force json dataType
+ s.dataTypes[ 0 ] = "json";
- return data;
+ // Delegate to script
+ return "script";
}
+} );
+
+
+
+// Install script dataType
+jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript"
+ },
+ contents: {
+ script: /javascript/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
});
-/*
- * Create the request object; Microsoft failed to properly
- * implement the XMLHttpRequest in IE7 (can't request local files),
- * so we use the ActiveXObject when it is available
- * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
- * we need a fallback.
- */
-if ( window.ActiveXObject ) {
- jQuery.ajaxSettings.xhr = function() {
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ s.global = false;
+ }
+} );
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+
+ var script,
+ head = document.getElementsByTagName( "head" )[ 0 ] || document.documentElement;
+
+ return {
+
+ send: function( _, callback ) {
+
+ script = document.createElement( "script" );
+
+ script.async = "async";
+
+ if ( s.scriptCharset ) {
+ script.charset = s.scriptCharset;
+ }
+
+ script.src = s.url;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+ if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+ // Handle memory leak in IE
+ script.onload = script.onreadystatechange = null;
+
+ // Remove the script
+ if ( head && script.parentNode ) {
+ head.removeChild( script );
+ }
+
+ // Dereference the script
+ script = undefined;
+
+ // Callback if not abort
+ if ( !isAbort ) {
+ callback( 200, "success" );
+ }
+ }
+ };
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709 and #4378).
+ head.insertBefore( script, head.firstChild );
+ },
+
+ abort: function() {
+ if ( script ) {
+ script.onload( 0, 1 );
+ }
+ }
+ };
+ }
+} );
+
+
+
+
+var // Next active xhr id
+ xhrId = jQuery.now(),
+
+ // active xhrs
+ xhrs = {},
+
+ // #5280: see below
+ xhrUnloadAbortInstalled,
+
+ // XHR used to determine supports properties
+ testXHR;
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+ /* Microsoft failed to properly
+ * implement the XMLHttpRequest in IE7 (can't request local files),
+ * so we use the ActiveXObject when it is available
+ * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+ * we need a fallback.
+ */
+ function() {
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
- } catch(xhrError) {}
+ } catch( xhrError ) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
- } catch(activeError) {}
+ } catch( activeError ) {}
+ } :
+ // For all other browsers, use the standard XMLHttpRequest object
+ function() {
+ return new window.XMLHttpRequest();
};
-}
-// Does this browser support XHR requests?
-jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
+// Test if we can create an xhr object
+try {
+ testXHR = jQuery.ajaxSettings.xhr();
+} catch( xhrCreationException ) {}
+
+//Does this browser support XHR requests?
+jQuery.support.ajax = !!testXHR;
+
+// Does this browser support crossDomain XHR requests
+jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
+
+// No need for the temporary xhr anymore
+testXHR = undefined;
+
+// Create transport if the browser can provide an xhr
+if ( jQuery.support.ajax ) {
+
+ jQuery.ajaxTransport(function( s ) {
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( !s.crossDomain || jQuery.support.cors ) {
+
+ var callback;
+
+ return {
+ send: function( headers, complete ) {
+
+ // #5280: we need to abort on unload or IE will keep connections alive
+ if ( !xhrUnloadAbortInstalled ) {
+
+ xhrUnloadAbortInstalled = 1;
+
+ jQuery(window).bind( "unload", function() {
+
+ // Abort all pending requests
+ jQuery.each( xhrs, function( _, xhr ) {
+ if ( xhr.onreadystatechange ) {
+ xhr.onreadystatechange( 1 );
+ }
+ } );
+
+ } );
+ }
+
+ // Get a new xhr
+ var xhr = s.xhr(),
+ handle;
+
+ // Open the socket
+ // Passing null username, generates a login popup on Opera (#2865)
+ if ( s.username ) {
+ xhr.open( s.type, s.url, s.async, s.username, s.password );
+ } else {
+ xhr.open( s.type, s.url, s.async );
+ }
+
+ // Requested-With header
+ // Not set for crossDomain requests with no content
+ // (see why at http://trac.dojotoolkit.org/ticket/9486)
+ // Won't change header if already provided
+ if ( !( s.crossDomain && !s.hasContent ) && !headers["x-requested-with"] ) {
+ headers[ "x-requested-with" ] = "XMLHttpRequest";
+ }
+
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ jQuery.each( headers, function( key, value ) {
+ xhr.setRequestHeader( key, value );
+ } );
+ } catch( _ ) {}
+
+ // Do send the request
+ // This may raise an exception which is actually
+ // handled in jQuery.ajax (so no try/catch here)
+ xhr.send( ( s.hasContent && s.data ) || null );
+
+ // Listener
+ callback = function( _, isAbort ) {
+
+ // Was never called and is aborted or complete
+ if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+
+ // Only called once
+ callback = 0;
+
+ // Do not keep as active anymore
+ if ( handle ) {
+ xhr.onreadystatechange = jQuery.noop;
+ delete xhrs[ handle ];
+ }
+
+ // If it's an abort
+ if ( isAbort ) {
+ // Abort it manually if needed
+ if ( xhr.readyState !== 4 ) {
+ xhr.abort();
+ }
+ } else {
+ // Get info
+ var status = xhr.status,
+ statusText,
+ responseHeaders = xhr.getAllResponseHeaders(),
+ responses = {},
+ xml = xhr.responseXML;
+
+ // Construct response list
+ if ( xml && xml.documentElement /* #4958 */ ) {
+ responses.xml = xml;
+ }
+ responses.text = xhr.responseText;
+
+ // Firefox throws an exception when accessing
+ // statusText for faulty cross-domain requests
+ try {
+ statusText = xhr.statusText;
+ } catch( e ) {
+ // We normalize with Webkit giving an empty statusText
+ statusText = "";
+ }
+
+ // Filter status for non standard behaviours
+ status =
+ // Opera returns 0 when it should be 304
+ // Webkit returns 0 for failing cross-domain no matter the real status
+ status === 0 ?
+ (
+ // Webkit, Firefox: filter out faulty cross-domain requests
+ !s.crossDomain || statusText ?
+ (
+ // Opera: filter out real aborts #6060
+ responseHeaders ?
+ 304 :
+ 0
+ ) :
+ // We assume 302 but could be anything cross-domain related
+ 302
+ ) :
+ (
+ // IE sometimes returns 1223 when it should be 204 (see #1450)
+ status == 1223 ?
+ 204 :
+ status
+ );
+
+ // Call complete
+ complete( status, statusText, responses, responseHeaders );
+ }
+ }
+ };
+
+ // if we're in sync mode or it's in cache
+ // and has been retrieved directly (IE6 & IE7)
+ // we need to manually fire the callback
+ if ( !s.async || xhr.readyState === 4 ) {
+ callback();
+ } else {
+ // Add to list of active xhrs
+ handle = xhrId++;
+ xhrs[ handle ] = xhr;
+ xhr.onreadystatechange = callback;
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback(0,1);
+ }
+ }
+ };
+ }
+ });
+}
var elemdisplay = {},
rfxtypes = /^(?:toggle|show|hide)$/,
- rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/,
+ rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
@@ -6311,7 +7306,7 @@ jQuery.fn.extend({
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
- if ( !jQuery.data(elem, "olddisplay") && display === "none" ) {
+ if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
@@ -6319,7 +7314,7 @@ jQuery.fn.extend({
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
- jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
+ jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
@@ -6330,7 +7325,7 @@ jQuery.fn.extend({
display = elem.style.display;
if ( display === "" || display === "none" ) {
- elem.style.display = jQuery.data(elem, "olddisplay") || "";
+ elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
@@ -6346,8 +7341,8 @@ jQuery.fn.extend({
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
- if ( display !== "none" ) {
- jQuery.data( this[i], "olddisplay", display );
+ if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
+ jQuery._data( this[i], "olddisplay", display );
}
}
@@ -6621,7 +7616,7 @@ jQuery.fx.prototype = {
}
var r = parseFloat( jQuery.css( this.elem, this.prop ) );
- return r && r > -10000 ? r : 0;
+ return r || 0;
},
// Start an animation from one number to another
@@ -6815,7 +7810,7 @@ if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
- if ( options ) {
+ if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
@@ -6838,7 +7833,7 @@ if ( "getBoundingClientRect" in document.documentElement ) {
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
- return box || { top: 0, left: 0 };
+ return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
@@ -6857,7 +7852,7 @@ if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0];
- if ( options ) {
+ if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
@@ -6976,7 +7971,7 @@ jQuery.offset = {
return { top: top, left: left };
},
-
+
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
@@ -7010,7 +8005,7 @@ jQuery.offset = {
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
-
+
if ( "using" in options ) {
options.using.call( elem, props );
} else {
@@ -7070,7 +8065,7 @@ jQuery.each( ["Left", "Top"], function( i, name ) {
jQuery.fn[ method ] = function(val) {
var elem = this[0], win;
-
+
if ( !elem ) {
return null;
}
@@ -7138,7 +8133,7 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
if ( !elem ) {
return size == null ? null : this;
}
-
+
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
@@ -7148,8 +8143,10 @@ jQuery.each([ "Height", "Width" ], function( i, name ) {
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
- return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
- elem.document.body[ "client" + name ];
+ // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
+ var docElemProp = elem.document.documentElement[ "client" + name ];
+ return elem.document.compatMode === "CSS1Compat" && docElemProp ||
+ elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
index 43456a77f6..4dcb3779a2 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/jquery_ujs.js
@@ -1,132 +1,148 @@
-jQuery(function ($) {
- var csrf_token = $('meta[name=csrf-token]').attr('content'),
- csrf_param = $('meta[name=csrf-param]').attr('content');
-
- $.fn.extend({
- /**
- * Triggers a custom event on an element and returns the event result
- * this is used to get around not being able to ensure callbacks are placed
- * at the end of the chain.
- *
- * TODO: deprecate with jQuery 1.4.2 release, in favor of subscribing to our
- * own events and placing ourselves at the end of the chain.
- */
- triggerAndReturn: function (name, data) {
- var event = new $.Event(name);
- this.trigger(event, data);
-
- return event.result !== false;
- },
-
- /**
- * Handles execution of remote calls firing overridable events along the way
- */
- callRemote: function () {
- var el = this,
- method = el.attr('method') || el.attr('data-method') || 'GET',
- url = el.attr('action') || el.attr('href'),
- dataType = el.attr('data-type') || 'script';
-
- if (url === undefined) {
- throw "No URL specified for remote call (action or href must be present).";
- } else {
- if (el.triggerAndReturn('ajax:before')) {
- var data = el.is('form') ? el.serializeArray() : [];
- $.ajax({
- url: url,
- data: data,
- dataType: dataType,
- type: method.toUpperCase(),
- beforeSend: function (xhr) {
- el.trigger('ajax:loading', xhr);
- },
- success: function (data, status, xhr) {
- el.trigger('ajax:success', [data, status, xhr]);
- },
- complete: function (xhr) {
- el.trigger('ajax:complete', xhr);
- },
- error: function (xhr, status, error) {
- el.trigger('ajax:failure', [xhr, status, error]);
- }
- });
- }
-
- el.trigger('ajax:after');
- }
- }
- });
-
- /**
- * confirmation handler
- */
- $('a[data-confirm],input[data-confirm]').live('click', function () {
- var el = $(this);
- if (el.triggerAndReturn('confirm')) {
- if (!confirm(el.attr('data-confirm'))) {
- return false;
- }
- }
- });
-
-
- /**
- * remote handlers
- */
- $('form[data-remote]').live('submit', function (e) {
- $(this).callRemote();
- e.preventDefault();
- });
-
- $('a[data-remote],input[data-remote]').live('click', function (e) {
- $(this).callRemote();
- e.preventDefault();
- });
-
- $('a[data-method]:not([data-remote])').live('click', function (e){
- var link = $(this),
- href = link.attr('href'),
- method = link.attr('data-method'),
- form = $('<form method="post" action="'+href+'"></form>'),
- metadata_input = '<input name="_method" value="'+method+'" type="hidden" />';
-
- if (csrf_param != null && csrf_token != null) {
- metadata_input += '<input name="'+csrf_param+'" value="'+csrf_token+'" type="hidden" />';
- }
-
- form.hide()
- .append(metadata_input)
- .appendTo('body');
-
- e.preventDefault();
- form.submit();
- });
-
- /**
- * disable-with handlers
- */
- var disable_with_input_selector = 'input[data-disable-with]';
- var disable_with_form_remote_selector = 'form[data-remote]:has(' + disable_with_input_selector + ')';
- var disable_with_form_not_remote_selector = 'form:not([data-remote]):has(' + disable_with_input_selector + ')';
-
- var disable_with_input_function = function () {
- $(this).find(disable_with_input_selector).each(function () {
- var input = $(this);
- input.data('enable-with', input.val())
- .attr('value', input.attr('data-disable-with'))
- .attr('disabled', 'disabled');
- });
- };
-
- $(disable_with_form_remote_selector).live('ajax:before', disable_with_input_function);
- $(disable_with_form_not_remote_selector).live('submit', disable_with_input_function);
-
- $(disable_with_form_remote_selector).live('ajax:complete', function () {
- $(this).find(disable_with_input_selector).each(function () {
- var input = $(this);
- input.removeAttr('disabled')
- .val(input.data('enable-with'));
- });
- });
-
-});
+/**
+ * Unobtrusive scripting adapter for jQuery
+ *
+ * Requires jQuery 1.4.3 or later.
+ * https://github.com/rails/jquery-ujs
+ */
+
+(function($) {
+ // Triggers an event on an element and returns the event result
+ function fire(obj, name, data) {
+ var event = new $.Event(name);
+ obj.trigger(event, data);
+ return event.result !== false;
+ }
+
+ // Submits "remote" forms and links with ajax
+ function handleRemote(element) {
+ var method, url, data,
+ dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
+
+ if (element.is('form')) {
+ method = element.attr('method');
+ url = element.attr('action');
+ data = element.serializeArray();
+ // memoized value from clicked submit button
+ var button = element.data('ujs:submit-button');
+ if (button) {
+ data.push(button);
+ element.data('ujs:submit-button', null);
+ }
+ } else {
+ method = element.attr('data-method');
+ url = element.attr('href');
+ data = null;
+ }
+
+ $.ajax({
+ url: url, type: method || 'GET', data: data, dataType: dataType,
+ // stopping the "ajax:beforeSend" event will cancel the ajax request
+ beforeSend: function(xhr, settings) {
+ if (settings.dataType === undefined) {
+ xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
+ }
+ return fire(element, 'ajax:beforeSend', [xhr, settings]);
+ },
+ success: function(data, status, xhr) {
+ element.trigger('ajax:success', [data, status, xhr]);
+ },
+ complete: function(xhr, status) {
+ element.trigger('ajax:complete', [xhr, status]);
+ },
+ error: function(xhr, status, error) {
+ element.trigger('ajax:error', [xhr, status, error]);
+ }
+ });
+ }
+
+ // Handles "data-method" on links such as:
+ // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
+ function handleMethod(link) {
+ var href = link.attr('href'),
+ method = link.attr('data-method'),
+ csrf_token = $('meta[name=csrf-token]').attr('content'),
+ csrf_param = $('meta[name=csrf-param]').attr('content'),
+ form = $('<form method="post" action="' + href + '"></form>'),
+ metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';
+
+ if (csrf_param !== undefined && csrf_token !== undefined) {
+ metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
+ }
+
+ form.hide().append(metadata_input).appendTo('body');
+ form.submit();
+ }
+
+ function disableFormElements(form) {
+ form.find('input[data-disable-with]').each(function() {
+ var input = $(this);
+ input.data('ujs:enable-with', input.val())
+ .val(input.attr('data-disable-with'))
+ .attr('disabled', 'disabled');
+ });
+ }
+
+ function enableFormElements(form) {
+ form.find('input[data-disable-with]').each(function() {
+ var input = $(this);
+ input.val(input.data('ujs:enable-with')).removeAttr('disabled');
+ });
+ }
+
+ function allowAction(element) {
+ var message = element.attr('data-confirm');
+ return !message || (fire(element, 'confirm') && confirm(message));
+ }
+
+ function requiredValuesMissing(form) {
+ var missing = false;
+ form.find('input[name][required]').each(function() {
+ if (!$(this).val()) missing = true;
+ });
+ return missing;
+ }
+
+ $('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
+ var link = $(this);
+ if (!allowAction(link)) return false;
+
+ if (link.attr('data-remote') != undefined) {
+ handleRemote(link);
+ return false;
+ } else if (link.attr('data-method')) {
+ handleMethod(link);
+ return false;
+ }
+ });
+
+ $('form').live('submit.rails', function(e) {
+ var form = $(this), remote = form.attr('data-remote') != undefined;
+ if (!allowAction(form)) return false;
+
+ // skip other logic when required values are missing
+ if (requiredValuesMissing(form)) return !remote;
+
+ if (remote) {
+ handleRemote(form);
+ return false;
+ } else {
+ disableFormElements(form);
+ }
+ });
+
+ $('form input[type=submit], form button[type=submit], form button:not([type])').live('click.rails', function() {
+ var button = $(this);
+ if (!allowAction(button)) return false;
+ // register the pressed submit button
+ var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null;
+ button.closest('form').data('ujs:submit-button', data);
+ });
+
+ $('form').live('ajax:beforeSend.rails', function(event) {
+ if (this == event.target) disableFormElements($(this));
+ });
+
+ $('form').live('ajax:complete.rails', function(event) {
+ if (this == event.target) enableFormElements($(this));
+ });
+})( jQuery );
diff --git a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
index fc69f93c58..2cd1220786 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
+++ b/railties/lib/rails/generators/rails/app/templates/public/javascripts/prototype_ujs.js
@@ -95,9 +95,10 @@
parameters: params,
evalScripts: true,
- onComplete: function(request) { element.fire("ajax:complete", request); },
- onSuccess: function(request) { element.fire("ajax:success", request); },
- onFailure: function(request) { element.fire("ajax:failure", request); }
+ onCreate: function(response) { element.fire("ajax:create", response); },
+ onComplete: function(response) { element.fire("ajax:complete", response); },
+ onSuccess: function(response) { element.fire("ajax:success", response); },
+ onFailure: function(response) { element.fire("ajax:failure", response); }
});
element.fire("ajax:after");
@@ -114,7 +115,7 @@
csrf_token = $$('meta[name=csrf-token]')[0];
var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
- element.parentNode.insert(form);
+ $(element.parentNode).insert(form);
if (method !== 'post') {
insertHiddenField(form, '_method', method);
@@ -127,52 +128,81 @@
form.submit();
}
+ function disableFormElements(form) {
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
+ input.store('rails:original-value', input.getValue());
+ input.setValue(input.readAttribute('data-disable-with')).disable();
+ });
+ }
+
+ function enableFormElements(form) {
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
+ input.setValue(input.retrieve('rails:original-value')).enable();
+ });
+ }
- document.on("click", "*[data-confirm]", function(event, element) {
+ function allowAction(element) {
var message = element.readAttribute('data-confirm');
- if (!confirm(message)) event.stop();
- });
+ return !message || confirm(message);
+ }
- document.on("click", "a[data-remote]", function(event, element) {
- if (event.stopped) return;
- handleRemote(element);
- event.stop();
- });
+ document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) {
+ if (!allowAction(link)) {
+ event.stop();
+ return false;
+ }
- document.on("click", "a[data-method]", function(event, element) {
- if (event.stopped) return;
- handleMethod(element);
- event.stop();
+ if (link.readAttribute('data-remote')) {
+ handleRemote(link);
+ event.stop();
+ } else if (link.readAttribute('data-method')) {
+ handleMethod(link);
+ event.stop();
+ }
});
- document.on("click", "form input[type=submit]", function(event, button) {
+ document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) {
// register the pressed submit button
event.findElement('form').store('rails:submit-button', button.name || false);
});
document.on("submit", function(event) {
- var form = event.findElement(),
- message = form.readAttribute('data-confirm');
+ var form = event.findElement();
- if (message && !confirm(message)) {
+ if (!allowAction(form)) {
event.stop();
return false;
}
- form.select('input[type=submit][data-disable-with]').each(function(input) {
- input.store('rails:original-value', input.getValue());
- input.disable().setValue(input.readAttribute('data-disable-with'));
- });
-
if (form.readAttribute('data-remote')) {
handleRemote(form);
event.stop();
+ } else {
+ disableFormElements(form);
}
});
- document.on("ajax:after", "form", function(event, form) {
- form.select('input[type=submit][data-disable-with]').each(function(input) {
- input.setValue(input.retrieve('rails:original-value')).enable();
- });
+ document.on('ajax:create', 'form', function(event, form) {
+ if (form == event.findElement()) disableFormElements(form);
+ });
+
+ document.on('ajax:complete', 'form', function(event, form) {
+ if (form == event.findElement()) enableFormElements(form);
+ });
+
+ Ajax.Responders.register({
+ onCreate: function(request) {
+ var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
+
+ if (csrf_meta_tag) {
+ var header = 'X-CSRF-Token',
+ token = csrf_meta_tag.readAttribute('content');
+
+ if (!request.options.requestHeaders) {
+ request.options.requestHeaders = {};
+ }
+ request.options.requestHeaders[header] = token;
+ }
+ }
});
})();
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 9c54b98238..8b1aed974f 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
@@ -8,11 +8,15 @@ module Rails
end
def app
- directory "app" if options[:mountable]
+ if options[:mountable]
+ directory "app"
+ template "#{app_templates_dir}/app/views/layouts/application.html.erb.tt",
+ "app/views/layouts/#{name}/application.html.erb"
+ end
end
def readme
- copy_file "README.rdoc"
+ template "README.rdoc"
end
def gemfile
@@ -40,7 +44,7 @@ module Rails
end
def config
- template "config/routes.rb" if mountable?
+ template "config/routes.rb" if full?
end
def test
@@ -88,6 +92,29 @@ task :default => :test
end
end
+ def stylesheets
+ empty_directory_with_gitkeep "public/stylesheets" if options[:mountable]
+ end
+
+ def javascripts
+ return unless options[:mountable]
+
+ empty_directory "#{app_templates_dir}/public/javascripts"
+
+ unless options[:skip_javascript]
+ copy_file "#{app_templates_dir}/public/javascripts/#{options[:javascript]}.js", "public/javascripts/#{options[:javascript]}.js"
+ copy_file "#{app_templates_dir}/public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js"
+
+ if options[:javascript] == "prototype"
+ copy_file "#{app_templates_dir}/public/javascripts/controls.js", "public/javascripts/controls.js"
+ copy_file "#{app_templates_dir}/public/javascripts/dragdrop.js", "public/javascripts/dragdrop.js"
+ copy_file "#{app_templates_dir}/public/javascripts/effects.js", "public/javascripts/effects.js"
+ end
+ end
+
+ copy_file "#{app_templates_dir}/public/javascripts/application.js", "public/javascripts/application.js"
+ end
+
def script(force = false)
directory "script", :force => force do |content|
"#{shebang}\n" + content
@@ -143,6 +170,14 @@ task :default => :test
build(:lib)
end
+ def create_public_stylesheets_files
+ build(:stylesheets)
+ end
+
+ def create_javascript_files
+ build(:javascripts)
+ end
+
def create_script_files
build(:script)
end
@@ -163,6 +198,10 @@ task :default => :test
public_task :apply_rails_template, :bundle_if_dev_or_edge
protected
+ def app_templates_dir
+ "../../app/templates"
+ end
+
def create_dummy_app(path = nil)
dummy_path(path) if path
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
index 25292f59ad..5704e75a29 100755
--- a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
@@ -16,9 +16,6 @@ Rake::RDocTask.new(:rdoc) do |rdoc|
end
<% if full? && !options[:skip_active_record] -%>
-namespace :app do
- ENGINE_PATH = File.expand_path("..", __FILE__)
- load File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__)
-end
-<% end -%>
-
+APP_RAKEFILE = File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__)
+load 'rails/tasks/engine.rake'
+<% end %>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
index 42ddf380d8..8e158d5831 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/config/routes.rb
@@ -1,3 +1,6 @@
+<% if mountable? -%>
<%= camelized %>::Engine.routes.draw do
-
+<% else -%>
+Rails.application.routes.draw do
+<% end -%>
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
index 9600ee0c3f..aa8ea77bae 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/engine.rb
@@ -1,7 +1,7 @@
module <%= camelized %>
class Engine < Rails::Engine
<% if mountable? -%>
- isolate_namespace <%= camelized %>
+ isolate_namespace <%= camelized %>
<% end -%>
end
end
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
index cab8708be3..ee85b70bb5 100644
--- a/railties/lib/rails/generators/test_case.rb
+++ b/railties/lib/rails/generators/test_case.rb
@@ -114,7 +114,7 @@ module Rails
end
alias :assert_no_directory :assert_no_file
- # Asserts a given file does not exist. You need to supply an absolute path or a
+ # Asserts a given migration exists. You need to supply an absolute path or a
# path relative to the configured destination:
#
# assert_migration "db/migrate/create_products.rb"
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index 8570fc7b3f..d15887f561 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -134,10 +134,10 @@ module Rails
@root = root
@glob = options[:glob]
- autoload_once! if options[:autoload_once]
- eager_load! if options[:eager_load]
- autoload! if options[:autoload]
- load_path! if options[:load_path]
+ options[:autoload_once] ? autoload_once! : skip_autoload_once!
+ options[:eager_load] ? eager_load! : skip_eager_load!
+ options[:autoload] ? autoload! : skip_autoload!
+ options[:load_path] ? load_path! : skip_load_path!
end
def children
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index b3dc1f894c..32acc66f10 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -21,7 +21,7 @@ module Rails
request = ActionDispatch::Request.new(env)
path = request.fullpath
- info "\n\nStarted #{env["REQUEST_METHOD"]} \"#{path}\" " \
+ info "\n\nStarted #{request.request_method} \"#{path}\" " \
"for #{request.ip} at #{Time.now.to_default_s}"
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index 030a838dc1..7fca565124 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -3,55 +3,43 @@ require 'rails/configuration'
require 'active_support/inflector'
module Rails
- # Railtie is the core of the Rails Framework and provides several hooks to extend
+ # Railtie is the core of the Rails framework and provides several hooks to extend
# Rails and/or modify the initialization process.
#
# Every major component of Rails (Action Mailer, Action Controller,
- # Action View, Active Record and Active Resource) are all Railties, so each of
- # them is responsible to set their own initialization. This makes, for example,
- # Rails absent of any Active Record hook, allowing any other ORM framework to hook in.
+ # Action View, Active Record and Active Resource) is a Railtie. Each of
+ # them is responsible for their own initialization. This makes Rails itself
+ # absent of any component hooks, allowing other components to be used in
+ # place of any of the Rails defaults.
#
# Developing a Rails extension does _not_ require any implementation of
# Railtie, but if you need to interact with the Rails framework during
- # or after boot, then Railtie is what you need to do that interaction.
+ # or after boot, then Railtie is needed.
#
- # For example, the following would need you to implement Railtie in your
- # plugin:
+ # For example, an extension doing any of the following would require Railtie:
#
# * creating initializers
- # * configuring a Rails framework or the Application, like setting a generator
- # * adding Rails config.* keys to the environment
- # * setting up a subscriber to the Rails +ActiveSupport::Notifications+
- # * adding rake tasks into rails
+ # * configuring a Rails framework for the application, like setting a generator
+ # * adding config.* keys to the environment
+ # * setting up a subscriber with ActiveSupport::Notifications
+ # * adding rake tasks
#
# == Creating your Railtie
#
- # Implementing Railtie in your Rails extension is done by creating a class
- # Railtie that has your extension name and making sure that this gets loaded
- # during boot time of the Rails stack.
+ # To extend Rails using Railtie, create a Railtie class which inherits
+ # from Rails::Railtie within your extension's namespace. This class must be
+ # loaded during the Rails boot process.
#
- # You can do this however you wish, but here is an example if you want to provide
- # it for a gem that can be used with or without Rails:
+ # The following example demonstrates an extension which can be used with or without Rails.
#
- # * Create a file (say, lib/my_gem/railtie.rb) which contains class Railtie inheriting from
- # Rails::Railtie and is namespaced to your gem:
- #
- # # lib/my_gem/railtie.rb
- # module MyGem
- # class Railtie < Rails::Railtie
- # end
+ # # lib/my_gem/railtie.rb
+ # module MyGem
+ # class Railtie < Rails::Railtie
# end
+ # end
#
- # * Require your own gem as well as rails in this file:
- #
- # # lib/my_gem/railtie.rb
- # require 'my_gem'
- # require 'rails'
- #
- # module MyGem
- # class Railtie < Rails::Railtie
- # end
- # end
+ # # lib/my_gem.rb
+ # require 'my_gem/railtie' if defined?(Rails)
#
# == Initializers
#
diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb
index b6d4ed2312..920ab67ff1 100644
--- a/railties/lib/rails/railtie/configurable.rb
+++ b/railties/lib/rails/railtie/configurable.rb
@@ -1,9 +1,7 @@
module Rails
class Railtie
module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
+ extend ActiveSupport::Concern
module ClassMethods
delegate :config, :to => :instance
@@ -26,9 +24,9 @@ module Rails
protected
- def method_missing(*args, &block)
- instance.send(*args, &block)
- end
+ def method_missing(*args, &block)
+ instance.send(*args, &block)
+ end
end
end
end
diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake
new file mode 100644
index 0000000000..2f0e7be896
--- /dev/null
+++ b/railties/lib/rails/tasks/engine.rake
@@ -0,0 +1,69 @@
+task "load_app" do
+ namespace :app do
+ load APP_RAKEFILE
+ end
+
+ if !defined?(ENGINE_PATH) || !ENGINE_PATH
+ ENGINE_PATH = find_engine_path(APP_RAKEFILE)
+ end
+end
+
+def app_task(name)
+ task name => [:load_app, "app:db:#{name}"]
+end
+
+namespace :db do
+ app_task "reset"
+
+ desc "Migrate the database (options: VERSION=x, VERBOSE=false)."
+ app_task "migrate"
+ app_task "migrate:up"
+ app_task "migrate:down"
+ app_task "migrate:redo"
+ app_task "migrate:reset"
+
+ desc "Display status of migrations"
+ app_task "migrate:status"
+
+ desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
+ app_task "create"
+ app_task "create:all"
+
+ desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
+ app_task "drop"
+ app_task "drop:all"
+
+ desc "Load fixtures into the current environment's database."
+ app_task "fixtures:load"
+
+ desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)."
+ app_task "rollback"
+
+ desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
+ app_task "schema:dump"
+
+ desc "Load a schema.rb file into the database"
+ app_task "schema:load"
+
+ desc "Load the seed data from db/seeds.rb"
+ app_task "seed"
+
+ desc "Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)"
+ app_task "setup"
+
+ desc "Dump the database structure to an SQL file"
+ app_task "structure:dump"
+
+ desc "Retrieves the current schema version number"
+ app_task "version"
+end
+
+def find_engine_path(path)
+ return if path == "/"
+
+ if Rails::Engine.find(path)
+ path
+ else
+ find_engine_path(File.expand_path('..', path))
+ end
+end
diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb
index f81002328f..00029e627e 100644
--- a/railties/lib/rails/test_help.rb
+++ b/railties/lib/rails/test_help.rb
@@ -19,6 +19,10 @@ if defined?(ActiveRecord)
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
self.fixture_path = "#{Rails.root}/test/fixtures/"
+
+ setup do
+ ActiveRecord::IdentityMap.clear
+ end
end
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index c12c4a4660..044fd2a278 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -280,5 +280,58 @@ module ApplicationTests
get "/"
assert_equal "/omg/images/foo.jpg", last_response.body
end
+
+ test "config.action_view.cache_template_loading with cache_classes default" do
+ add_to_config "config.cache_classes = true"
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading without cache_classes default" do
+ add_to_config "config.cache_classes = false"
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert !ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading = false" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ config.action_view.cache_template_loading = false
+ RUBY
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert !ActionView::Resolver.caching?
+ end
+
+ test "config.action_view.cache_template_loading = true" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.action_view.cache_template_loading = true
+ RUBY
+ require "#{app_path}/config/environment"
+ require 'action_view/base'
+
+ assert ActionView::Resolver.caching?
+ end
+
+ test "config.action_dispatch.show_exceptions is sent in env" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = true
+ end
+
+ class ::OmgController < ActionController::Base
+ def index
+ render :text => env["action_dispatch.show_exceptions"]
+ end
+ end
+
+ get "/"
+ assert_equal 'true', last_response.body
+ end
end
end
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
index d4159dd0fd..793e73556c 100644
--- a/railties/test/application/console_test.rb
+++ b/railties/test/application/console_test.rb
@@ -26,14 +26,14 @@ class ConsoleTest < Test::Unit::TestCase
assert_instance_of ActionDispatch::Integration::Session, session
end
- def test_reload_should_fire_preparation_callbacks
+ def test_reload_should_fire_preparation_and_cleanup_callbacks
load_environment
a = b = c = nil
# TODO: These should be defined on the initializer
- ActionDispatch::Callbacks.to_prepare { a = b = c = 1 }
- ActionDispatch::Callbacks.to_prepare { b = c = 2 }
- ActionDispatch::Callbacks.to_prepare { c = 3 }
+ ActionDispatch::Reloader.to_cleanup { a = b = c = 1 }
+ ActionDispatch::Reloader.to_cleanup { b = c = 2 }
+ ActionDispatch::Reloader.to_prepare { c = 3 }
# Hide Reloading... output
silence_stream(STDOUT) { reload! }
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index 475091f789..19311a7fa0 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class FrameworlsTest < Test::Unit::TestCase
+ class FrameworksTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -166,7 +166,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
- expects = [ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActiveRecord::SessionStore]
+ expects = [ActiveRecord::IdentityMap::Middleware, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActiveRecord::SessionStore]
middleware = Rails.application.config.middleware.map { |m| m.klass }
assert_equal expects, middleware & expects
end
diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb
index 178b31cff3..390f65ab5c 100644
--- a/railties/test/application/initializers/i18n_test.rb
+++ b/railties/test/application/initializers/i18n_test.rb
@@ -63,6 +63,36 @@ module ApplicationTests
assert I18n.load_path.include?("#{app_path}/config/another_locale.yml")
end
+ test "load_path is populated before eager loaded models" do
+ add_to_config <<-RUBY
+ config.cache_classes = true
+ RUBY
+
+ app_file "config/locales/en.yml", <<-YAML
+en:
+ foo: "1"
+ YAML
+
+ app_file 'app/models/foo.rb', <<-RUBY
+ class Foo < ActiveRecord::Base
+ @foo = I18n.t(:foo)
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] }
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+ load_app
+
+ get "/i18n"
+ assert_equal "1", last_response.body
+ end
+
test "locales are reloaded if they change between requests" do
add_to_config <<-RUBY
config.cache_classes = false
diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb
new file mode 100644
index 0000000000..5487e41e0a
--- /dev/null
+++ b/railties/test/application/middleware/show_exceptions_test.rb
@@ -0,0 +1,37 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class ShowExceptionsTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ test "unspecified route when set action_dispatch.show_exceptions to false" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = false
+ end
+
+ assert_raise(ActionController::RoutingError) do
+ get '/foo'
+ end
+ end
+
+ test "unspecified route when set action_dispatch.show_exceptions to true" do
+ make_basic_app do |app|
+ app.config.action_dispatch.show_exceptions = true
+ end
+
+ assert_nothing_raised(ActionController::RoutingError) do
+ get '/foo'
+ end
+ end
+ end
+end
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index 173ac40b12..b314832685 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -27,7 +27,9 @@ module ApplicationTests
"ActionDispatch::ShowExceptions",
"ActionDispatch::RemoteIp",
"Rack::Sendfile",
+ "ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
+ "ActiveRecord::IdentityMap::Middleware",
"ActiveRecord::ConnectionAdapters::ConnectionManagement",
"ActiveRecord::QueryCache",
"ActionDispatch::Cookies",
@@ -55,6 +57,7 @@ module ApplicationTests
boot!
assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement")
assert !middleware.include?("ActiveRecord::QueryCache")
+ assert !middleware.include?("ActiveRecord::IdentityMap::Middleware")
end
test "removes lock if allow concurrency is set" do
@@ -75,10 +78,16 @@ module ApplicationTests
assert !middleware.include?("ActionDispatch::Static")
end
- test "removes show exceptions if action_dispatch.show_exceptions is disabled" do
+ test "includes show exceptions even action_dispatch.show_exceptions is disabled" do
add_to_config "config.action_dispatch.show_exceptions = false"
boot!
- assert !middleware.include?("ActionDispatch::ShowExceptions")
+ assert middleware.include?("ActionDispatch::ShowExceptions")
+ end
+
+ test "removes ActionDispatch::Reloader if cache_classes is true" do
+ add_to_config "config.cache_classes = true"
+ boot!
+ assert !middleware.include?("ActionDispatch::Reloader")
end
test "use middleware" do
@@ -105,6 +114,11 @@ module ApplicationTests
assert_equal "Rack::Runtime", middleware.fourth
end
+ test "identity map is inserted" do
+ boot!
+ assert middleware.include?("ActiveRecord::IdentityMap::Middleware")
+ end
+
test "insert middleware before" do
add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config"
boot!
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 23cd2378c7..59e5ef4dee 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -63,5 +63,41 @@ module ApplicationTests
RUBY
assert_match 'cart GET /cart(.:format)', Dir.chdir(app_path){ `rake routes` }
end
+
+ def test_model_and_migration_generator_with_change_syntax
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ output = Dir.chdir(app_path){ `rake db:migrate` }
+ assert_match /create_table\(:users\)/, output
+ assert_match /CreateUsers: migrated/, output
+ assert_match /add_column\(:users, :email, :string\)/, output
+ assert_match /AddEmailToUsers: migrated/, output
+
+ output = Dir.chdir(app_path){ `rake db:rollback STEP=2` }
+ assert_match /drop_table\("users"\)/, output
+ assert_match /CreateUsers: reverted/, output
+ assert_match /remove_column\("users", :email\)/, output
+ assert_match /AddEmailToUsers: reverted/, output
+ end
+
+ def test_loading_specific_fixtures
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate model product name:string`
+ `rake db:migrate`
+ end
+
+ require "#{rails_root}/config/environment"
+
+ # loading a specific fixture
+ errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
+ assert $?.success?, errormsg
+
+ assert_equal 2, ::AppTemplate::Application::Product.count
+ assert_equal 0, ::AppTemplate::Application::User.count
+ end
end
end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 7faa674a81..018c2fa6bf 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -64,6 +64,23 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "things-43/config/application.rb", /^module Things43$/
end
+ def test_application_new_exits_with_non_zero_code_on_invalid_application_name
+ # TODO: Suppress the output of this (it's because of a Thor::Error)
+ `rails new test`
+ assert_equal false, $?.success?
+ end
+
+ def test_application_new_exits_with_message_and_non_zero_code_when_generating_inside_existing_rails_directory
+ app_root = File.join(destination_root, 'myfirstapp')
+ run_generator [app_root]
+ output = nil
+ Dir.chdir(app_root) do
+ output = `rails new mysecondapp`
+ end
+ assert_equal "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\nType 'rails' for help.\n", output
+ assert_equal false, $?.success?
+ end
+
def test_application_name_is_detected_if_it_exists_and_app_folder_renamed
app_root = File.join(destination_root, "myapp")
app_moved_root = File.join(destination_root, "myapp_moved")
@@ -106,7 +123,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_config_database_is_added_by_default
run_generator
assert_file "config/database.yml", /sqlite3/
- assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/
+ assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
end
def test_config_another_database
@@ -135,6 +152,9 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "public/javascripts/application.js"
assert_file "public/javascripts/prototype.js"
assert_file "public/javascripts/rails.js"
+ assert_file "public/javascripts/controls.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/effects.js"
assert_file "test"
end
@@ -151,6 +171,9 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "config/application.rb", /#\s+config\.action_view\.javascript_expansions\[:defaults\]\s+=\s+%w\(jquery rails\)/
assert_file "public/javascripts/application.js"
assert_file "public/javascripts/prototype.js"
+ assert_file "public/javascripts/controls.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/effects.js"
assert_file "public/javascripts/rails.js", /prototype/
end
diff --git a/railties/test/generators/generators_test_helper.rb b/railties/test/generators/generators_test_helper.rb
index 46a6da3568..1b9a8fd8a7 100644
--- a/railties/test/generators/generators_test_helper.rb
+++ b/railties/test/generators/generators_test_helper.rb
@@ -34,6 +34,6 @@ module GeneratorsTestHelper
routes = File.expand_path("../../../lib/rails/generators/rails/app/templates/config/routes.rb", __FILE__)
destination = File.join(destination_root, "config")
FileUtils.mkdir_p(destination)
- FileUtils.cp File.expand_path(routes), destination
+ FileUtils.cp routes, destination
end
end
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 288ec30460..6eecfc8e2e 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -34,15 +34,10 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
run_generator [migration, "title:string", "body:text"]
assert_migration "db/migrate/#{migration}.rb" do |content|
- assert_method :up, content do |up|
+ assert_method :change, content do |up|
assert_match /add_column :posts, :title, :string/, up
assert_match /add_column :posts, :body, :text/, up
end
-
- assert_method :down, content do |down|
- assert_match /remove_column :posts, :title/, down
- assert_match /remove_column :posts, :body/, down
- end
end
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index 552b7eb30a..3d773b4134 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -99,15 +99,11 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["product", "name:string", "supplier_id:integer"]
assert_migration "db/migrate/create_products.rb" do |m|
- assert_method :up, m do |up|
+ assert_method :change, m do |up|
assert_match /create_table :products/, up
assert_match /t\.string :name/, up
assert_match /t\.integer :supplier_id/, up
end
-
- assert_method :down, m do |down|
- assert_match /drop_table :products/, down
- end
end
end
@@ -141,7 +137,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["account", "--no-timestamps"]
assert_migration "db/migrate/create_accounts.rb" do |m|
- assert_method :up, m do |up|
+ assert_method :change, m do |up|
assert_no_match /t.timestamps/, up
end
end
@@ -181,7 +177,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator
old_migration = Dir["#{destination_root}/db/migrate/*_create_accounts.rb"].first
error = capture(:stderr) { run_generator ["Account", "--force"] }
- assert_no_match /Another migration is already named create_foos/, error
+ assert_no_match /Another migration is already named create_accounts/, error
assert_no_file old_migration
assert_migration 'db/migrate/create_accounts.rb'
end
@@ -207,4 +203,45 @@ class ModelGeneratorTest < Rails::Generators::TestCase
content = capture(:stderr){ run_generator ["object"] }
assert_match /The name 'Object' is either already used in your application or reserved/, content
end
+
+ def test_index_is_added_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_added_for_references_association
+ run_generator ["account", "supplier:references"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_belongs_to_association
+ run_generator ["account", "supplier:belongs_to", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match /add_index/, up
+ end
+ end
+ end
+
+ def test_index_is_skipped_for_references_association
+ run_generator ["account", "supplier:references", "--no-indexes"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match /add_index/, up
+ end
+ end
+ end
+
end
diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb
index 1badae0713..f23701e99e 100644
--- a/railties/test/generators/named_base_test.rb
+++ b/railties/test/generators/named_base_test.rb
@@ -98,6 +98,11 @@ class NamedBaseTest < Rails::Generators::TestCase
assert_name g, 'posts', :index_helper
end
+ def test_index_helper_to_pluralize_once
+ g = generator ['Stadium']
+ assert_name g, 'stadia', :index_helper
+ end
+
def test_index_helper_with_uncountable
g = generator ['Sheep']
assert_name g, 'sheep_index', :index_helper
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index 0d24821ff6..2a8b337144 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -38,8 +38,10 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "things-43/lib/things-43.rb", /module Things43/
end
- def test_generating_test_files
+ def test_generating_without_options
run_generator
+ assert_file "README.rdoc", /Bukkits/
+ assert_no_file "config/routes.rb"
assert_file "test/test_helper.rb"
assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/
end
@@ -66,7 +68,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_database_entry_is_assed_by_default_in_full_mode
run_generator([destination_root, "--full"])
assert_file "test/dummy/config/database.yml", /sqlite/
- assert_file "Gemfile", /^gem\s+["']sqlite3-ruby["'],\s+:require\s+=>\s+["']sqlite3["']$/
+ assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
end
def test_config_another_database
@@ -91,6 +93,35 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "test/dummy/config/database.yml", /postgres/
end
+ def test_skipping_javascripts_without_mountable_option
+ run_generator
+ assert_no_file "public/javascripts/prototype.js"
+ assert_no_file "public/javascripts/rails.js"
+ assert_no_file "public/javascripts/controls.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ assert_no_file "public/javascripts/application.js"
+ end
+
+ def test_javascripts_generation
+ run_generator [destination_root, "--mountable"]
+ assert_file "public/javascripts/rails.js"
+ assert_file "public/javascripts/prototype.js"
+ assert_file "public/javascripts/controls.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/dragdrop.js"
+ assert_file "public/javascripts/application.js"
+ end
+
+ def test_skip_javascripts
+ run_generator [destination_root, "--skip-javascript", "--mountable"]
+ assert_no_file "public/javascripts/prototype.js"
+ assert_no_file "public/javascripts/rails.js"
+ assert_no_file "public/javascripts/controls.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ assert_no_file "public/javascripts/dragdrop.js"
+ end
+
def test_ensure_that_javascript_option_is_passed_to_app_generator
run_generator [destination_root, "--javascript", "jquery"]
assert_file "test/dummy/public/javascripts/jquery.js"
@@ -122,6 +153,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_creating_engine_in_full_mode
run_generator [destination_root, "--full"]
+ assert_file "config/routes.rb", /Rails.application.routes.draw do/
assert_file "lib/bukkits/engine.rb", /module Bukkits\n class Engine < Rails::Engine\n end\nend/
assert_file "lib/bukkits.rb", /require "bukkits\/engine"/
end
@@ -137,6 +169,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "test/dummy/config/routes.rb", /mount Bukkits::Engine => "\/bukkits"/
assert_file "app/controllers/bukkits/application_controller.rb", /module Bukkits\n class ApplicationController < ActionController::Base/
assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/
+ assert_file "app/views/layouts/bukkits/application.html.erb", /<title>Bukkits<\/title>/
end
def test_passing_dummy_path_as_a_parameter
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index f366600b16..df787f61ba 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -3,7 +3,7 @@ require 'rails/generators/rails/scaffold/scaffold_generator'
class ScaffoldGeneratorTest < Rails::Generators::TestCase
include GeneratorsTestHelper
- arguments %w(product_line title:string price:integer)
+ arguments %w(product_line title:string product:belongs_to user:references)
setup :copy_routes
@@ -14,7 +14,10 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/
assert_file "test/unit/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
assert_file "test/fixtures/product_lines.yml"
- assert_migration "db/migrate/create_product_lines.rb"
+ assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
+ assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :product_id/
+ assert_migration "db/migrate/create_product_lines.rb", /references :user/
+ assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :user_id/
# Route
assert_file "config/routes.rb" do |route|
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 346c9ceb9d..99c9d790eb 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -94,6 +94,14 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match /Rails 2\.x generator/, output
end
+ def test_invoke_with_nested_namespaces
+ model_generator = mock('ModelGenerator') do
+ expects(:start).with(["Account"], {})
+ end
+ Rails::Generators.expects(:find_by_namespace).with('namespace', 'my:awesome').returns(model_generator)
+ Rails::Generators.invoke 'my:awesome:namespace', ["Account"]
+ end
+
def test_rails_generators_help_with_builtin_information
output = capture(:stdout){ Rails::Generators.help }
assert_match /Rails:/, output
@@ -120,6 +128,16 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match /^ active_record:fixjour$/, output
end
+ def test_default_banner_should_show_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:foobar)
+ assert_match /^rails generate foobar:foobar/, klass.banner
+ end
+
+ def test_default_banner_should_not_show_rails_generator_namespace
+ klass = Rails::Generators.find_by_namespace(:model)
+ assert_match /^rails generate model/, klass.banner
+ end
+
def test_no_color_sets_proper_shell
Rails::Generators.no_color!
assert_equal Thor::Shell::Basic, Thor::Base.shell
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 3b03e4eb3d..c5b1cb9a80 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -215,6 +215,13 @@ module TestHelpers
end
end
+ def remove_from_config(str)
+ file = "#{app_path}/config/application.rb"
+ contents = File.read(file)
+ contents.sub!(/#{str}/, "")
+ File.open(file, "w+") { |f| f.puts contents }
+ end
+
def app_file(path, contents)
FileUtils.mkdir_p File.dirname("#{app_path}/#{path}")
File.open("#{app_path}/#{path}", 'w') do |f|
@@ -231,6 +238,7 @@ module TestHelpers
:activemodel,
:activerecord,
:activeresource] - arr
+ remove_from_config "config.active_record.identity_map = true" if to_remove.include? :activerecord
$:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 05bd0c36cd..0ce00db3c4 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -1,12 +1,15 @@
require "isolation/abstract_unit"
require "railties/shared_tests"
require 'stringio'
+require 'rack/test'
+require 'rack/file'
module RailtiesTest
class EngineTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
include SharedTests
+ include Rack::Test::Methods
def setup
build_app
@@ -87,10 +90,8 @@ module RailtiesTest
boot_rails
- env = Rack::MockRequest.env_for("/bukkits")
- response = Rails.application.call(env)
-
- assert_equal ["HELLO WORLD"], response[2]
+ get("/bukkits")
+ assert_equal "HELLO WORLD", last_response.body
end
test "it provides routes as default endpoint" do
@@ -115,9 +116,8 @@ module RailtiesTest
boot_rails
- env = Rack::MockRequest.env_for("/bukkits/foo")
- response = Rails.application.call(env)
- assert_equal ["foo"], response[2]
+ get("/bukkits/foo")
+ assert_equal "foo", last_response.body
end
test "engine can load its own plugins" do
@@ -191,13 +191,11 @@ module RailtiesTest
boot_rails
env = Rack::MockRequest.env_for("/")
- response = Bukkits::Engine.call(env)
-
+ Bukkits::Engine.call(env)
assert_equal Bukkits::Engine.routes, env['action_dispatch.routes']
env = Rack::MockRequest.env_for("/")
- response = Rails.application.call(env)
-
+ Rails.application.call(env)
assert_equal Rails.application.routes, env['action_dispatch.routes']
end
@@ -230,6 +228,12 @@ module RailtiesTest
<%= stylesheet_link_tag("foo") %>
ERB
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
add_to_config 'config.asset_path = "/omg%s"'
boot_rails
@@ -239,9 +243,8 @@ module RailtiesTest
::Bukkits::Engine.config.asset_path = "/bukkits%s"
- env = Rack::MockRequest.env_for("/foo")
- response = Bukkits::Engine.call(env)
- stripped_body = response[2].body.split("\n").map(&:strip).join
+ get("/bukkits/foo")
+ stripped_body = last_response.body.split("\n").map(&:strip).join
expected = "/omg/bukkits/images/foo.png" +
"<script src=\"/omg/bukkits/javascripts/foo.js\" type=\"text/javascript\"></script>" +
@@ -264,14 +267,16 @@ module RailtiesTest
end
RUBY
- boot_rails
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
- env = Rack::MockRequest.env_for("/foo")
- response = Bukkits::Engine.call(env)
- stripped_body = response[2].body.strip
+ boot_rails
- expected = "/bukkits/images/foo.png"
- assert_equal expected, stripped_body
+ get("/bukkits/foo")
+ assert_equal "/bukkits/images/foo.png", last_response.body.strip
end
test "engine's files are served via ActionDispatch::Static" do
@@ -291,25 +296,42 @@ module RailtiesTest
boot_rails
- env = Rack::MockRequest.env_for("/app.html")
- response = Rails.application.call(env)
- assert_equal rack_body(response[2]), rack_body(File.open(File.join(app_path, "public/app.html")))
+ get("/app.html")
+ assert_equal File.read(File.join(app_path, "public/app.html")), last_response.body
- env = Rack::MockRequest.env_for("/bukkits/bukkits.html")
- response = Rails.application.call(env)
- assert_equal rack_body(response[2]), rack_body(File.open(File.join(@plugin.path, "public/bukkits.html")))
+ get("/bukkits/bukkits.html")
+ assert_equal File.read(File.join(@plugin.path, "public/bukkits.html")), last_response.body
- env = Rack::MockRequest.env_for("/bukkits/file_from_app.html")
- response = Rails.application.call(env)
- assert_equal rack_body(response[2]), rack_body(File.open(File.join(app_path, "public/bukkits/file_from_app.html")))
+ get("/bukkits/file_from_app.html")
+ assert_equal File.read(File.join(app_path, "public/bukkits/file_from_app.html")), last_response.body
end
- def rack_body(obj)
- buffer = ""
- obj.each do |part|
- buffer << part
- end
- buffer
+ test "an applications files are given priority over an engines files when served via ActionDispatch::Static" do
+ add_to_config "config.serve_static_assets = true"
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ class Engine < ::Rails::Engine
+ engine_name :bukkits
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ @plugin.write "public/bukkits.html", "in engine"
+
+ app_file "public/bukkits/bukkits.html", "in app"
+
+ boot_rails
+
+ get('/bukkits/bukkits.html')
+
+ assert_equal 'in app', last_response.body.strip
end
test "shared engine should include application's helpers and own helpers" do
@@ -355,17 +377,14 @@ module RailtiesTest
boot_rails
- env = Rack::MockRequest.env_for("/foo")
- response = Rails.application.call(env)
- assert_equal ["Something... Something... Something..."], response[2]
+ get("/foo")
+ assert_equal "Something... Something... Something...", last_response.body
- env = Rack::MockRequest.env_for("/foo/show")
- response = Rails.application.call(env)
- assert_equal ["/foo"], response[2]
+ get("/foo/show")
+ assert_equal "/foo", last_response.body
- env = Rack::MockRequest.env_for("/foo/bar")
- response = Rails.application.call(env)
- assert_equal ["It's a bar."], response[2]
+ get("/foo/bar")
+ assert_equal "It's a bar.", last_response.body
end
test "isolated engine should include only its own routes and helpers" do
@@ -464,25 +483,20 @@ module RailtiesTest
assert ::Bukkits::MyMailer.method_defined?(:foo_path)
assert !::Bukkits::MyMailer.method_defined?(:bar_path)
- env = Rack::MockRequest.env_for("/bukkits/from_app")
- response = AppTemplate::Application.call(env)
- assert_equal ["false"], response[2]
+ get("/bukkits/from_app")
+ assert_equal "false", last_response.body
- env = Rack::MockRequest.env_for("/bukkits/foo/show")
- response = AppTemplate::Application.call(env)
- assert_equal ["/bukkits/foo"], response[2]
+ get("/bukkits/foo/show")
+ assert_equal "/bukkits/foo", last_response.body
- env = Rack::MockRequest.env_for("/bukkits/foo")
- response = AppTemplate::Application.call(env)
- assert_equal ["Helped."], response[2]
+ get("/bukkits/foo")
+ assert_equal "Helped.", last_response.body
- env = Rack::MockRequest.env_for("/bukkits/routes_helpers_in_view")
- response = AppTemplate::Application.call(env)
- assert_equal ["/bukkits/foo, /bar"], response[2]
+ get("/bukkits/routes_helpers_in_view")
+ assert_equal "/bukkits/foo, /bar", last_response.body
- env = Rack::MockRequest.env_for("/bukkits/polymorphic_path_without_namespace")
- response = AppTemplate::Application.call(env)
- assert_equal ["/bukkits/posts/1"], response[2]
+ get("/bukkits/polymorphic_path_without_namespace")
+ assert_equal "/bukkits/posts/1", last_response.body
end
test "isolated engine should avoid namespace in names if that's possible" do
@@ -541,9 +555,8 @@ module RailtiesTest
boot_rails
- env = Rack::MockRequest.env_for("/bukkits/posts/new")
- response = AppTemplate::Application.call(env)
- assert rack_body(response[2]) =~ /name="post\[title\]"/
+ get("/bukkits/posts/new")
+ assert_match /name="post\[title\]"/, last_response.body
end
test "loading seed data" do
@@ -612,16 +625,14 @@ module RailtiesTest
end
RUBY
- require 'rack/test'
- extend Rack::Test::Methods
-
boot_rails
require "#{rails_root}/config/environment"
- get "/foo"
+
+ get("/foo")
assert_equal "foo", last_response.body
- get "/bukkits/bar"
+ get("/bukkits/bar")
assert_equal "bar", last_response.body
end
@@ -721,5 +732,74 @@ module RailtiesTest
engine_path = File.join(@plugin.path, '..', engine_dir)
assert_equal Bukkits::Engine.instance, Rails::Engine.find(engine_path)
end
+
+ test "ensure that engine properly sets assets directories" do
+ add_to_config("config.action_dispatch.show_exceptions = false")
+ add_to_config("config.serve_static_assets = true")
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "public/stylesheets/foo.css", ""
+ @plugin.write "public/javascripts/foo.js", ""
+
+ @plugin.write "app/views/layouts/bukkits/application.html.erb", <<-RUBY
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag :all %>
+ <%= yield %>
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/home_controller.rb", <<-RUBY
+ module Bukkits
+ class HomeController < ActionController::Base
+ def index
+ render :text => "Good morning!", :layout => "bukkits/application"
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ match "/home" => "home#index"
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount Bukkits::Engine => "/bukkits"
+ end
+ RUBY
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ boot_rails
+
+ require "#{rails_root}/config/environment"
+
+ assert_equal File.join(@plugin.path, "public"), Bukkits::HomeController.assets_dir
+ assert_equal File.join(@plugin.path, "public/stylesheets"), Bukkits::HomeController.stylesheets_dir
+ assert_equal File.join(@plugin.path, "public/javascripts"), Bukkits::HomeController.javascripts_dir
+
+ assert_equal File.join(app_path, "public"), ActionController::Base.assets_dir
+ assert_equal File.join(app_path, "public/stylesheets"), ActionController::Base.stylesheets_dir
+ assert_equal File.join(app_path, "public/javascripts"), ActionController::Base.javascripts_dir
+
+ get "/bukkits/home"
+
+ assert_match %r{bukkits/stylesheets/foo.css}, last_response.body
+ assert_match %r{bukkits/javascripts/foo.js}, last_response.body
+ end
+
+ private
+ def app
+ Rails.application
+ end
end
end
diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb
index 6d194eecba..7ea8364ae9 100644
--- a/railties/test/railties/railtie_test.rb
+++ b/railties/test/railties/railtie_test.rb
@@ -21,10 +21,10 @@ module RailtiesTest
test "Railtie provides railtie_name" do
begin
- class ::Foo < Rails::Railtie ; end
- assert_equal "foo", ::Foo.railtie_name
+ class ::FooBarBaz < Rails::Railtie ; end
+ assert_equal "foo_bar_baz", ::FooBarBaz.railtie_name
ensure
- Object.send(:remove_const, :"Foo")
+ Object.send(:remove_const, :"FooBarBaz")
end
end
diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb
index 31ba2eaca2..3eb79d57c8 100644
--- a/railties/test/railties/shared_tests.rb
+++ b/railties/test/railties/shared_tests.rb
@@ -294,7 +294,7 @@ YAML
boot_rails
- assert_equal %W(
+ expected_locales = %W(
#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml
#{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml
#{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml
@@ -302,7 +302,13 @@ YAML
#{@plugin.path}/config/locales/en.yml
#{app_path}/config/locales/en.yml
#{app_path}/app/locales/en.yml
- ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) }
+ ).map { |path| File.expand_path(path) }
+
+ actual_locales = I18n.load_path.map { |path|
+ File.expand_path(path)
+ } & expected_locales # remove locales external to Rails
+
+ assert_equal expected_locales, actual_locales
assert_equal "2", I18n.t(:foo)
assert_equal "1", I18n.t(:bar)